﻿
var SearchSuggestCol = new Array();

function SearchSuggest(pSearchForm) {
    // Parameters
    this.MySearchForm = pSearchForm;
    this.SearchBox = null
    this.Index = null
    this.LastKeyPressed = null
    this.Keywords = null
    this.ResultsPanel = null
    this.CurrentResultItemNo = null
    this.KeywordsSpan = null
    this.SearchButton = null
    this.SearchProgress = null
    this.SelectedEntries = 0
    this.ResultItemCount = null
    this.SelectedRecordIds = ""
    this.CountResultItemsSpan = null
    this.ResultItems = null
    this.SearchComponent = null
    this.SelectionContainer = null
    this.CommentWidth = null;
    this.ResultWidth = null
    this.SelectionTextBox = null
    this.AddEntryDiv = null
    this.SelectionNameLabel = ""
    this.MaxSelections = null
    this.TotalMatches = null;
    this.CountResultItems = function () { return $(this.MySearchForm).find(".ResultItem").length }
    this.CountEntries = function () { return $(this.MySearchForm).find(".SelectedEntry").length }
    // ---------------

    // functions
    // /////////////////////////////////// Result select funnction
    this.ShowResult = function () {

        //alert(this.Index + " of " + this.CountResultItems);
        if (this.CurrentResultItemNo != null) {
            var ResultItem = this.ResultItems[this.CurrentResultItemNo];
            $(ResultItem).removeHighlight();
            $(this.SearchBox).val(ResultItem.Result.Title);
            
            //we have the ResultItem object all result details
            //alert('selected Name=' + ResultItem.Result.Title + ' | ' + ' id=' + ResultItem.Result.id);
            this.AddSelected(ResultItem.Result.Title, ResultItem.Result.id);
            $(this.SearchBox).val('');
            //alert($(this.MySearchForm).find(".SelectedEntry").length + " of " + this.MaxSelections);
            if ($(this.MySearchForm).find(".SelectedEntry").length < this.MaxSelections) {
                this.SearchBox.focus();

            }
            $(this.ResultsPanel).addClass('hidden');
        }
    }
    // ------------------------------------ end of Select function

    this.Prepare = function () {
        me = this
        this.Index = SearchSuggestCol.length - 1;


        this.SearchBox = $(this.MySearchForm).find(".SearchBox"); //.find("input[id$=SearchBox]");
        this.SearchComponent = $(this.MySearchForm).find(".SearchComponent"); //.find("input[id$=SearchBox]");

        this.SelectionContainer = $(this.MySearchForm).find(".SelectionContainer");
        $(this.SearchBox).attr("index", this.Index);
        this.ResultsPanel = $(this.MySearchForm).find(".ResultsPanel");
        $(this.ResultsPanel).attr("index", this.Index);

        
        this.SelectionTextBox = $(this.MySearchForm).find(".SelectionTextBox");
        this.SelectedRecordIds = $(this.MySearchForm).find(".SelectionTextBox");
        this.SelectionNameLabel = $(this.MySearchForm).find(".SelectionNameLabel");
        
        //alert($(p).width());

        //alert("top:" + position.top + ", left:" + position.left + ", width:" + $(p).width() + ", height:" + $(p).height());
        //alert($(this.SelectionContainer).height());


        //alert(this.ResultWidth);
        //$(this.ResultsPanel).left($(p).left());
        //var SearchComponent = $(this.SearchComponent).height();
        //SearchComponent = SearchComponent + 7 + $(this.SearchComponent).css("padding");
        //alert(SearchComponent); //.replace("px", "") + parseInt($(this.SearchBox).css("padding").replace("px", "")))
        //$(this.ResultsPanel).css("margin-top", SearchComponent);

        this.TotalMatches = $(this.MySearchForm).find(".TotalMatches");
        this.MaxSelections = $(this.MySearchForm).find(".MaxSelectionsTextBox").val();
        this.CommentWidth = $(this.MySearchForm).find(".CommentWidth").val();
        this.AddEntryDiv = $(this.MySearchForm).find("#AddEntryDiv");
        this.CountResultItemsDiv = $(this.MySearchForm).find("#CountResultItemsDiv");
        this.KeywordsSpan = $(this.MySearchForm).find(".KeywordsSpan");
        this.SearchButton = $(this.MySearchForm).find("#SearchButton");
        this.SearchProgress = $(this.MySearchForm).find(".SearchProgress");
        //$(this.SearchProgress).left(
        $(this.SearchBox).attr("SearchIndex", this.Index);
        this.ResultItems = new Array();
        
        this.SelectedIndex = $(this.MySearchForm).find("#SelectedIndex");
    };        // end of Prepare


//    this.RemoveSelected = function (id) {


//        //var element = $(id);



//        //$(this.SelectionContainer).append(newelement);
//        //$(newelement).fadeIn('fast');

//        //$(this.SelectionContainer).remove(element);

////        var arr = new Array();
////        arr = jQuery.grep(arr, function (value) {
////            return value != removeItem;
////        });
//    }



    this.AddSelected = function (str, id) {


        //alert($(this.SelectionTextBox).val());

        if (CheckExistArray($(this.SelectionTextBox).val(), id) == true) {
            alert(str + " has already been selected.");
        }
        else {
            var elementid = S4();

            this.SelectedEntries = this.SelectedEntries + 1;
            var newelement = document.createElement("div");
            $(this.SelectionTextBox).val($(this.SelectionTextBox).val() + id.toString() + "|");
            $(this.SelectionNameLabel).text($(this.SelectionNameLabel).text() + str.toString() + ", ");


            newelement.setAttribute('SelectedId', id);
            newelement.setAttribute('SelectedName', str);
            newelement.setAttribute('SearchBox', $(this.SearchBox).attr("id"));
            newelement.setAttribute('SelectionTextBox', $(this.SelectionTextBox).attr("id"));
            newelement.setAttribute('SelectionNameLabel', $(this.SelectionNameLabel).attr("id"));
            //newelement.setAttribute('form', $(this.MySearchForm).attr("id"));
            newelement.setAttribute('id', 'selection_' + elementid);
            newelement.setAttribute('class', 'SelectedEntry');
            //newelement.setAttribute('style', 'cursor:pointer');
            newelement.innerHTML = str + "&nbsp;<img src='http://www.technologytradingpost.com/images/delete.gif' class='DeleteEntryImage'></a>";

            newelement.setAttribute("onclick", "RemoveSelected('" + str + "','" + $(this.SelectionTextBox).val() + "','" + $(this.SelectionContainer).attr("id") + "','selection_" + elementid + "')");
            //newelement.setAttribute("onclick", "$('" + this.SelectionContainer + "').remove('selection_" + this.SelectedEntries + "');");
            newelement.setAttribute('style', 'display:none;');
            $(this.SelectionContainer).append(newelement);
            //newelement.setAttribute("onclick", this.RemoveSelected2(event, 'selection_0'));
            $(newelement).fadeIn('fast');

            //this.SelectedRecordIds = this.SelectedRecordIds + "|" + id.toString();

            //alert(this.SelectedRecordIds);

            //        var divname = document.createElement('div');

            //$(this.SearchComponent).append("div").addClass("selectedorganizationoutline").val(str);

            //        divname.setAttribute('id', 'selection_0');
            //        divname.setAttribute('class', 'selectedorganizationoutline');
            //        divname.setAttribute('style', 'cursor:pointer');
            //        divname.innerHTML = str + "&nbsp;<img src='../../images/delete.gif' class='DeleteEntryImage'></a>";
            //        //divname.setAttribute("onclick", "RemoveEntry('selection_" + count + "')");
            //        document.getElementById(this.SearchComponent).appendChild(divname);

            //alert($(this.MySearchForm).find(".SelectedEntry").length + " of " + this.MaxSelections);
            if ($(this.MySearchForm).find(".SelectedEntry").length >= this.MaxSelections) {
                $(this.AddEntryDiv).slideUp();
                //$(this.SearchProgress).hide();
                //alert("You may only make " + MaxSelections + " selection/s");
            }
            else {
                $(this.AddEntryDiv).show();
            }
        }
    }

    
//    this.NoResults = function () {
//        var NewResultsCategory = "<div class='ResultsCategory' index='0'></div><div id='ResultsArea0_0' class='Results' >None</div><div class='clear:both'></div>";
//        //$(this.ResultsPanel).find(".ResultsContent").append(NewResultsCategory);
//        //var ResultsArea = $("#ResultsArea" + this.Index + "_" + CategoryId);
//        var ResultsArea = $("#ResultsArea0_0");
//        $(ResultsArea).html(NewResultsCategory);
//    }

    this.NavigateResults = function (MoveNext) {
        if (MoveNext) {
            this.HighlightNextResultItem(); return false
        }
        else {
            this.HighlightPreviousItem(); return false
        }
        
    }
    this.HighlightNextResultItem = function () {

        
        if (this.CurrentResultItemNo < this.CountResultItems() - 1 || this.CountResultItems() == 1) {
            if (this.CurrentResultItemNo == null) { this.CurrentResultItemNo = 0; }
            else if (this.CurrentResultItemNo == this.CountResultItems()) { }
            else { this.CurrentResultItemNo++ }
            this.SelectResultItem(this.CurrentResultItemNo)
        }

    }           // end of HighlightNextResultItem

    this.HighlightPreviousItem = function () {
        if (this.CurrentResultItemNo >= 0) {
            if (this.CurrentResultItemNo == null) { }
            else if (this.CurrentResultItemNo == 0) { this.CurrentResultItemNo = null; }
            else { this.CurrentResultItemNo-- }
            this.SelectResultItem(this.CurrentResultItemNo);
        }
    }

    this.SelectResultItem = function (pItemToSelect) {
        $(this.ResultsPanel).find(".ResultItem").removeClass("ResultOver");
        var ResultPanels = $(this.ResultsPanel).find(".ResultItem");
        $(ResultPanels[this.CurrentResultItemNo]).addClass("ResultOver");
    }

    this.Suggest = function () {
        me = this;
        this.Keywords = $(this.SearchBox).val();
        this.Keywords = StripHTML(this.Keywords,1000);
        if (this.Keywords == "") {
            this.HideResultsPanel(true);
            this.HideSearchProgress(true);
        } else {
            this.HideSearchProgress(false);

            if (this.KeywordsSpan != undefined) {
                $(this.KeywordsSpan).html(this.Keywords);
                $(this.SearchButton).val("Search for " + this.Keywords);
                //NoResults();
            }
            var Keywords = this.Keywords;
            var SearchIndex = this.Index;
            $.ajax({
                type: "POST",
                datatype: "json",
                url: "http://www.technologytradingpost.com/searchsuggest/searchsuggestloc.aspx?pKeywords=" + Keywords,
                success: function () { me.RequestSuccess(); },
                //error: function (jqXHR, textStatus, errorThown) { alert( errorThown) },
                complete: function (data) {
                    me.RecieveData(data);
                    //var total = data.length();
                    //alert(total);
                }
                
            });
            return true;
        }
        

    }            // end of Suggest

    this.HideResultsPanel = function (Hide) {
        if (Hide == true) {
            $(this.ResultsPanel).addClass('hidden');
        } else {
            var p = this.SelectionContainer;
            var position = p.position();

            $(this.ResultsPanel).width($(p).width());

            this.ResultWidth = $(p).width() - 102;
            $(this.ResultsPanel).removeClass('hidden');



        };
       

        this.CurrentResultItemNo = null;
    }      // end of HideResultsPanel

    this.HideSearchProgress = function (Hide) {
        if (Hide == true) {
            $(this.SearchProgress).addClass('hidden');
        } else {
            $(this.SearchProgress).removeClass('hidden');
        }
    } // end of HideResultsPanel

    this.RequestSuccess = function () {
        this.HideSearchProgress(true);
        this.HideResultsPanel(false);
    }



    this.RecieveData = function (data) {
        this.HideSearchProgress(true);
        this.HideResultsPanel(false);
        //this.Results = null;
        this.ResultItems = new Array();
        try {
            var Response = $.parseJSON(data.responseText); // convert the recieving json data into a usable object
            $(this.ResultsPanel).find(".ResultsContent").html("");
            // loop through each category

            for (CategoryId = 0; CategoryId <= Response.Categories.length - 1; CategoryId++) {

                var CatName = "Cat" + CategoryId;

                // loop through each result and populate it
                var NewResultsCategory = "<div class='ResultsCategory'  index='" + CategoryId + "'>" + Response.Categories[CategoryId].Name + "</div><div id='ResultsArea" + this.Index + "_" + CategoryId + "' class='Results' ></div><div class='clear:both'></div>";
                $(this.ResultsPanel).find(".ResultsContent").append(NewResultsCategory).css("width", this.ResultWidth);
                var ResultsArea = $("#ResultsArea" + this.Index + "_" + CategoryId);
                $(ResultsArea).html("");

                for (i = 0; i <= Response.Results.length - 1; i++) {
                    if (Response.Results[i].Category == Response.Categories[CategoryId].Name) {
                        this.ResultItems[this.ResultItems.length] = new ResultItem(ResultsArea, Response.Results[i], (i == Response.Results.length + 1), this.ResultItems.length,this.CommentWidth);
                    }
                }

                var me = this;
                $(ResultsArea).find(".ResultItem").mouseover(function () { $(".ResultItem").removeClass("ResultOver"); $(this).addClass("ResultOver").css("width", this.ResultWidth); me.CurrentResultItemNo = $(this).attr("index"); });
                $(ResultsArea).find(".ResultItem").click(function () {
                    me.CurrentResultItemNo = $(this).attr("index");
                    me.ShowResult();
                });

                

            } // end of for categories 
            this.HideResultsPanel(Response.Results.length = 0);
            //alert(this.Keywords);
            if (this.Keywords != "") {
                this.HighlightKeywords();
            }
            
            //alert($(p).width());

        } catch (err) {
            this.SearchUnavailable(); 
        }
    }                        // end of RecieveData

    this.SearchUnavailable = function () { this.HideSearchProgress(true); $(".ResultsContent").css("width", this.ResultWidth).html("<span class='SearchUnavail'>" + this.Index + " Search suggest unavailable</span>"); this.HideResultsPanel(false); }    // what to do if search is unavail
    this.HighlightKeywords = function () {
        //if (this.keywords != "") {
        //alert();
        //$(this.CountResultItemsDiv).html(this.CountResultItems() + " of " + this.TotalMatches);
        $(this.CountResultItemsDiv).html(this.CountResultItems());
        $(".ResultTitle").highlight(this.Keywords);
     
        //}

    }
   
    
} // end of search suggest



