﻿var _nmenu_root_index = -1;
var _controlVpadding = 90;// 120;
var _searchControlStartHeight = 160;
var _nmenu_indexByURL = -1;

$(document).ready(function () {


    //------------------------------------------------------------------------------------------------
    //MENU ROOT CONTROLLER
    //------------------------------------------------------------------------------------------------
    $("#nmenuFooter").hide();

    _nmenu_indexByURL = parseInt($("#nmenu").attr("curIndex"));
    if (_nmenu_indexByURL > -1) { setRootMenuState(_nmenu_indexByURL, 0); }

    $(".nm_x_del").fadeTo(0, 0.2);
    $('.nm_x_del').hover(function () { $(this).fadeTo(0, 1); });
    $('.nm_x_del').mouseout(function () { $(this).fadeTo(0, 0.2); });
    $('.nm_x_del').mousedown(function () { nm_clearSearch(); });
    $('.nControl').hide();

    $('#nm_signIn_1').mousedown(function () {
        nm_showFavSignInPanel();
    });
    $('.nm_loginBack').mousedown(function () {
        nm_showFavLoginOptionsPanel();
    });

    $('.nitem').mousedown(function () {
        var nindex = $('.nitem').index(this);
        if (_nmenu_root_index == nindex) {
            closeRootMenu();
            stopSearch();
        }
        else {
            if (nindex != 1) { stopSearch(); }
            var allowOpen = true;
            var pageUrl = document.location.toString();
            var lurl = pageUrl.toLowerCase();
            if ((nindex == 0 || nindex == 3) && (IsHP == 'True')) { sm_toogleFooter(true); } /////only if hp!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            if ((nindex == 1 || nindex == 2) && (IsHP == 'True')) { sm_removeHpHightlight(); sm_toogleFooter(false); } /////only if hp!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            if (nindex == 1 && lurl.indexOf("/search.aspx") > 0) { allowOpen = false; } //on search page dont open search panel
            if (nindex == 2 && lurl.indexOf("/favorites.aspx") > 0) { allowOpen = false; } //on fav page dont open fav panel
            if (allowOpen) {
                openRootMenu(nindex);
                openCloseSiteTree(false); //(site_footer_tree.ascx)
            }
        }
    });
    $('.nitem').hover(function () {
        var nindex = $('.nitem').index(this);
        if (_nmenu_root_index != nindex) {
            setRootMenuState(nindex, 1);
        }
    });
    $('.nitem').mouseout(function () {
        var nindex = $('.nitem').index(this);
        if (_nmenu_root_index != nindex) {
            setRootMenuState(nindex, 0);
        }
    });
    initTreeMenus();
    nm_initSearchControl();
    nm_fixIEpng();
    setCurrentPageSubLinkSelected();
});

function setCurrentPageSubLinkSelected() {
    var pageUrl = document.location.toString();
    var lurl = pageUrl.toLowerCase();
    var isSubFound = false;
    $('.nTreeSubItem').find('a').each(function (index) {
        var linkURL = $(this).attr("href").toLowerCase();
        linkURL = linkURL.replace("../", "");
        if (lurl.indexOf(linkURL) > -1) {
            isSubFound = true;
            $(this).css("color", "#ffffff");
            $(this).closest(".nControlSubMenu").show();
            $(this).closest(".nTreeMenuItem").attr("state", "1");
            $(this).closest(".nTreeMenuItem").find(".nTreeGroupLink").find('a').css("color", _colLinkBlue);
        }
    });
    if (!isSubFound) {
        //SEARCH IN JUNCTION PAGES
        $('.nTreeGroupLink').find('a').each(function (index2) {
            var catURL = $(this).attr("id").toLowerCase();
            //if (lurl.indexOf("table.aspx") <0) {
              //  lurl = lurl.replace("table.", "table/");
            //}
            if (lurl.indexOf(catURL) > -1 && !isSubFound) {
                isSubFound = true;
                $(this).closest(".nTreeMenuItem").find(".nControlSubMenu").show();
                $(this).closest(".nTreeMenuItem").attr("state", "1");
                $(this).css("color", _colLinkBlue);
            }
        });
    }

}

