
$(document).ready(function() {
    // fHightlightCustomerResult();
    //fFixCustomersLogo();
    if ($('#_where_name').val() == 'כל הארץ') $('#_where_name').css('color', '#a29fa0');
    //sorter_init();
    init_groupLinks();
    windowResize();
    if ($("a.helpIcon").length > 0) $("a.helpIcon").colorbox({ opacity: 0.55, scrollbars: false });
    if ($(".dpv_cont").length > 0) onStartDpVideo();
    if (vPageName == 'Business-Results' && (vHeadingCode == '35840' || vHeadingCode == '25590' || vHeadingCode == '13110' || vHeadingCode == '48240' || vHeadingCode == '32280' || vHeadingCode == '17300' || vHeadingCode == '5260' || vHeadingCode == '43110' || vHeadingCode == '11030' || vHeadingCode == '49680' || vHeadingCode == '31770' || vHeadingCode == '27450')) {
        if ($(".closeToMe_container .closeToMe").css('display') == 'block') $(".closeToMe_container .sTitle").click();
        if ($(".zoomIn_container").css('display') == 'block') $(".zoomResults_container .sTitle:eq(0)").click();
        if ($(".zoomOut_container").css('display') == 'block') $(".zoomResults_container .sTitle:eq(1)").click();
    }
	if($("#_search_text").length > 0 && $("#_where_name").length > 0) initHistory();
	
	if((vPageName=="Business-Results"||vPageName=="Summaries")&&vIsShowMap!=1)loadComparison(vHeadingCode);
	
	//alert(getCookie("cookie-comparison_40680"))
});

$(window).resize(function() {
    windowResize();
});

function windowResize() {
    if (browser == 'msie' && parseInt(jQuery.browser.version) < 8) {
        if ($(document).width() < 1001) {
            $(".myd_bottom_strip_container").css("bottom", "16px");
            //$("body").width(995);
        }
        else {
            $(".myd_bottom_strip_container").css("bottom", "0px");
            //$("body").css("width","auto");
        }
    }

    if (vIsShowMap == "1" || vPageName=="Integration-Maps") {
        if ($(document).width() < 1001) {
            $('#content').width('980px');
        }
        else $('#content').width('auto');
    }
}

function redirectMapR() {
	changeLocation(Link_ResultsDmap);
}

function fHightlightCustomerResult() {
    var customersResult = $("div.businessResult");
    customersResult.each(function(index) {
    $(this).mouseover(function(e) { if($(this).css("background") == "transparent") $(this).css("background", "#ECECEC"); else $(this).css("background", "transparent"); });
    $(this).mouseout(function(e) { if ($(this).css("background") == "transparent") $(this).css("background", "#ECECEC"); else $(this).css("background", "transparent"); });
    });
    //alert(customersResult.length);
}


function sorter_init() {

    sorter_init_closeToMe();

    sorter_relevantHedings(".zoomIn_container .zoomIn_where");
    sorter_relevantHedings(".zoomIn_container .zoomIn_what");

    $('.zoomIn_what .show4results').height($('.zoomIn_what .show4results').height());
    $(".closeToMe_container .sTitle").click(function() { $(".closeToMe_container .closeToMe").toggle("slow"); $(this).toggleClass("closeArrow"); });
    $(".zoomResults_container .sTitle:eq(0)").click(function() { $(".zoomIn_container").toggle("slow"); $(this).toggleClass("closeArrow"); });
    $(".zoomResults_container .sTitle:eq(1)").click(function() { $(".zoomOut_container").toggle("slow"); $(this).toggleClass("closeArrow"); sorter_zoomOutResults(); });
}