function ResultItem(ResultsArea, Result, isLastResult, index, CommentWidth) {
    this.Result = Result;
    var Resulthtml = "<div id='ResultItem" + i + "' class='ResultItem' index='" + index + "'>";
    if (Result.ImageURL != "") {
        Resulthtml += "<img src='http://www.technologytradingpost.com/storage/organization/" + Result.OrganizationId + "/" + Result.ImageURL + "?maxwidth=12px&maxheight=12' align='left' style='border:none !important'  />";
    } else {
        Resulthtml += "<img src='http://www.technologytradingpost.com/images/blank.gif' style='height:0px;width:12px;border:none !important' align='left' />";
        //Resulthtml += "<div style='width:12px;float:left'></div>";
    }
   // $(this.TotalMatches).html("hoi");
    //
//    if (Result.Title.Length > 100) {
//        Resulthtml += "<div class='ResultTitle'><marquee behavior='scroll' scrollamount='3' direction='left'>" + StripHTML(Result.Title) + "</marquee></div><div class='ResultText'>" + StripHTML(Result.ResultText) + "</div></div>";
//    }
    //    else {
    Resulthtml += "<div ><span class='ResultTitle'>" + StripHTML(Result.Title, 100) + " " + StripHTML(Result.CustomString, 100) + "</span></div><div class='ResultText' style='margin-left:21px;'>" + StripHTML(Result.ResultText, CommentWidth) + "</div></div>";
    //    }
    var total = Result.TotalMatches;
    $(ResultsArea).append(Resulthtml);
    $(this.TotalMatches).html(total);
    if (isLastResult == true) {
        
        $('#OrgResultItem' + i).addClass("BottomBorder");
    }
    //alert(Result.TotalMatches);
    
}