function nm_fixIEpng() {
    if (jQuery.browser.msie) {
        $('#nmenuXup').css('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader');
        $(".nm_searchBtn").css('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader');
        $("#nm_signIn_1").css('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader');
        $(".nm_signUp").css('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader');
    }
}	

function setRootMenuState(index, state) {
    //state: 0:static,1:rollover,2:selected
    var nItem = $('.nitem').get(index);
    var bgW = 0;
    var bgX = 0;
    var bgY = 0;

    switch (index) {
        case 0:
            bgW = 121;
            bgX = -129;
            break;
        case 1:
            bgW = 111;
            bgX = -250;
            break;
        case 2:
            bgW = 138;
            bgX = -360;
            break;
        case 3:
            bgW = 100;
            bgX = -497;
            break;
    }

    switch (state) {
        case 0:
            bgY = 0;
            break;
        case 1:
            bgY = -60;
            break;
        case 2:
            bgY = -120;
            break;
    }

    if (index == _nmenu_indexByURL && state==0) {
        bgW = bgW - 16;
        bgY = -120; //IN CURRENT URL WE LOCK THE COLOR
    }

    $(nItem).find('a').css("width", bgW + "px");
    $(nItem).find('a').css("background-position", bgX + "px " + bgY + "px");
}

function openRootMenu(newIndex) {
    //CHECK IF MENU IS OPEN CLOSE IT FIRST
    $('.nControl').hide();
    if (_nmenu_root_index > -1) {
        setRootMenuState(_nmenu_root_index, 0);
    }
    //CHECK THE HEIGHT OF THE TARGET CONTROL:
    _nmenu_root_index = newIndex;
    if (newIndex > -1) {
        setRootMenuState(newIndex, 2);
        expendBgToFit();
    }
}
function expendBgToFit() {
    $("#nmenuFooter").show();
    var nObj = $('.nControl').get(_nmenu_root_index);
    var th = $(nObj).height();
    th = th + _controlVpadding;
    $('#nmenuBody').animate({ height: th },
    {
        easing: 'easeInOutCubic',
        duration: 700, complete: function () {
            $(nObj).fadeTo(450, 1);
            if (jQuery.browser.msie) { $("#nmenuXup").show(); nm_fixIEpng(); } else { $("#nmenuXup").fadeTo(100, 1); }
            if (_nmenu_root_index == 2) { checkFavorties(); }
        }
    });
    $('#statusVspacer').animate({ height: 45 },{easing: 'easeInOutCubic',duration: 400 });
}
function closeRootMenu() {
    if (IsHP == "True") { sm_removeHpHightlight(); }
    setRootMenuState(_nmenu_root_index, 0);
    _nmenu_root_index = -1;
    if (jQuery.browser.msie) { $("#nmenuXup").hide(); } else { $("#nmenuXup").fadeTo(100, 0); }
    $('#nmenuBody').animate({ height: 60 },
    {
        easing: 'easeInOutCubic',
        duration: 400, complete: function () { $("#nmenuXup").hide(); $("#nmenuFooter").hide(); }
    });
    $('#statusVspacer').animate({ height: 20 },{easing: 'easeInOutCubic',duration: 400 });
 }
 
 //------------------------------------------------------------------------------------
//SUB TREE MENU CONTROLLERS
//------------------------------------------------------------------------------------
var _lastSubChildren;
var _colLinkBlue = "#38c9f8";

