
$(function() {
 if (browser === "msie" && parseInt($.browser.version, 10) === 6)
 {
  document.body.tabIndex = -10;
  document.body.focus();
 }
 // fHightlightCustomerResult();
 //fFixCustomersLogo();
 if (helpers.isCountryWide($('#_where_name').val()))
 {
  $('#_where_name').css('color', '#a29fa0'); 
 }
 //sorter_init();
 init_groupLinks();
 windowResize();
 $(".dpzengine_what_input.iTxtWErr").click(function(){$("#_search_text").focus();}).css("cursor", "text");
 $(".dpzengine_where_input.iTxtWErr.iTxt").click(function(){$("#_where_name").focus();}).css("cursor", "text");
 if ($("a.helpIcon").length > 0)
 {
  $("a.helpIcon").colorbox({ opacity: 0.55, scrollbars: false, href: "/?page=Integration-Marketing-SiteHelpFlash&amp;FlashURL=/Hebrew/flash/HelpVideos/search-engine.swf"});
 }
 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();
  }
 }
 // History
 if ($("#_search_text").length > 0 && $("#_where_name").length > 0)
 {
  initHistory();
 }
 if (vPageName === "Integration-Maps")
 {
  gpi.cookieHistory.initMapHistory();
 }
 if (window.pinnedSite && window.gpi && window.gpi.history &&
     window.gpi.pinnedSite)
 {
  gpi.pinnedSite.initializePinnedSiteOperations();
 }
 if ((vPageName === "Business-Results" || vPageName === "Summaries" ||
      vPageName === "Integration-Articles-Loby" ||
      vPageName === "Integration-Articles-Article") &&
     vIsShowMap != 1)
 {
  loadComparison(vHeadingCode);
 }
 //alert(getCookie("cookie-comparison_40680"))
 if (!(browser === "opera" || browser === "mozilla" || browser === "msie"))
 {
  $("#add-to-favorites-footer").hide();
 }
 if (browser !== "msie")
 {
  $("#set-as-homepage-footer").hide();
 }
});

var helpers = {};
helpers.isCountryWide =
 function (val)
 {
  return typeof val === "string" && val.match(/^[\s\t]*(כל הארץ|ישראל|israel)[\s\t]*$/i) !== null;
 };

function shareOnFacebook(url)
{
 window.open("http://www.facebook.com/sharer.php?u=" + url, "", "width=600,height=400");
 return false;
}


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.documentElement).width() < 1001) {
            $('#content').width('980px');
        }
        else $('#content').width('auto');
    }
}
$(window).resize(windowResize);

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"); if (!$(this).hasClass("closeArrow")) sorter_zoomOutResults(); });
}

