﻿var currentSelection = -1;
var currentUrl = '';
var currentPageNo2 = 1;
var xmlResult = "";
var xmlQuery = "";

/*function HighLightLink(obj, listName) {
$(obj).parent().children().removeClass("SelectedPage").addClass("notSelectedPage");
$(obj).removeClass("notSelectedPage").addClass("SelectedPage");
}*/

function PageClick(pageNo, pageSize, query, category) {
    currentPageNo2 = pageNo;

    var currentCultureDiv = $("#CurrentCulture");
    var currentCulture = "sv";
    if (currentCultureDiv != null) {
        currentCulture = $(currentCultureDiv).text().trim();
    }

    $.ajax({
        type: "POST",
        url: "/generichandlers/LoadPagedSearchResult.ashx?pageNo=" + pageNo + "&pageSize=" + pageSize + "&query=" + query + "&category=" + category + "&CurrentCulture=" + currentCulture,
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json/text",
        error: function(msg) {
            //alert(msg);
        },
        success: function(msg) {
            var jsonValue = (new Function("return(" + msg + ");"))();
            var serviceList = document.getElementById(category + 'Area');
            //alert(serviceList);

            // Delete all the options previously loaded.
            $(serviceList).find('div').remove();

            for (var i = 0; i < jsonValue.length; i++) {
                //alert(jsonValue.length);
                //Search result Item
                var mainItem = document.createElement('div');
                mainItem.className = 'searchItem';

                var itemIcon = '';
                if (typeof (jsonValue[i].imgURL) !== 'undefined' && jsonValue[i].imgURL != null) {
                    itemIcon = jsonValue[i].imgURL;
                }

                // Image
                var iconDiv = document.createElement('div');
                iconDiv.className = 'searchItemIcon';
                var icon = document.createElement('img');
                icon.src = itemIcon;
                iconDiv.appendChild(icon);

                //Text
                var itemText = '';
                if (typeof (jsonValue[i].text) !== 'undefined' && jsonValue[i].text != null) {
                    itemText = jsonValue[i].text;
                }

                var itemDescription = '';
                if (typeof (jsonValue[i].title) !== 'undefined' && jsonValue[i].title != null) {
                    itemDescription = jsonValue[i].title;
                }

                var textDiv = document.createElement('div');
                textDiv.className = 'searchItemText';
                textDiv.innerHTML = '<a href=\"' + jsonValue[i].url + '\">' + itemDescription + '</a><br />' + itemText; //jsonValue[i].text;

                mainItem.appendChild(iconDiv);
                mainItem.appendChild(textDiv);
                serviceList.appendChild(mainItem);
            }
        }
    });

    return false;
}

var loadingAJAX = false;