function sorter_zoomOutResults() {
    if ($(".zoomIn_container").length != 0) {
        ajaxSorterCities += "&isJson=1";
        var whereNameVal = $("#_where_name").val();
        whereNameVal = (whereNameVal == 'כל הארץ') ? '' : whereNameVal;
        var searchTxt = $("#_search_text").val();
        var cityName = '';
        var streetName = '';
        if ($("#cityName").length > 0)
            cityName = ($("#cityName").val() == "שם יישוב / עיר") ? '' : $("#cityName").val();
        if ($("#streetName").length > 0)
            streetName = ($("#streetName").val() == "שם רחוב") ? '' : $("#streetName").val();
        var searchType;
        $("form[name='mainForm'] input:radio").each(function() { if (this.checked) searchType = this.value; });
        var resultsNum;
        if (is0ResultsNum) { resultsNum = 0 }
        else { resultsNum = (window['vResultsNum'] != undefined) ? vResultsNum : $(".result-message .ttl span").html(); }
        ajaxSorterCities += "&search_text=" + searchTxt + "&search_type=" + searchType + "&where_name=" + whereNameVal + "&resultsNum=" + resultsNum + "&headingCode=" + vHeadingCode + "&cityName=" + cityName + "&streetName=" + streetName + "&str=אבג";
        if (vWhereNameDefaultValue != '') {
            $.ajax({
                url: ajaxSorterCities,
                cache: false,
                dataType: "json",
                success: function(data) {
                    sorter_ZoomResults(data);
                },
                error: function() {
                    //alert("Error");
                },
                complete: function() {}
            });
        }
        else sorter_ZoomResults();
    }
}

function sorter_init_closeToMe() {
	 if ($(".closeToMe_slider").length != 0) {
        sorter_closeToMe_radius = (sorter_closeToMe_radius == 0) ? 4 : sorter_closeToMe_radius;
        $(".closeToMe_slider").slider({
            range: "min",
            value: sorter_closeToMe_radius,
            min: 0.2,
            max: 8,
            step: .2,
            slide: function(event, ui) {
                $("#closeToMe_radius").val(ui.value);
            }
        });
        $("#closeToMe_radius").val($(".closeToMe_slider").slider("value"));
    }
}

function sorter_CloseToMe_onS() {
    var r = true;
    if ($('#cityName').val() == 'שם יישוב / עיר' || $('#cityName').val() == '') {
        r = false;
        $('.closeToMe_err').show();
    }
    if (r == true && ($('#streetName').val() == 'שם רחוב' || $('#streetName').val() == '')) $('#streetName').val('');
    return r;
}

function sorter_ZoomResults(data) {
    $('.zr_uploadImg').hide();
    if (vWhereNameDefaultValue == '')
        sorter_relevantHedings(".zoomOut_container .zoomOut_where")
    else
        sorter_insertResults(data.GeoFilterResults.ZoomOut, ".zoomOut_container .zoomResults", ".zoomOut_where");
    if (window['isShowLeftResults'] != undefined && isShowLeftResults == 0 && vWhereNameDefaultValue != '') $(".zoomOut_container").show();
}

function sorter_insertResults(data, contDivClass_results, contDivClass_more) {
    var numOfList = data.List.length;
    var numOfContDivs = Math.floor(numOfList / 10) + 1;
    var showResultHeight = 0;
    sorter_zoomResultsContDiv(numOfContDivs, contDivClass_results, 'show10results', 'show10results_id');
    if (data.whereName)
        sorter_appendZoomResults(data.whereName, data.noOfResults, data.url, contDivClass_results + " .show10results:eq(0)", "selected");
    if (numOfList != 0) {
        idNum = 0;
        $(data.List).each(function(i) {
            sorter_appendZoomResults(this.resultTitle, this.noOfResults, this.url, contDivClass_results + " .show10results:eq(" + idNum + ")");
            if (i % 9 == 0 && i != 0) idNum++;
            if (i == 0) showResultHeight = $(contDivClass_results + " .show10results:eq(" + idNum + ")").height();
        });
    }
    showResultHeight = (showResultHeight == 0) ? 'auto' : showResultHeight;
    $(contDivClass_results + " .show10results:eq(0)").height(showResultHeight).show("slow");
    if (numOfList > 4) {
        $(contDivClass_more + " .zoom_more").click(function() {
            $(contDivClass_results + " .show10results:eq(0)").hide("slow", function() { $(this).css("height", "auto").show("slow") });
            $(this).hide();
            if (numOfContDivs > 1) {
                $(contDivClass_more + " .zoom_prev").click(function() {
                    sorter_zoomResultsChangeShowDiv($(contDivClass_results + " .show10results:visible"), false);
                }).show();
                $(contDivClass_more + " .zoom_next").click(function() {
                    sorter_zoomResultsChangeShowDiv($(contDivClass_results + " .show10results:visible"), true);
                }).show();
            }
        }).show();
        $(contDivClass_more + " .moreResultsLink").show();
    }
}