function resetColors(parentObjIndexs) {
    if (parentObjIndexs < 0) {
        //RESET ALL MENU COLORS
        $('.nTreeGroupLink').find('a').css("color", "#ccdee5");
    }
    else {
        //RESET COLORS ONLY FOR SINGLE CONTROL (TREE)
        var nObj = $('.nControl').get(_nmenu_root_index);
        $(nObj).find('.nTreeGroupLink').find('a').css("color", "#ccdee5");
    }
}
function initTreeMenus() {
    //SET DEFAULT COLOR
    resetColors(-1);
    $('.nTreeGroupLink').find('a').hover(function () {
        var state = $(this).closest(".nTreeMenuItem").attr("state");
        if (state != "1") { $(this).css("color", _colLinkBlue); }
    });
    $('.nTreeGroupLink').find('a').mouseout(function () {
        var state = $(this).closest(".nTreeMenuItem").attr("state");
        if (state != "1") { $(this).css("color", "#ccdee5"); } //ccdee5//858f92
    });




    $('.nTreeGroupLink').mousedown(function () {
        var state = $(this).closest(".nTreeMenuItem").attr("state");
        if (state != "1") {

            //CLOSE THE LAST SUBMENU IN THE SAME CONTROL(MENU TREE)
            var expendedOldItem = $(this).closest(".nControl").find(".nTreeMenuItem:[state='1']");
            if (expendedOldItem.length > 0) {
                $(expendedOldItem).attr("state", "0");
                $(expendedOldItem).find(".nControlSubMenu").slideUp(700);
            }

            $(this).closest(".nTreeMenuItem").attr("state", "1");

            var nCon = $(this).closest(".nControl");
            var treeIndex = $(".nControl").index(nCon);
            resetColors(treeIndex);
            $(this).find("a").css("color", _colLinkBlue);

            var lc = $(this).closest(".nControlMenu").find(".nTreeMenuItem").length;
            var lcIn = $(this).closest(".nTreeMenuItem").find(".nTreeSubItem").length;
            var tHeight = (lc + lcIn) * 17;

            tHeight = tHeight + 45;//30
            //if (jQuery.browser.msie) { tHeight = tHeight + 30; }//fix ie

            //alert("th=" + tHeight);
            $(this).closest(".nControl").css("height", tHeight);
            expendBgToFit();


            _lastSubChildren = $(this).closest(".nTreeMenuItem");
            setTimeout("openSubChildren();", 100);

            if (IsHP == 'True') {
                var junctionID = $(this).attr("jn");
                sm_highlightSectionFromMenu(junctionID); //hp sitemap highlight
            }
        }
        else {
            //open link
        }
    });
}
function openSubChildren() {
    $(_lastSubChildren).find(".nControlSubMenu").slideDown(700);
}


//------------------------------------------------------------------------------------
//  SEARCH
//------------------------------------------------------------------------------------
var nm_searchKey = "";
var nm_lastSearch = "";
var nm_pCurrentFilterCategoryID = "2,3,7,8,9";
var nm_pCurrentPageIndex = -1;
var nm_keyInterval;

function nm_initSearchControl() {
    $(".nm_searchBtn").mousedown(function () {
        //OPEN SEARCH PAGE WITH THE INPUT VALUE
    });
    $(".nm_filterItem").mousedown(function () {
        var attrVal = $(this).find("a").attr("cid");
        nm_changeSearchFilter(attrVal, false);
    });
    nm_setCategoryLinkState();
}
function nm_changeSearchFilter(cid) {
    nm_pCurrentFilterCategoryID = cid;
    nm_setCategoryLinkState();
    nm_search();
}
function nmSearch_onKeyUp() {
    nm_pCurrentPageIndex = -1;
    clearInterval(nm_keyInterval);
    nm_keyInterval = setInterval("nm_search()", 200); //activate delay while typing
}
function nm_setCategoryLinkState() {
    $('.nm_filterItem').each(function (index) {
        var linkElement = $(this).find("a");
        if (nm_pCurrentFilterCategoryID == $(linkElement).attr("cid")) {
            $(linkElement).attr('class', 'nm_filter_selected');
        }
        else {
            $(linkElement).attr('class', 'nm_filter_link');
        }
    });
}
function nm_search() {
    var searchFlag = true;
    clearInterval(nm_keyInterval);
    searchKey = document.getElementById("tbNmSearchKey").value;
    searchKey = searchKey.trim();
    searchKey = searchKey.toLowerCase();
    if (searchKey.length == 2) {
        var k1 = searchKey.substring(0, 1);var k2 = searchKey.substring(1, 2);
        var re1 = /[a-z]/;var re2 = /[0-9]/;
        var m1 = re1.exec(k1);var m2 = re2.exec(k2);
        if (m1 && m2) {searchFlag = true;}else {searchFlag = false;}
    }
    else if (searchKey < 2) {searchFlag = false;}
    if (searchFlag == true) {nm_clientSearch();}
}

