﻿var Expo_Search = (function() {
    function init() {
        //ראשון לביצוע
        initFildes();
        initSearchEvents();
        initCustForm();
        initSearchOn();
        initProductAllEvents();
        initCategories();
    }
    function LoadInit() {
        //שני לביצוע
        initTopMenu();

        initLangs();
        initContact();
        initRemove();

        initAutoComplete();
        initRecentSearch();
        initBanners(SEARCHTERM);
        initLogOut();
        initCheckExistItmes();
        focousUserNameFiled();
    }

    function initLangs() {
        $('.lang').expobee_tooltip();
    }
    function initTopMenu() {
        $('.with-children').dropdown({ clickElementCssClass: 'top-menu-item' });
    }
    function initAutoComplete() {
        var searchType = $('#search_on_panel input:radio:checked').val();
        var filterByexhibition = ($('#exhibitionCheck:checked').val() != null) ? true : false;
        var selectedexhibitionId = $("#exhibitionList").val();
        autocompleterobject = $("#inputSearchText").autocomplete(_AutocompleterHandlerUrl, {
            width: 354,
            extraParams: { searchType: searchType, filterByexhibition: filterByexhibition, selectedexhibitionId: selectedexhibitionId, cultureID: CULTUREID, userId: CURRENTUSERID },
            footerElement: $('#hideSuggestion'),
            open: function() { },
            selectFirst: false,
            mustMatch: false,
            matchContains: true,
            autoFill: false,
            scroll: false,
            cacheLength: 0,
            minChars: _AutocompleterMinChars
        });
        autocompleterobject.result(function() { initSearchBtnClick("inputSearchText"); });
        $('#hideSuggestion').click(function() { autocompleterobject.unautocomplete(); });

    }
    function SetOptionsToAutoCompleter() {
        var searchType = $('#search_on_panel input:radio:checked').val();
        var filterByexhibition = ($('#exhibitionCheck:checked').val() != null) ? true : false;
        var selectedexhibitionId = $("#exhibitionList").val();
        autocompleterobject.setOptions({ extraParams: { searchType: searchType, filterByexhibition: filterByexhibition, selectedexhibitionId: selectedexhibitionId, cultureID: CULTUREID, userId: CURRENTUSERID} });
    }
    function initSearchEvents() {
        if (SEARCHTERM.length > 0)
            $('.SearchFiled').val(SEARCHTERM);
        $('.SearchFiled').bind('keypress', function(e) {
            if (e.keyCode == 13) {
                initSearchBtnClick(this.id);
            }
        }).focus(function() {
            if (search_on_panel_is_open) {
                $("#search_on_panel").hide(); $("#search_on_btn").removeClass("active"); search_on_panel_is_open = false;
            }
        });
        $('.main_search_btn').click(function() {
            initSearchBtnClick(this.id + 'Text');
        });
    }
    function initSearchBtnClick(searchId) {
        var searchTextObj = $('#' + searchId);
        var searchTerm = escape(searchTextObj.val());
        var defaultValue = searchTextObj.attr('name');
        if (searchTerm == null || searchTerm.length < _SearchMinChars || searchTerm == defaultValue) {
            ShowSearchError();
            return;
        }
        var searchType = $('#search_on_panel input:radio:checked').val();
        var filterByexhibition = ($('#exhibitionCheck:checked').val() != null) ? true : false;
        var selectedexhibitionId = $("#exhibitionList").val();
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: _ServiceUrl + "/GetUrl",
            data: "{userId:'" + CURRENTUSERID + "',cultureId:'" + CULTUREID + "',searchType:'" + searchType + "',searchTerm:'" + searchTerm + "',isFairFilter:'" + filterByexhibition + "',fairID:'" + selectedexhibitionId + "'}",
            dataType: "json",
            success: function(result) {
                location.href = result.d;
            },
            error: function(xhr, ajaxOptions, thrownError) {
                SiteError(xhr, ajaxOptions, thrownError);
            }

        });



    }
    function initFildes() {
        $('.InitField').each(function(i) { initField(this); });
    }
    function initProductAllEvents() {
        initActiveIconsFromCookie();

        var objcollection = $('.product-icon');
        objcollection.each(function(index) {
            var item = $(this);
            var alt_remove = item.find('div.remove');
            alt_remove.css("width", "auto");
            var unactivewidth = alt_remove.width() + 8;
            var alt_active = item.find('div.add');
            alt_active.css("width", "auto");
            var activewidth = alt_active.width() + 8;
            if (item.hasClass('active')) //this item added already
            {
                addEventToActive(item, activewidth, unactivewidth);
            }
            else //this item not added already
            {
                addEventToUnActive(item, activewidth, unactivewidth);
            }
            $('div', item).removeClass("transparent_class").css({ 'opacity': '0', 'width': '0' });
        });
        ShowBigImagesLightBox();
        AddAllItemsToCatalogEvent();
        initProductOver();
    }

    function initCategories() {
        $('.category-panel').categories({ showCategoryBtnCssClass: 'show-more-categories', hideCategoryBtnCssClass: 'hide-more-cateogories', headerCssClass: 'round-header', contentCssClass: 'round-content' });
        $('.category-panel .transparent_class').removeClass('transparent_class');
    }
    function initContact() {
        var productinquiry = $("#productinquiry");
        var width = productinquiry.width();
        productinquiry.css({ left: '-' + (width - 20) / 2 + 'px' });
        $('.tooltip-arrow', productinquiry).css({ left: ((width - 10) / 2) + 'px' });
        productinquiry.appendTo(displayNone);
        var displayNone = $("#displayNone");
        $('.product-contact').mouseenter(function() { productinquiry.appendTo(this); $(this).addClass("over"); }).mouseleave(function() { productinquiry.appendTo(displayNone); $(this).removeClass("over"); })
    }
    function initRemove() {
        var removeList = $('.round-content .li .remove');
        removeList.each(function(i, item) {
            var chidlsGroup = $(".remove", $(item).parent());
            $(item).mouseenter(function() {
                $(this).addClass('over');
                if (_showRemoveTooltip) { $('#removeTooltip').appendTo(this); }
                chidlsGroup.addClass("over");
            })
        .mouseleave(function() {
            $(this).removeClass('over');
            if (_showRemoveTooltip) { $('#removeTooltip').appendTo($("#displayNone")); }
            chidlsGroup.removeClass("over");
        });
        });
        //כשעומדים מעל לחצן מחיקה של קטגוריה נדלקים כל הבנים
        var clearGroup = $('.round-content .clear-group');
        clearGroup.each(function(i, item) {
            var ChildGroup = $(".remove", $(item).parents(".filter-group"));
            $(item).mouseenter(function() {
                ChildGroup.addClass("over");
            })
        .mouseleave(function() {
            ChildGroup.removeClass("over");
        });
        });
        //כשעומדים מעל ללחצן של מחיקת הכל מסומנים כל האפשרויות
        var AllRemoveAbleGroup = $('.round-content .li .remove');
        $('.round-content .clear-all').mouseenter(function() {
            AllRemoveAbleGroup.addClass("over");
            $('.remove', this).addClass("over");
        })
        .mouseleave(function() {
            AllRemoveAbleGroup.removeClass("over");
            $('.remove', this).removeClass("over");
        });
    }

    function initCustForm() {
        $("input[type='radio']").custCheckBox({ callback: function() {
            var _selectedValue = $(this).attr("name");
            $("#searchtype").text($("#x" + _selectedValue + "x").text());
            SetOptionsToAutoCompleter();
            // Hide fairs filter according to a selected search type
            if (_selectedValue == 2) {
                // hide the filter by fairs
                $('#SelectFairOptions').css("display", "none");
            }
            else {
                $('#SelectFairOptions').css("display", "block");
            }
            initRecentSearch();
        }
        });
        $("input[type='checkbox']").change(function() { SetOptionsToAutoCompleter(); }).custCheckBox();
        $(".cust_select").change(function() {
            SetOptionsToAutoCompleter();
            if ($(this).val() * 1 > 0) {
                var exhibitionCheckObj = $("#exhibitionCheck");
                var exhibitionCheckCustObj = exhibitionCheckObj.prev("span");
                exhibitionCheckObj.attr("checked", "checked");
                if (!exhibitionCheckCustObj.hasClass("cust_checkbox_on")) {
                    exhibitionCheckCustObj.removeClass("cust_checkbox_off").addClass("cust_checkbox_on"); //turn on
                }
            }
        }).sSelect();


    }

    function initSearchOn() {
        $("#search_on_panel").hide().removeClass("transparent_class");
        $('#close_search_on_panel').click(function() {
            $("#search_on_panel").slideUp(100);
            $("#search_on_btn").removeClass("active");
            search_on_panel_is_open = true;
        });
        $("#search_on_btn").click(function() {
            var search_on_panel = $("#search_on_panel");
            if (search_on_panel.is(":hidden")) {
                $(this).addClass("active");
                search_on_panel.slideDown(100);
                search_on_panel_is_open = true;

            }
            else {
                search_on_panel.slideUp(100);
                $(this).removeClass("active");
                search_on_panel_is_open = false;

            }
        });

    }
    function initRecentSearch() {
        if (CURRENTUSERID > 0) {
            var searchType = $('#search_on_panel input:radio:checked').val();
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: _ServiceUrl + "/GetRecentSearchsForUser",
                data: "{userId:'" + CURRENTUSERID + "',searchType:'" + searchType + "',cultureID:'" + CULTUREID + "',url:'" + location.href + "'}",
                dataType: "json",
                success: function(result) {
                    var strLinks = "";
                    var list = result.d;
                    if (list) {
                        var cnt = list.length;
                        for (var i = 0; i < cnt; i++) {
                            strLinks = strLinks + "<a href='" + ExpoBee_ServerRoot + "ExpoBee/Search/ProductsSearch/Default.aspx" + list[i].Url + "'>" + list[i].Header + "</a>";
                            if ((i + 1) < cnt) {
                                strLinks = strLinks + ", ";
                            }
                        }
                        if (strLinks.length > 0) {
                            $("#recent_search_container").html(strLinks);
                            $("#recent-search-header").css("display", "inline");
                        }
                    }
                    else {
                        $("#recent_search_container").html("");
                        $("#recent-search-header").css("display", "none");
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    SiteError(xhr, ajaxOptions, thrownError);
                }

            });
        }
    }

    function initBanners(searchTerm) {
        var searchType = $('#search_on_panel input:radio:checked').val();
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: _ServiceUrl + "/GetBanners",
            dataType: "html",
            data: "{userId:'" + CURRENTUSERID + "',cultureId:'" + CULTUREID + "',searchType:'" + searchType + "',searchTerm:'" + escape(searchTerm) + "'}",
            dataType: "json",
            success: function(result) {
                $("#banner_container").html(result.d.toString());
            },
            error: function(xhr, ajaxOptions, thrownError) {
                SiteError(xhr, ajaxOptions, thrownError);
            }

        });

    }
    function initLogOut() {
        $(".user-logout").click(function() {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: _ServiceUrl + getLogoutMethod(),
                dataType: "html",
                data: "{}",
                dataType: "json",
                success: function(result) {
                    if (result.d != null) {
                        location.href = result.d.toString();
                    }
                    else {
                        location.href = location.href;
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    SiteError(xhr, ajaxOptions, thrownError);
                }

            });
        });
        return true;
    }

    function getLogoutMethod() {

        if (event.srcElement.id == "logoutFromRoleUser") {
            return "/UserManager_LogoutRoleUser";
        }

        return "/UserManager_Logout";
    }

    function initCheckExistItmes() {
        $("#goto_compare_link").click(function() {
            if ($("#lbl_cmpr").text() * 1 == 0) {
                $("#compare_link_container").expobee_generic_tooltip({}, NoProductCompareHeader, NoProductCompareContent);
                return false;
            }
        });
        $("#goto_catlaog_link").click(function() {
            if ($("#lbl_ctlg").text() * 1 == 0) {
                $("#ecatalog_link_container").expobee_generic_tooltip({}, NoProductEcatlogHeader, NoProductEcatlogContent);
                return false;
            }
            else {
                var cockieData = getCookieData("ctlg");
                if (cockieData != null) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: _ServiceUrl + "/CreateECatalog",
                        data: "{value:'" + cockieData + "'}",
                        dataType: "json",
                        success: function(result) {
                            if (result != null && result.d != null) {
                                if (result.d.Succeeded) {
                                    window.location = result.d.ReturnValue;
                                    removeCookieData("ctlg", null);
                                }
                                else {
                                    $(ExpoBee_Result).SetResult('attention', result.d.ReturnValue);
                                }
                            }
                        },
                        error: function(xhr, ajaxOptions, thrownError) {
                            SiteError(xhr, ajaxOptions, thrownError);
                        }
                    });

                }
            }
        });
    }
    function focousUserNameFiled() {
        $('#login').click(function() {
            setTimeout(function() {
                var iframeRef = document.getElementById("my_login_iframe");
                $(iframeRef).contents().find("#" + loginControlUserNameClientId).focus();

            }, 600);
        });
    }
    $(document).ready(function() { init(); });
    $(window).load(function() { LoadInit(); });




} ());