function sorter_zoomResultsChangeShowDiv(showDiv, isNext) {
    if (isNext && $(showDiv).next().length != 0 && $(showDiv).next().attr('className') == 'show10results') {
        $(showDiv).hide("slow", function() { $(showDiv).next().show("slow"); });
    }
    else if (!isNext && $(showDiv).prev().length != 0 && $(showDiv).prev().attr('className') == 'show10results') {
        $(showDiv).hide("slow", function() { $(showDiv).prev().show("slow"); });
    }
}

function sorter_zoomResultsContDiv(numOfContDivs, contDiv, cssName, divId) {
    for (var i = 0; i<numOfContDivs; i++) {
        $('<div></div>')
            .addClass(cssName)
            .css("overflow", "hidden")
            .hide()
            .appendTo($(contDiv));
    }
    
}

function sorter_appendZoomResults(resultTitle, noOfResult, url, appendToObj, cssName) {
    if (resultTitle != '')
        $('<div></div>')
            .click(function() { changeLocation(url) })
            .addClass("zoomInresult")
            .append(
                $('<span></span>')
                    .addClass("resultTitle")
                    .addClass(cssName)
                    .html(resultTitle)
                    .append(
                        $('<span></span>')
                            .addClass('noOfResult')
                            .html(" (" + noOfResult + ")")
                    )
        ).appendTo($(appendToObj));
}

function sorter_relevantHedings(obj) {
    if ($(obj + " .show10results").length > 0) {
        $(obj + " .zoom_more").click(function() {
            $(obj + " .show4results").hide("slow", function() { $(obj + " .show10results:eq(0)").show("slow"); });
            $(this).hide();
            if ($(obj + " .show10results").length > 1) {
                $(obj + " .zoom_prev").click(function() {
                    sorter_zoomResultsChangeShowDiv($(obj + " .show10results:visible"), false);
                }).show();
                $(obj + " .zoom_next").click(function() {
                    sorter_zoomResultsChangeShowDiv($(obj + " .show10results:visible"), true);
                }).show();
            }
        }).show();
    }
}

function clickEngineTab(engineName, tabClicked) {
    $(".tab_container > .tab").each(function(i) {
        $(this).removeClass("tab_on");
        if (i == tabClicked) $(this).addClass("tab_on");
    });
}

function showSearchTextAutocomplete() {
    var searchType;
    $("form[name='mainForm'] input:radio").each(function() { if (this.checked) searchType = this.value; });
	setWhatHistoryText(searchType);
    if (searchType == "heading" && $("#_env_search_text > #_search_text").length == 0) {
        $("#_env_search_text").remove();
        installAC($("#_search_text")[0], '/?page=Business-Ajax-AjaxHeadings&isXML=1&discardseo=1&query=', '#FFFFFF', '#000000', '#0000FF', '#FFFFFF', $("#headingCode")[0], 50, 0, 0, 0, 0);
    }
    else {
        if ($("#_env_search_text").length != 0) {
            $("#_search_text").clone().insertBefore("#_env_search_text");
            $("form[name='mainForm'] input[name='_search_text']:last").remove();
        }
    }
    if ($(".search_tips .what_tip_n").length > 0)
        if (searchType == "heading") {
        $(".search_tips .what_tip_n").hide();
        $(".search_tips .what_tip_h").show();
    }
    else {
        $(".search_tips .what_tip_h").hide();
        $(".search_tips .what_tip_n").show();
    };
}