function loadXMLDoc(query, obj) {

    if (query.length < 3 && loadingAJAX)
        return;

    loadingAJAX = true;
    // Fix för åäö
    query = encodeURIComponent(query);

    var currentCultureDiv = $("#CurrentCulture");
    var currentCulture = "sv";

    if (currentCultureDiv != null) {
        currentCulture = $(currentCultureDiv).text().trim();
    }


    $.ajax({
        type: "POST",
        url: "/GenericHandlers/SearchHandler.ashx?query=" + query + "&CurrentCulture=" + currentCulture,
        dataType: "xml",
        success: function(xml) {
            parseXML(xml, query, obj);
            

        },
        error: function(xhr, ajaxOptions, thrownError) {
            //alert(xhr.status);
            //alert(thrownError);

            xmlQuery = "";
            xmlResult = "";
        }
        
    });
//return xmlResult;
}
function parseXML(xml, query, obj) {
    xmlResult = "";
    var resultat = ""
    var resultat1 = "<h2>Erbjudanden</h2><ul>";
    var resultat2 = "<h2>Företagsinformation</h2><ul>";
    var resultat1Count = 0;
    var resultat2Count = 0;

    var currentCultureDiv = $("#CurrentCulture");
    var currentCulture = "sv";
    if (currentCultureDiv != null) {
        currentCulture = $(currentCultureDiv).text().trim();
    }

    currentCulture = currentCulture.substring(0, 2)

    // Autocomplete
    xmlQuery = $(xml).find('Q').text();
   

    $(xml).find('R').each(function() {
        var id = $(this).attr('N');
        var title = $(this).find('T').text();
        var url = $(this).find('U').text();
        var desc = $(this).find('S').text();
        //desc = desc.substring(6, 73);


        //var check = title.indexOf("Softronic");

        category = "CompanyInfo";

        var MTCategory = $(this).find('MT').attr("V");

        var MTImageUrl = $(this).find('MT').next().attr("V");
        //if (MTImageUrl == null) MTImageUrl = "/ClientUI/TEMP/soft.gif";

        if (MTCategory != null) category = MTCategory;
        if (title != "" && url != "" && desc != "") {
            //            if (category == "Offers" && resultat1Count < 4 && (resultat2Count + resultat1Count) < 8) {
            //                if (MTImageUrl == null) MTImageUrl = "/ClientUI/TEMP/kuggar.gif";
            //                resultat1 = resultat1 + '<li><img src="'+MTImageUrl+'"/><div class="searchItemSmall"><h2><a href="' + url + '">' + title + '</a></h2>' + desc + '</div></li>';
            //                resultat1Count++;
            //            }
            
            /*** Prioritering av erbjudanden   ***********/
            if (category == "Offers" && resultat1Count < 4) {
                if (resultat2Count + resultat1Count < 8) {
                    if (MTImageUrl == null) MTImageUrl = "/ClientUI/TEMP/kuggar.gif";
                    resultat1 = resultat1 + '<li><img src="' + MTImageUrl + '"/><div class="searchItemSmall"><h2><a href="' + url + '">' + title + '</a></h2>' + desc + '</div></li>';
                    resultat1Count++;
                }
                else if (resultat2Count > 4) {

                    var t = $(resultat2);

                    var list = t.find("li");

                    var index = 0;
                    list = $.map(list, function(a) {
                        if (index == list.length - 1) {
                            return null;
                        }
                        index++;
                        return a;

                    });
                    resultat2Count--;

                    resultat2 = "<h2>Företagsinformation</h2><ul>";
                    var res = "";
                 
                    $(list).each(function() {
                        res = res + "<li>" + $(this).html() + "</li>";
                    });
               
                    resultat2 = resultat2 + res;

                    if (MTImageUrl == null) MTImageUrl = "/ClientUI/TEMP/kuggar.gif";
                    resultat1 = resultat1 + '<li><img src="' + MTImageUrl + '"/><div class="searchItemSmall"><h2><a href="' + url + '">' + title + '</a></h2>' + desc + '</div></li>';
                    resultat1Count++;
                }
            }
            /////////////*********************////////////////////////////
            else if ((resultat2Count + resultat1Count) < 8 && category != "Offers") {
                if (MTImageUrl == null) MTImageUrl = "/ClientUI/TEMP/soft.gif";
                resultat2 = resultat2 + '<li><img src="' + MTImageUrl + '"/><div class="searchItemSmall"><h2><a href="' + url + '">' + title + '</a></h2>' + desc + '</div></li>';
                resultat2Count++;
            }
        }

    });

    var responsText = "inga sökresultat hittades";
    if (currentCulture == "en") {
        responsText = "no searchresults found"
    }

    if ((resultat1Count > 0 && resultat2Count > 0)) {

        resultat = resultat1 + "</ul>" + resultat2 + "<div style='height:30px;' class='allResult'><h2 style='float:right;'><a href='/" + currentCulture + "/Utanfor-strukturen/Sok/?query={" + xmlQuery + "}'>Se alla sökresultat<img src='/ClientUI/Images/arrowGray.png'/></a></h2></div>";
    }
    else if (resultat1Count > 0 && resultat2Count == 0) {
        resultat = resultat1 + "<div style='height:30px;' class='allResult'><h2 style='float:right;'><a href='/" + currentCulture + "/Utanfor-strukturen/Sok/?query={" + xmlQuery + "}'>Se alla sökresultat<img src='/ClientUI/Images/arrowGray.png'/></a></h2></div>";
    }
    else if (resultat1Count == 0 && resultat2Count > 0) {
        resultat = resultat2 + "<div style='height:30px;' class='allResult'><h2 style='float:right;'><a href='/" + currentCulture + "/Utanfor-strukturen/Sok/?query={" + xmlQuery + "}'>Se alla sökresultat<img src='/ClientUI/Images/arrowGray.png'/></a></h2></div>";
    } 

    else {
        resultat = "<h2 style='float:right;'><a href='/" + currentCulture + "/Utanfor-strukturen/Sok/?query={" + xmlQuery + "}'>" + responsText + "</a></h2>";
    }

    $(obj).parent().parent().find(".AutoComplete").html(resultat);
    $(obj).parent().parent().find(".AutoComplete").css("visibility", "visible");
    $(obj).parent().parent().find(".AutoComplete").slideDown("slow");


    /*
    // IE7 fix
    var ie = $.browser.version;
    if (ie == 7) {
        var highestZindex = 0;
        var zIndexNumber = 1000;
        $('div').each(function() {
            $(this).css('zIndex', zIndexNumber);
             zIndexNumber -= 10;

            var zIndex = $(this).css('zIndex');
            if (zIndex > highestZindex) {
                highestZindex = zIndex;

            }
        });
        //$(".AutoComplete").css('zIndex', highestZindex + 10);
        //$(".customerCaseWrapper").css('zIndex', highestZindex - 10);

    }
    */

    //$("#AutoComplete").slideDown("slow");

    loadingAJAX = false;
}