//function ShowAddEntry(elem) {
//    $(this.AddEntryDiv).toggle();
//}

// --------------- proxy functions

function KeyUpProxy(Key, elem) {
    
    var code = (Key.keyCode ? Key.keyCode : Key.which);
    // handle keypresses.
    
    if (code == 13) {
       
        SearchSuggestCol[$(elem).attr("SearchIndex")].ShowResult();
        return false;
    } else {
        return true;
        
        //SearchSuggestCol[$(elem).attr("SearchIndex")].Suggest();
    }
}
function Suggest(e) {

    var code = (e.keyCode ? e.keyCode : e.which);
    //alert(code);


    if (code == '40') {

        SearchSuggestCol[e.srcElement.attributes["index"].value].NavigateResults(true);
    }
    else if (code == '38') { SearchSuggestCol[e.srcElement.attributes["index"].value].NavigateResults(false); }
    else if (code != '13') {



        SearchSuggestCol[e.srcElement.attributes["index"].value].Suggest();
       
    }
}


$(document).ready(function () {
    
    $(".SearchComponent").each(function () {
        AddSearchForm(this);
    });
    $(document).click(function () { HideAllSearchResults(); })
    //alert("ready");
    //$(".ResultTitle").mouseover(function () {
    //alert($(this).val());
    // $(this).replace($(this).val(), "hi");
    //});
    this.MySearchForm = this; 
    this.SelectionContainer = $(this.MySearchForm).find("#SelectionContainer");

    $(this.SelectionContainer).click(function () {
        //$(this.SelectionContainer).click(function () {
        //alert("hi");
    });

//    var child = document.getElementById(childDiv);
//    var parent = document.getElementById(parentDiv);
//    var text = $(child).text();
//    

    //    $(ResultsArea).find(".SelectedEntry").click(function () {
//        //me.CurrentResultItemNo = $(this).attr("index");
//        //me.ShowResult();
//        alert("kk");
//    });

});