var xhrSearch = null;
var isNmSearching = false;
function nm_clientSearch() {
    var sKey = document.getElementById("tbNmSearchKey").value;
    if (isNmSearching) { xhrSearch.abort(); }
    isNmSearching = true;
    var ajaxURL = baseURL + "webservice/wsSearch.asmx/ajaxSearch";
    $("nm_PageContentsWrapper").remove();
    $(".nm_searchResults").hide();
    xhrSearch = $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", url: ajaxURL,
        data: "{'CategoryID': '" + nm_pCurrentFilterCategoryID + "','PageIndex':'-1','Key': '" + sKey + "','IsMenuEmbbeded':'True'}",
        dataType: "json",
        success: function (msg) {
            isNmSearching = false;
            var serverData = msg.d;
            if (serverData.length > 0) {

                $(".nm_searchResults").html(serverData);
                var ItemsCount = $(".nm_searchResults").find(".nm_searchitem").length;
                if (ItemsCount > 0) 
                {
                    initSearchItemsEvents();
                    var th = 400;
                    th = th + 15;// if (jQuery.browser.msie) { th = th + 15; }
                    var nObj = $('.nControl').get(_nmenu_root_index);
                    $(nObj).css("height", th);
                    th = th + _controlVpadding;
                    $('#nmenuBody').animate({ height: th },
                    {
                        easing: 'easeInOutCubic',
                        duration: 700, complete: function () {
                            if (jQuery.browser.msie) { $("#nmenuXup").show(); } else { $("#nmenuXup").fadeTo(100, 1); }
                            $(".nm_searchResults").fadeTo(400, 1);
                        }
                    });
                }
                else {
                    //hide search resulsts area and show only the controller
                    var nObj = $('.nControl').get(1);
                    $(nObj).css("height", _searchControlStartHeight);
                    expendBgToFit();
                }



                /*
                $(".nm_searchResults").html(serverData);
                initSearchItemsEvents();
                var th = 400; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<calc
                if (jQuery.browser.msie) { th = th + 15; }
                var nObj = $('.nControl').get(_nmenu_root_index);
                $(nObj).css("height", th);
                th = th + _controlVpadding;                
                $('#nmenuBody').animate({ height: th },
                {
                    easing: 'easeInOutCubic',
                    duration: 700, complete: function () {
                        if (jQuery.browser.msie) { $("#nmenuXup").show(); } else { $("#nmenuXup").fadeTo(100, 1); }
                        $(".nm_searchResults").fadeTo(400, 1);
                    }
                });
                */



            }
        }
    });
}
function stopSearch() {
    if (isNmSearching) { xhrSearch.abort(); }
}
function initSearchItemsEvents() {
    $('.nm_searchitem').find("span").hover(function () 
    {
        $(this).closest(".nm_searchitem").find(".nm_search_tframe").show();
        $(this).closest(".nm_searchitem").find(".nm_searchitem_text").css("color", _colLinkBlue);
    });
    $('.nm_searchitem').find("span").mouseout(function () 
    {
        $(this).closest(".nm_searchitem").find(".nm_search_tframe").hide();
        $(this).closest(".nm_searchitem").find(".nm_searchitem_text").css("color", "#ffffff");
    });
}
function nm_clearSearch() {
    $("#tbNmSearchKey").val("");
    $(".nm_PageContentsWrapper").remove();
    $(".nm_searchitem_viewall").remove();
    var nObj = $('.nControl').get(1);
    $(nObj).css("height", _searchControlStartHeight);
    expendBgToFit();
}