//$(document).ready(function () {
function SearchLoad(){
    var currentCultureDiv = $("#CurrentCulture");
    var currentCulture = "sv";
    var currentSearchText = $($("#searchBoxTextTranslationDiv")).text();

    if (currentCultureDiv != null) {
        currentCulture = $(currentCultureDiv).text().trim();
    }
    currentCulture = currentCulture.substring(0, 2)

    var slideUpCheck = true;

    $(".AutoComplete").click(function (event) {

        var $elem = $(event.target).closest("li");

        if ($elem.length) {
            window.location = $(event.target).closest("li").find(".searchItemSmall").find("h2").find("a").attr("href");
        }
    });


    $(".searchPager a").click(function () {

        $(this).parent().children().removeClass("SelectedPage").addClass("notSelectedPage");
        $(this).removeClass("notSelectedPage").addClass("SelectedPage");

    });
    $('.searchPager').children(":first-child").addClass("SelectedPage");

    $('.searchBoxInput').focus(function () {
        var input = $(this).val();
        if (input == currentSearchText) { $(this).val(''); }
        if (input != currentSearchText && input != '') { $(this).parent().parent().find(".AutoComplete").slideDown("slow"); }
    });
    $('.searchBoxInput').blur(function () {

        $(this).val(currentSearchText);
        if (slideUpCheck == false) {
            //alert("jaa");
            $(this).parent().parent().find(".AutoComplete").slideUp("slow");
            currentSelection = -1;
        }
    });

    $('.AutoComplete').mouseover(function () {
        slideUpCheck = true;
    });
    $('.AutoComplete').mouseout(function () {
        slideUpCheck = false;
    });


    $('.searchBoxInput').bind('keyup', function (e) {

        var query = $(this).val();

        if (e.keyCode == 38 || e.keyCode == 40 || e.keyCode == 13 || e.keyCode == 8) {
            switch (e.keyCode) {
                // User pressed "up" arrow                                                  
                case 38:
                    //alert("up");
                    navigate('up');
                    break;
                // User pressed "down" arrow                                                 
                case 40:
                    //alert("down");
                    navigate('down');
                    break;
                // User pressed "enter"                               
                case 8:
                    //alert("backspace");
                    //if (query.length > 2) loadXMLDoc(query);
                    if (query.length < 3) $(this).parent().parent().find(".AutoComplete").slideUp("slow");
                    //alert(query);
                    break;
                case 13:
                    if (currentUrl != '') {
                        window.location = currentUrl;
                    }
                    else {
                        window.location = "/" + currentCulture + "/Utanfor-strukturen/Sok/?query={" + xmlQuery + "}";

                    }

                    break;
            }
        }
        else {
            if (query.length > 2) {
                loadXMLDoc(query, this);
            }
        }
    });
    function navigate(direction) {
        // Check if any of the menu items is selected

        if (direction == 'up' && currentSelection != -1) {
            if (currentSelection != 0) {
                currentSelection--;
            }
        } else if (direction == 'down') {
            if (currentSelection != $(".AutoComplete ul li").size()) {
                currentSelection++;
            }
        }
        setSelected(currentSelection);
    }

    function setSelected(menuitem) {

        if (menuitem == $(".AutoComplete ul li").size()) {
            $(".AutoComplete ul li").removeClass("itemhover");
            $(".AutoComplete .allResult").addClass("itemhover");
            currentUrl = "/" + currentCulture + "/Utanfor-strukturen/Sok/?query={" + xmlQuery + "}";
        }
        else {
            $(".AutoComplete ul li").removeClass("itemhover");
            $(".AutoComplete .allResult").removeClass("itemhover");
            $(".AutoComplete ul li").eq(menuitem).addClass("itemhover");

            currentUrl = $(".AutoComplete ul li a").eq(menuitem).attr("href");
        }

    }

    $(".hideSearch img").click(function () {
        window.location = "/" + currentCulture + "/Utanfor-strukturen/Sok/?query={" + xmlQuery + "}";

    });

    // Expand / collaps searchresult items
    $(".searchCategory .showHide").toggle(function () {
        $(this).parent().next().slideUp();
        //$(this).parent().find(".searchPager").slideUp(); //.slideUp();

        if ($(this).parent().next().next().attr('class') == "searchPager") {
            $(this).parent().next().next().slideUp();
        }
    },
function () {
    $(this).parent().next().slideDown();

    if ($(this).parent().next().next().attr('class') == "searchPager") {
        $(this).parent().next().next().slideDown();
    }

});


}//);
    





  