// add a search form to the forms collection as the SearchSuggest object.
function AddSearchForm(Form) {
    SearchSuggestCol[SearchSuggestCol.length] = new SearchSuggest(Form);
    SearchSuggestCol[SearchSuggestCol.length - 1].Prepare();
}

function HideAllSearchResults() {
    for (i = 0; i <= SearchSuggestCol.length - 1; i++) {
        SearchSuggestCol[i].HideResultsPanel(true);
    } 
}

function StripHTML(str,le) {
    //alert(le);
    var str = html_stripped = str.replace(/(<.*?>)/ig, "");
    if (str.length >= le) {
        str = str.substring(0, le) + "...";
    }
    return str;
};

function CheckExistArray(arr,selection) {

    var SelectedEntries = arr;
    var col_array = SelectedEntries.split("|");
    var truefalse = false;
    for (i = 0; i < col_array.length; i++) {

        if (col_array[i] != undefined) {
            if (col_array[i] != "") {


                if (col_array[i].trim() == selection.trim()) {
                    truefalse = true;
                }

            }

        }

    }
    return truefalse;
}

function RemoveFromArray(arr, selection,seperator) {

    var SelectedEntries = arr;
    var col_array = SelectedEntries.split(seperator);
    var newarr = "";
    for (i = 0; i < col_array.length; i++) {

        if (col_array[i] != undefined) {
            if (col_array[i] != "") {
                if (col_array[i].trim() != selection.trim()) {

                    newarr += col_array[i].trim() + seperator;
                }
            }
        }
    }
    return newarr;
}