function fSetPage(searchTextValue, searchType) {
    if ((searchType == 'name') || (searchTextValue != dpzOriginalSearchTxt)) {
        $("form[name='mainForm'] input[name='page']").val('Summaries');
        if ($("form[name='mainForm'] input[name='headingCode']").length > 0)
            $("form[name='mainForm'] input[name='headingCode']").remove();
        //$("form[name='mainForm'] input[name='headingCode']").val('');
    }
    return true;
}

function checkSearchEngine(defaultWhereName) {
    var searchType;
    $("form[name='mainForm'] input:radio").each(function() { if (this.checked) searchType = this.value; });
    $("#headingCode").val((searchType == "heading") ? $("#headingCode").attr("value") : "");
    var searchTextValue = $("#_search_text").val();
    if (searchTextValue == "")
    {
        if ($(".search_tips > .dpzengine_error_msg_hp").length > 0)
            $(".search_tips > .dpzengine_error_msg_hp").css("visibility", "visible");
        else
            $(".search_tips > .dpzengine_error_msg").show();
        $(".search_tips > .what_tip").hide();
        $('.dpzengine_what_input > div:first').attr('className', 'eror');
        return false;
    }
    $("#_where_name").val(($("#_where_name").val() == defaultWhereName) ? "" : $("#_where_name").val());
    var searchText = $("#_search_text")[0];
    var whereName = $("#_where_name")[0];
    fTags2Entites(searchText, whereName);
    //////need to check myd place;
    dcsMultiTrack('DCSext.vSearchEngineClick', '1');
    return (vPageName == 'Business-Results') ? fSetPage(searchTextValue, searchType) : true;
}

function fTags2Entites() {
    var vArgs = fTags2Entites.arguments;
    for (var i = 0; i < vArgs.length; i++) {
        if (vArgs[i].value.match(/</) != null) vArgs[i].value = vArgs[i].value.replace(/</g, '&lt;');
        if (vArgs[i].value.match(/>/) != null) vArgs[i].value = vArgs[i].value.replace(/>/g, '&gt;');
    }
}

function searchEngineChangeType(searchType) {
    $("form input:radio[value='" + searchType + "']").attr("checked", "checked");
    $(".dpzengine_search_btn:submit").click();
}

function searchEngineChangeWN(changeWhere) {
    $("#_where_name").val(changeWhere);
    $(".dpzengine_search_btn:submit").click();
}

function whereNameOnF() {
    $('.dpzengine_where_input > div:first').attr('className', 'select');
    if ($('#_where_name').val() == 'כל הארץ') $('#_where_name').val('').css('color', '#191415');
}

function whereNameOutF() {
    $('.dpzengine_where_input > div:first').attr('className', '');
    if ($('#_where_name').val() == '') $('#_where_name').val('כל הארץ').css('color', '#a29fa0');
}

function ResultNotFound_ValidateForm() {
    if ($('#ResultNotFound_busName').val().length == 0) {
        alert('יש למלא את שם בית העסק');
        return false;
    }
    if ($('#ResultNotFound_busAddress').val().length == 0) {
        alert(' יש למלא את כתובת בית העסק');
        return false;
    }
    return true;
}
		 
function randomBanners(size, noBanners) {
    noBanners = (noBanners > size)? size : noBanners;
    var homeHLBannerNum = -1;
    for (i = 0; i < noBanners; i++) {
        showBanner[i] = Math.floor(Math.random() * (size));
        for (j = 0; j < i; j++) {
            homeHLBannerNum = (homeHLBannerNum == -1)? Math.floor(Math.random() * (size)) : homeHLBannerNum;
            while (showBanner[i] == showBanner[j]) {
                showBanner[i] = Math.floor(Math.random() * (size));
                j = 0;
            }
        }
        var oDiv = $('#tdBanner' + showBanner[i]);
        oDiv.show();
        $('#divBanners').append(oDiv);
    }
    $('#tdBanner' + homeHLBannerNum).clone().appendTo($(".homeHLBanner"));
    $(".homeHLBanner .DPH").show();
    $('#tempDivBanners').empty();
}

function checkRouteSearch_HP() {
    if ($("input[name=_saddressHP]").val() != "" & $("input[name=_daddressHP]").val() != "")
        return true
    else {
        $(".routeSC .errormsg").show();
        return false;
    }
}