function sorter_zoomOutResults() {
    if ($(".zoomIn_container").length != 0) {
        var ajaxSorterCitiesQuery = ajaxSorterCities + "&isJson=1";
        var whereNameVal = $("#_where_name").val();
        whereNameVal = (helpers.isCountryWide(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:checked").val();
        var resultsNum;
        if (is0ResultsNum) { resultsNum = 0; }
        else { resultsNum = (typeof window['vResultsNum'] != "undefined") ? vResultsNum : $(".result-message .ttl span").html(); }
        ajaxSorterCitiesQuery += "&search_text=" + searchTxt + "&search_type=" + searchType + "&where_name=" + whereNameVal + "&resultsNum=" + resultsNum + "&headingCode=" + vHeadingCode + "&cityName=" + cityName + "&streetName=" + streetName + "&str=אבג";
        if ($(".zoomOut_container .resultTitle").length !== 0)
         return;
        if (vWhereNameDefaultValue != '') {
            $.ajax({
                url: ajaxSorterCitiesQuery,
                cache: false,
                dataType: "json",
                success: function(data) {
                    sorter_ZoomResults(data);
                },
                error: function() {
                    //alert("error" + arguments[0].responseText);
                },
                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 ((typeof 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) {
    var i;
    for (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:checked").val();
    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 && searchType != "heading") {
            $("#_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:checked").val();
    $("#headingCode").val((searchType == "heading") ? $("#headingCode").val() : "");
    var searchTextValue = $("#_search_text").val();
    if (searchTextValue.replace(/[^a-zA-Zא-ת0-9]/g, "") == "")
    {
        $("#_search_text").val("");
        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((helpers.isCountryWide($("#_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 i, vArgs = fTags2Entites.arguments;
    for (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;');
        var slashCount = vArgs[i].value.match(/[\\]*$/);
        if (slashCount != null && slashCount[0].length % 2 == 1) vArgs[i].value = vArgs[i].value.replace(/\\$/, "\\\\");
    }
}

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() {
    function formSubmitSuccess(currentForm)
    {
     currentForm.find(".success").show();
     currentForm.find(".failure, .form").hide();
     currentForm.parent().parent().find(".external-form").hide();
    }
    function formSubmitFailure(currentForm)
    {
     currentForm.find(".success, .form").hide();
     currentForm.find(".failure").show();
     currentForm.parent().parent().find(".external-form").hide();
    }
    if ($('#ResultNotFound_busName').val().length == 0) {
        alert('יש למלא את שם בית העסק');
        return false;
    }
    if ($('#ResultNotFound_busAddress').val().length == 0) {
        alert(' יש למלא את כתובת בית העסק');
        return false;
    }
  if (vPageName == "Integration-SEO-PopularHeadings")
  {
   var currentForm = $("form[name=ResultNotFound_Form]");
   var parameters = {};
   currentForm.find("*[name]").each(function(i,e) { parameters[$(e).attr("name")] = $(e).val(); });
   $(document).ajaxError(function () { formSubmitFailure(currentForm) });
   $.ajax({
           url: currentForm.attr("action"),
           data: parameters,
           success: function() { formSubmitSuccess(currentForm) },
           error: function() { formSubmitFailure(currentForm) }
          });
   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();
}

var phonePlayerAudioElement = document.createElement("AUDIO");
function buildPhonePlayer(custId, headingCode, RandomFileName, contDivSelector) {
 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';
 if (document.createElement("AUDIO").canPlayType &&
     document.createElement("AUDIO").canPlayType("audio/x-wav") != "")
 {
  try  {   phonePlayerAudioElement.currentTime = 0;  }  catch(e)  {  }
  phonePlayerAudioElement.src = filepath;
  phonePlayerAudioElement.play();
 }
 else
 {
  if ($('#phonePlayer').length == 1) $('#phonePlayer').remove(); 
  var player = "wmp";
  if (navigator.plugins.length > 0)
   for (x in navigator.plugins)
   {
    var _pluginName = navigator.plugins[x].name.toLowerCase();
    if (_pluginName.indexOf("windows media") != -1)
    {
      player = "wmp";
      break;
    }
    if (_pluginName.indexOf("quicktime") != -1)
      player = "qt";
    if (_pluginName.indexOf("mplayer") != -1 && player != "qt")
      player = "mp"
   }
  if (player == "wmp")
   $("body").append('<object id="phonePlayer" width="1" height="1" classid="clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95" type="application/x-oleobject">' +
    '<param name="FileName" value="' + filepath + '"><param name="AutoPlay" value="true" />' +
    '<param name="AutoStart" value="true" /><param name="ShowControls" value="false" /><param name="ShowStatusBar" value="false" /><param name="ShowDisplay" value="false"/>' +
    '<embed id="MediaPlayerEmbed" TYPE="application/x-mplayer2" FileName="' + filepath + '" name="NumberMediaPlayer" ' +
    'width="1" AutoPlay="true" AutoStart="true" height="1" ShowControls="false" ShowStatusBar="false" ShowDisplay="false"></embed></object>');
  else if (player == "qt")
    $(contDivSelector).append('<embed src="' + filepath + '" width="1" height="1" autoplay="true" controller="false" loop="false" pluginspage="http://www.apple.com/quicktime/">');
  else if (player == "mp")
   $(contDivSelector).append('<embed width="1" height="1" id="phonePlayer" type="audio/x-wav" src="' + filepath + '" autostart="1" autoplay="1"></embed>');
 }
}

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') });
}

function reportClickTale(filter)
{
     if(typeof ClickTaleTag=="function")
        ClickTaleTag(filter);
}

function showServiceWarrantyOverlay(url, friendly)
{
 var serviceWarrantyProperties = {
                                  opacity: 0.55,
                                  scrollbars: false,
                                  href: url,
                                  open: true,
                                  iframe: true,
                                  width: 600,
                                  height: 520
                                 };
 if (friendly)
 {
  if ($("object#Player").length != 0 &&
      typeof SwitchPlayerState != "undefined" &&
      typeof StopMe != "undefined")
  {
   StopMe();
   SwitchPlayerState(8);
  }
  $.colorbox? $.colorbox(serviceWarrantyProperties): $.fn.colorbox(serviceWarrantyProperties);
 }
 else
  window.parent.$.colorbox? window.parent.$.colorbox(serviceWarrantyProperties): window.parent.$.fn.colorbox(serviceWarrantyProperties);
}

function showFullIndexDescription()
{
 $(".full-index-description").show();
 $(".index-description-summary").hide();
}

function addToFavorites(e)
{
}

function showTrafficReports()
{
 if (vPageName == "Integration-Maps" || ((vPageName == "Summaries" || vPageName == "Business-Results") && vIsShowMap == "1"))
 {
  $("#Traffic").click();
 }
 else
 {
  location.href = "http://map.d.co.il/#!/traffic/on";
 }
}

if (!window.gpi)
{
 window.gpi = {};
}
if (!gpi.history)
{
 gpi.history = {};
}
gpi.history.types = {BUSINESS_QUERY: "business", LOCATION_QUERY: "location", CUSTOMER: "customer"};
gpi.history.unifyDomainHistory =
 function ()//domain, key, value)
 {
 };
gpi.history.updateHistory =
 function(entry, type)
 {
  var key, domain;
  if (entry.pop && entry.length > 0 && entry[0] === "")
  {
   return;
  }
  key = gpi.history.getKeyNameByType_(type);
  domain = (location.host.match("www.d.co.il") !== null)? "map.d.co.il": "www.d.co.il";
  gpi.history.addHistoryEntry_(key, entry);
  gpi.history.unifyDomainHistory(domain, key, entry);
 };
gpi.history.getKeyNameByType_ =
 function (type)
 {
  // "gsi" due tolegacy issues.
  return "gsi-history-" + type;
 };
gpi.history.addHistoryEntry_ =
 function (key, value)
 {
  var i, j, same, currentEntries;
  currentEntries = JSON.parse(localStorage[key] || "[]");
  for (i = 0; i < currentEntries.length; i++)
  {
   same = true;
   for (j = 0; j < value.length; j++)
   {
    if (currentEntries[i][j] !== value[j])
    {
     same = false;
    }
   }
   if (same)
   {
    currentEntries.splice(i,1);
    break;
   }
  }

  if (currentEntries.length === 4)
  {
   currentEntries.pop();
  }
  currentEntries.unshift(value);
  localStorage[key] = JSON.stringify(currentEntries);
 };
gpi.history.getHistoryEntries =
 function (type, count)
 {
  var i, entries = [], currentEntries;
  currentEntries = JSON.parse(localStorage[gpi.history.getKeyNameByType_(type)] || "[]");
  for (i = 0; i < currentEntries.length && i < count; i++)
  {
   entries.push(currentEntries[i]);
  }
  return entries;
 };
gpi.history.decodeQueryStringEntry =
 function ()
 {
  var queryString, key, value, keyValue1, keyValue2;
  if (location.search.length > 0)
  {
   queryString = location.search.substring(1).split("&");
   if (queryString.length === 2)
   {
    keyValue1 = queryString[0].split("=");
    keyValue2 = queryString[1].split("=");
    if (keyValue1.length === 2 && keyValue2.length === 2)
    {
     key = keyValue1[0] === "key"? keyValue1[1]: decodeURIComponent(keyValue2[1]);
     value = keyValue2[0] === "value"? keyValue2[1]: JSON.parse(decodeURIComponent(keyValue1[1]));
     gpi.history.addHistoryEntry_(key, value);
    }
   }
  }
 };
if (!gpi.pinnedSite)
{
 gpi.pinnedSite = {};
}
gpi.pinnedSite.jumpLists = {};
gpi.pinnedSite.jumpLists.createJumpList_ =
 function(name)
 {
  window.external.msSiteModeCreateJumplist(name);
 };
gpi.pinnedSite.jumpLists.addJumpListItem_ =
 function (name, URL, icon)
 {
  window.external.msSiteModeAddJumpListItem(name, URL, icon);
 };
gpi.pinnedSite.jumpLists.showJumpList_ =
 function ()
 {
  window.external.msSiteModeShowJumpList();
 };
gpi.pinnedSite.jumpLists.clearJumpList_ =
 function ()
 {
  window.external.msSiteModeClearJumpList();
 };
gpi.pinnedSite.jumpLists.createBusinessQueryURL_ =
 function (businessQueryURL, name, location, searchType)
 {
  var templateAnchor = document.createElement("a");
  templateAnchor.href = (businessQueryURL.match(/^(http:\/\/|\/)/) !== null? "": "/") + businessQueryURL;
  if (templateAnchor.search.length > 1)
  {
   templateAnchor.search = templateAnchor.search.replace(/([_]*where_name|[_]*search_text)=[^&]+[&]*/g, "") + "&page=Summaries&";
  }
  else
  {
   templateAnchor.search = "?page=Summaries&";
  } 
   
  templateAnchor.search += "search_type=" + searchType + "&search_text=" + name + (location? "&where_name=" + location: "");
  templateAnchor.search += "&str=אבג&ref=IE9";
  return templateAnchor.href;
 };
gpi.pinnedSite.jumpLists.createLocationQueryURL_ =
 function (locationQueryURL, location, destination)
 {
  var templateAnchor = document.createElement("a");
  templateAnchor.href = (locationQueryURL.match(/^http:\/\//) !== null? "": "/") + locationQueryURL;

  if (templateAnchor.search.length > 1)
  {
   templateAnchor.search += "&";
  }
  else
  {
   templateAnchor.search = "?";
  }

  templateAnchor.search = "saddressHP=" + location + (destination? "&daddressHP=" + destination: "");
  
  templateAnchor.search += "&str=אבג&ref=PinnedSite";
  return templateAnchor.href;
 };
gpi.pinnedSite.jumpLists.createCustomerURL_ =
 function (baseCustomerURL, customerID, headingCode)
 {
  return baseCustomerURL.replace("CUSTOMER_ID", customerID).replace("HEADING_CODE", headingCode) + "?ref=IE9";
 };
gpi.pinnedSite.jumpLists.addHistoryJumpList =
 function ()
 {
    var i, businessQueryURL, locationQueryURL, customerURL, itemURL, location, destination,
        businessQueries, locationQueries, customers, prefix, name, where;
    businessQueryURL = $(".saved-state-for-business-searching").val();
    locationQueryURL = $(".saved-state-for-location-searching").val();
    customerURL = "//" + window.location.host + "/CUSTOMER_ID/HEADING_CODE/";
    businessQueries = gpi.history.getHistoryEntries(gpi.history.types.BUSINESS_QUERY, 4);
    locationQueries = gpi.history.getHistoryEntries(gpi.history.types.LOCATION_QUERY, 3);
    customers = gpi.history.getHistoryEntries(gpi.history.types.CUSTOMER, 3);
    if (businessQueries.length + locationQueries.length + customers.length === 0)
    {
     return;
    }
    gpi.pinnedSite.jumpLists.clearJumpList_();
    gpi.pinnedSite.jumpLists.createJumpList_("חיפושים אחרונים");
    
    for (i = 0; i < businessQueries.length; i++)
    {
     prefix = "תוצאות חיפוש: ";
     name = prefix + businessQueries[i][0];
     where = null;
     if (businessQueries[i][1] && !helpers.isCountryWide(businessQueries[i][1]))
     // && businessQueries[i][1] != ""
     {
      name += " ב" + businessQueries[i][1];
      where = businessQueries[i][1];
     }
     itemURL = gpi.pinnedSite.jumpLists.createBusinessQueryURL_(businessQueryURL,
                                                          businessQueries[i][0],
                                                          where,
                                                          businessQueries[i][2]);
     gpi.pinnedSite.jumpLists.addJumpListItem_(name, itemURL, "/Hebrew/fav.ico");
    }
    
    for (i = 0; i < locationQueries.length; i++)
    {
     location = locationQueries[i][0];
     destination = locationQueries[i][1];
     name = location;
     if (destination && !helpers.isCountryWide(destination))
     // && destination != ""
     {
      name = "מ" + name + " אל " + destination;
     }
     else
     {
      destination = null;
     }
     itemURL = gpi.pinnedSite.jumpLists.createLocationQueryURL_(locationQueryURL,
                                                          location, destination);
     gpi.pinnedSite.jumpLists.addJumpListItem_(name, itemURL, "/Hebrew/fav.ico");
    }
    
    for (i = 0; i < customers.length; i++)
    {
     prefix = "בית עסק: ";
     name = prefix + customers[i][0];
     itemURL = gpi.pinnedSite.jumpLists.createCustomerURL_(customerURL, customers[i][1], customers[i][2]);
     gpi.pinnedSite.jumpLists.addJumpListItem_(name, itemURL, "/Hebrew/fav.ico");
    }
    gpi.pinnedSite.jumpLists.showJumpList_();
 };

gpi.pinnedSite.previewButtons = {};
gpi.pinnedSite.previewButtons.buttons = {};
gpi.pinnedSite.previewButtons.addPreviewButton_ =
 function (icon, tooltip)
 {
  try
  {
   return window.external.msSiteModeAddThumbBarButton(icon, tooltip);
  }
  catch (e)
  {
   return null;
  }
 };
gpi.pinnedSite.previewButtons.removePreviewButton_ =
 function (buttonID)
 {
  try
  {
   window.external.msSiteModeUpdateThumbBarButton(parseInt(buttonID, 10), false, false);
  }
  catch (e) {}
 };
gpi.pinnedSite.previewButtons.enablePreviewButton_ =
 function (buttonID)
 {
  try
  {
   window.external.msSiteModeUpdateThumbBarButton(parseInt(buttonID, 10), true, true);
  }
  catch (e) {}
 };
gpi.pinnedSite.previewButtons.disablePreviewButton_ =
 function (buttonID)
 {
  try
  {
   window.external.msSiteModeUpdateThumbBarButton(parseInt(buttonID, 10), false, true);
  }
  catch (e) {}
 };
gpi.pinnedSite.previewButtons.handlePreviewButtonClick_ =
 function (e)
 {
  var button = gpi.pinnedSite.previewButtons.buttons[e.buttonID];
  if (button)
  {
   if (button.action)
   {
    button.action();
   }
   if (button.focus)
   {
    window.focus();
   }
  }
 };
gpi.pinnedSite.previewButtons.createPreviewButtonEntry_ =
 function (jElement, icon, type, tooltip, buttons, focus)
 {
  var button =
   {
    icon: icon,
    action:
     function()
     {
      jElement.click();
      if (jElement.attr("href"))
      {
       window.location.href = jElement.attr("href");
      }
     },
    type: type,
    tooltip: tooltip,
    focus: (typeof focus !== "undefined"? focus: true),
    active: jElement.length > 0
   };
  buttons.push(button);
 };
gpi.pinnedSite.previewButtons.showPreviewButtons_ =
 function ()
 {
  window.external.msSiteModeShowThumbBar();
 };
gpi.pinnedSite.previewButtons.cleanUp_ =
 function ()
 {
  $.each(gpi.pinnedSite.previewButtons.buttons,
         function(i)
         {
          gpi.pinnedSite.previewButtons.removePreviewButton_(i);
         });
 };
gpi.pinnedSite.previewButtons.listBusinessPreviewButtons =
 function (business)
 {
  var buttons = [];
  gpi.pinnedSite.previewButtons.createPreviewButtonEntry_(
   (business?
     $(".customer-menu .general-info-tab-button a"):
     $("none.non-existing-element")),
   "/Hebrew/images/Icons/previewButtons/info.ico",
   "general-info",
   "מידע כללי",
   buttons);
  gpi.pinnedSite.previewButtons.createPreviewButtonEntry_(
   (business?
     $(".customer-side-menu .free-call-button"):
     $("none.non-existing-element")),
   "/Hebrew/images/Icons/previewButtons/freeCall.ico",
   "free-call",
   "שיחת חינם",
   buttons);
  gpi.pinnedSite.previewButtons.createPreviewButtonEntry_(
   (business?
     $(".customer-side-menu .sms-to-mobile-button"):
     $("none.non-existing-element")),
   "/Hebrew/images/Icons/previewButtons/send2mobile.ico",
   "send-to-mobile",
   "שלח את פרטי העסק לנייד",
   buttons);
  gpi.pinnedSite.previewButtons.createPreviewButtonEntry_(
   (business?
     $(".customer-side-menu .website-button a"):
     $("none.non-existing-element")),
   "/Hebrew/images/Icons/previewButtons/site.ico",
   "customer-website",
   "אתר בית העסק",
   buttons);                                       
  gpi.pinnedSite.previewButtons.createPreviewButtonEntry_(
   (business?
     $(".customer-menu .coupon-tab-button a"):
     $("none.non-existing-element")),
   "/Hebrew/images/Icons/previewButtons/coupon.ico",
   "coupon",
   "הטבה",
   buttons);
  return buttons;
 };
gpi.pinnedSite.previewButtons.listSearchResultPreviewButtons =
 function (results)
 {
  var buttons = [];
  gpi.pinnedSite.previewButtons.createPreviewButtonEntry_(
   (results?
     $(".rightSide .mapR"):
     $("none.non-existing-element")),
   "/Hebrew/images/Icons/previewButtons/map.ico",
   "switch-to-map-view",
   "עבור לתצוגת מפה",
   buttons);
  gpi.pinnedSite.previewButtons.createPreviewButtonEntry_(
   (results?
     $(".articlesBox .articles-and-tips-link"):
     $("none.non-existing-element")),
   "/Hebrew/images/Icons/previewButtons/tips.ico",
   "articles-and-tips",
   "מדריכים וטיפים",
   buttons);
  return buttons;
 };
gpi.pinnedSite.previewButtons.addPreviewButtons =
 function (buttonList)
 {
  var buttonID, buttonsToHide = [], i;
  for (i = 0; i < buttonList.length; i++)
  {
   buttonID =
    gpi.pinnedSite.previewButtons.addPreviewButton_(
     buttonList[i].icon, buttonList[i].tooltip);
   if (buttonID)
   {
    if (buttonList[i].active)
    {
     gpi.pinnedSite.previewButtons.enablePreviewButton_(buttonID);
    }
    else
     {
      buttonsToHide.push(buttonID);
     }
    gpi.pinnedSite.previewButtons.buttons[buttonID] = buttonList[i];
   }
  }
  if (document.addEventListener)
  {
   document.addEventListener(
    "msthumbnailclick",
    gpi.pinnedSite.previewButtons.handlePreviewButtonClick_, false);
  }
  else
  {
   if (document.attachEvent)
   {
    document.attachEvent(
     "onmsthumbnailclick",
     gpi.pinnedSite.previewButtons.handlePreviewButtonClick_);
   }
  }
  gpi.pinnedSite.previewButtons.showPreviewButtons_();
  for (i = 0; i < buttonsToHide.length; i++)
  {
   gpi.pinnedSite.previewButtons.removePreviewButton_(buttonsToHide[i]);
  }
  $(window).bind(
   "beforeunload unload",
   gpi.pinnedSite.previewButtons.cleanUp_);
 };
gpi.pinnedSite.initializePinnedSiteOperations =
 function ()
 {
  var buttons, from, location, to;
  buttons =
   gpi.pinnedSite.previewButtons.listBusinessPreviewButtons(
    top == window && // Using "==" due to an Internet Explorer bug.
    vPageName.match(/Business-(Customer|Features)/) !== null);
  buttons =
   buttons.concat(
    gpi.pinnedSite.previewButtons.listSearchResultPreviewButtons(
     vPageName === "Business-Results" || vPageName === "Summaries"));
  if (vPageName === "Business-Results" || vPageName === "Summaries")
  {
   gpi.history.updateHistory(
    [vSearchText, vWhereNameDefaultValue,
     $("input[name=_search_type]:checked").val()],
    gpi.history.types.BUSINESS_QUERY);
  }
  if (vPageName === "Integration-Maps")
  {
   location = $("#fullAdress").val();
   from = $("#fromAddress").val();
   to = $("#toAddress").val();
   if ($("input[name=mapSearch_type]:checked").val() === "address" &&
       location)
   {
    to = from = null;
   }
   gpi.history.updateHistory(
    [(to && from)? from: location,
     (to && from)? to: location],
    gpi.history.types.LOCATION_QUERY);
  }
  if (vPageName.match(/Business-(Customer|Features)/) !== null)
  {
   gpi.history.updateHistory(
    [$("h1").text(), vCustId, vHeadingCode],
    gpi.history.types.CUSTOMER);
  }
  if (window == top) // Using "==" due to an Internet Explorer bug.
  {
   gpi.pinnedSite.previewButtons.addPreviewButtons(buttons);
  }
  gpi.pinnedSite.jumpLists.addHistoryJumpList();
 };
if (!gpi.premium)
{
 gpi.premium = {};
}
gpi.premium.rotateInline =
 function (adCount)
 {
  if (adCount === 0)
  { 
   return;
  }
  if (adCount > 1)
  {
   var STPRand = Math.floor(Math.random() * adCount);
   $("#STPpremiumFlash0").hide();
   $("#STPpremiumFlash" + STPRand).show();
  }
  // Removing the dotted line below the fifth result.
  $(".rightResultsColumn .dot-border:eq(4)").hide();
 };
if (!gpi.noProblem)
{
 gpi.noProblem = {};
}
gpi.noProblem.activateIFrame =
 function (selector)
 {
  var iFrame = document.getElementById(selector);
  if (iFrame)
  {
   iFrame.setAttribute(
    "src",
    iFrame.getAttribute("incomplete-src")
     .replace("$URL$", encodeURIComponent(location.href)));
   iFrame.removeAttribute("incomplete-src");
  }
 };