function RemoveSelected(str,selected, parentDiv, childDiv) {
    //alert("parent:" + parentDiv + ", child:" + childDiv);
    var child = document.getElementById(childDiv);
    var parent = document.getElementById(parentDiv);
    var text = $(child).text();
    var SelectionTextBoxattr = $(child).attr('SelectionTextBox');
    var SelectionNameLabelattr = $(child).attr('SelectionNameLabel');
    
    var SearchBoxattr = $(child).attr('SearchBox');
    var formattr = $(child).attr('form');
    var selectedidattr = $(child).attr('selectedid');
    $(child).fadeOut('fast');
    //alert(child);
    parent.removeChild(child);
    //alert(attr);
    //alert(SelectionTextBoxattr);
    //setTimeout("parent.removeChild(child);", 2000);
    //$(parent).remove(child);

    //this.SelectionTextBox = $(formattr).find(".SelectionTextBox");
    //alert(text);
    //alert(selected);
    //alert(formattr);
    //$('#' + SelectionTextBoxattr).val('hi');
    $('#' + SelectionTextBoxattr).val(RemoveFromArray($('#' + SelectionTextBoxattr).val(), selectedidattr,"|"));
    $('#' + SelectionNameLabelattr).text(RemoveFromArray($('#' + SelectionNameLabelattr).text(), str,", "));

    $(this.AddEntryDiv).slideDown();
    $('#' + SearchBoxattr).focus();
}

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}



$(document).ready(function () {

    $('.SelectedEntry').click(function (event) {

        var TargetSelection = $(event.target).attr('id');
        var SelectedRecordId = $(event.target).attr('selectedid');
        var ParentContainer = $(event.target).closest('.SelectionContainer').attr('id');
        var SelectionTextBoxattr = $(event.target).attr('SelectionTextBox');
        var SelectedText = $(event.target).text();
        //alert(SelectedText + ' - ' + TargetSelection + " in " + ParentContainer);
        $('#' + ParentContainer + " #" + TargetSelection).remove();

        $('#' + SelectionTextBoxattr).val(RemoveFromArray($('#' + SelectionTextBoxattr).val(), SelectedRecordId, "|"));
        //$('#' + SelectionNameLabelattr).text(RemoveFromArray($('#' + SelectionNameLabelattr).text(), str, ", "));
    });

});