function toggleHeadingAbout() {
    $('.headingAbout').slideToggle();
}

function clickSearchTypeTxt(radioNum) {
    $('input:radio[name="_search_type"]:eq('+ radioNum +')').click();
}

function buildPhonePlayer(custId, headingCode, RandomFileName, contDiv){
    if ($('#phonePlayer').length == 1) $('#phonePlayer').remove();    
    var filepath = 'http://ws.d.co.il/PhoneReader/Default.aspx?custId=' + custId + '&RandomFileName=' + RandomFileName + '&headingCode=' + headingCode;
    //var filepath = 'http://ws.d.co.il/PhoneReader/Default.aspx?custId=3722&RandomFileName=3534535345&headingCode=2400';
    var playerC = "<object width='0' height='0' id='phonePlayer' showcontrols='false' autostart='true' type='audio/x-wav' data='" + filepath + "' >";
    playerC += "<param name='src' value='" + filepath + "' />";
    playerC += "<param name='type' value='audio/x-wav' />";
    playerC += "<param name='autostart' value='true' />";
    playerC += "<param name='showcontrols' value='false' />"; 
    playerC += "<param name='showstatusbar' value='false' />";
    playerC += "</object>";
    $(contDiv).append(playerC);
}

function initMovingLinks()
{
	$(".moinLink").click(function() { openWindow('http://www.moin.gov.il/apps/pubwebsite/MainMenu.nsf/') });
	$(".israelpostLink").click(function() { openWindow('https://www.israelpost.co.il/mynewaddress.nsf') });
	$(".electricLink").click(function() { openWindow('http://www.israel-electric.co.il/bin/ibp.jsp?ibpDispWhat=object&ibpDisplay=view&ibpPage=IP&ibpDispWho=General%5El277&ibpZone=QAndA&ibpVersion=0&') });
	$(".maccabiLink").click(function() { openWindow('http://www.maccabi-health.co.il/5302-he/Maccabi.aspx') });
	$(".leumitLink").click(function() { openWindow('http://www.leumit.co.il/ShabanForm.asp?type=2') });
	$(".meuhedetLink").click(function() { openWindow('https://www.meuhedet.co.il/meuhedet/views/engine?rnd=0.5442290320290347&templateName=meuhedetMenu.txt&idorItemId=topMenu&formview=formLink&formFormTypeParam=31&formlinkParam=personalInfoUpdateForm&mainView=personalInfoUpdateForm&mainFormTypeParam=31&menuBarStartMenuParam=') });
	$(".clalitLink").click(function() { openWindow('https://e-services.clalit.org.il/onlineweb/general/login.aspx') });
	$(".yesLink").click(function() { openWindow('http://www.yes.co.il/special/moving1.aspx') });
	$(".hotLink").click(function() { openWindow('http://www.hot.net.il/HOT.aspx?FolderID=2898&lang=he') });
	$(".bezeqLink").click(function() { openWindow('http://www.bezeq.co.il/Sales/Pages/moving3.aspx?gclid=CMaxrcrDoaICFVA03wodumODxA') });
	$(".012Link").click(function() { openWindow('http://www.012.net/about.aspx?FolderID=28&lang=he&res=0&pos=0&tabn=0') });
	$(".013netvisionLink").click(function() { openWindow('http://www.013netvision.net.il/Article/?ArticleID=658683') });
	$(".pelephoneLink").click(function() { openWindow('http://www.pelephone.co.il//web/3G/Corporate/CustomerService/PhoneServices/.aspx') });
	$(".cellcomLink").click(function() { openWindow('http://www.cellcom.co.il/support/contact_us/pages/default.aspx') });
	$(".orangeLink").click(function() { openWindow('https://direct.orange.co.il/selfservice/ccservice.jsp?catID=80&actionID=53') });
	$(".nokiaLink").click(function() { openWindow('http://www.nokia.co.il/support/contact-us') });
	$(".MirsLink").click(function() { openWindow('http://82.80.228.139/764-he/Mirs.aspx') });
}