//------------------------------------------------------------------------------------
//  FAVORITES
//------------------------------------------------------------------------------------
var xhrLogin = null;
var nm_isLoginProc = false;
function nm_loginMemberclick() {
    if (nm_isLoginProc == false) {
        var logID = $(".nm_loginID").val();
        var logPs = $(".nm_loginPass").val();
        if (logID.length > 0 && logPs.length > 0) {
            var ajaxURL = baseURL + "webservice/wsCatalogCookiesUtil.asmx/authMember";
            isLoginProc = true;
            xhrLogin = $.ajax({
                type: "POST", contentType: "application/json; charset=utf-8", url: ajaxURL,
                data: "{'logID': '" + logID + "','logPs':'" + logPs + "'}", dataType: "json",
                success: function (msg) {
                    var serverData = msg.d;
                    if (serverData.length > 0) {
                        nm_isLoginProc = false;
                        if (serverData == "-1") {
                            $("#nm_loginErr").html("Wrong Email or Password");
                        }
                        else {
                            //change member_id value
                            checkFavorties();
                        }
                    }
                }
            });
        }
    }
}

var isFavoritesLoaded = false;
var xhrNmFav = null;
function checkFavorties() {
    if (!isFavoritesLoaded) {
        var ajaxURL = baseURL + "webservice/wsGetFavorites.asmx/getMenuFavorites";
        $("#nm_fav_contents").html("loading fav!!!!");
        xhrNmFav = $.ajax({
            type: "POST", contentType: "application/json; charset=utf-8", url: ajaxURL, dataType: "json",
            success: function (msg) {
                if (msg.d == "err1") {
                    //DISPLAY LOGIN BOX
                    //if(nm_isFavFirstMotion)
                    nm_showFavLoginOptionsPanel();
                }
                else if (msg.d.length > 0) 
                {
                    $("#nm_fav_emptyMsg").hide();
                    $("#nm_fav_contents").hide();
                    $("#nm_fav_contents").html(msg.d);
                    var favItemsCount = $("#nm_fav_contents").find(".nm_searchitem").length;
                    if (favItemsCount > 0) {
                        $("#nm_fav_contents").fadeTo(300, 1);
                        initSearchItemsEvents();
                    }
                    else {
                        $("#nm_fav_emptyMsg").fadeTo(300, 1);
                    }
                    nm_showFavResultsPanel();
                    isFavoritesLoaded = true;
                }
            }
        });
    }
}

var nm_isFavFirstMotion = true;
function nm_showFavLoginOptionsPanel() {
    nm_slideFavControl(0);
    $("#nm_fav_panels").show();
    $(".nm_fav_loading_progress").hide();
}
function nm_showFavSignInPanel() {
    nm_slideFavControl(1);
    $("#nm_fav_panels").show();
    $(".nm_fav_loading_progress").hide();
}
function nm_showFavResultsPanel() {
    nm_slideFavControl(2);
    $("#nm_fav_panels").show();
    $(".nm_fav_loading_progress").hide();
}
function nm_slideFavControl(panelIndex) {
    var th = 0 - (panelIndex * 210);
    if (nm_isFavFirstMotion) 
    {
        $('#nm_fav_panels').css("top",th+"px");
    }
    else 
    {
        $('#nm_fav_panels').animate({ top: th }, { easing: 'easeInOutCubic', duration: 650, complete: function () { } });
    }
    nm_isFavFirstMotion = false;
}
