﻿// JScript File
var isIE = document.all ? true : false;
var isIE6 = navigator.userAgent.toLowerCase().indexOf("msie 6.")>-1 ;
var isIE7 = navigator.userAgent.toLowerCase().indexOf("msie 7.")>-1 ;
var isIE8 = navigator.userAgent.toLowerCase().indexOf("msie 8.")>-1 ;
var isGecko = navigator.userAgent.toLowerCase().indexOf("gecko")>-1 ;
var isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
var isChrome = navigator.userAgent.toLowerCase().indexOf("chrome") > -1;

var is_print_local_page = false;

function Print(Path) {

    if (!is_print_local_page) {
        var print_page = window.open(Path + '?DisplayMode=Print', 'הדפס', 'height=500,width=700, scrollbars=1');
        print_page.focus();
        print_page.print();
        //print_page.close();
    } else {
        self.print();
    }
}

function SendMail(strSubject,strBody)
{
	window.location.href='mailto:?subject='+ strSubject + '&body='+strBody;
}



$(document).ready(function() {

    onLoad_MenuItemsTraversal(); //showing top corner menu items to flow during tab click
    onLoad_MenuToolbar(); //tab option accesability mode of top menu toolbar (opens menu by tab press)
    onLoad_FixInputClickEventsInsideTables();

    AddCustomLinks();
    extendElements();
    registerClientEvent();
    FixDisplay();
    if (isIE6) {
        FixIframe();
    }
    AddClasses();
    AddHomeBanner();
    AddRemarketingFrame();
    //AddStylesheets();
    //RewriteNetValidation();

});

function AddRemarketingFrame() {
    if (location.href.toLowerCase().indexOf('products/other+insurances/best+friend.htm') > -1 ){
        if ($("#MiddlePage")) {
            $("#MiddlePage").after('<iframe src="/phoenixMarketing/pages/pets_remarketing.htm" width="0" height="0" frameborder="0" scrolling="no" ></iframe>');
        }
    }
}



function AddHomeBanner() {
    var divLogInAgent = $("#_ctl0_divLogInAgent");
    if (!divLogInAgent) return;

    //divLogInAgent.after('<a href="http://www.fnx.co.il/Products/Vehicle+Insurance/hatavot" style=" " target="_blank" ><img  style="margin-top: 10px;  border: 0px; "src="/PhoenixMarketing/images/banner_hatavot_lemevutachim.jpg" alt="הטבות למבוטחי הפניקס בביטוח רכב" /></a>');
}

function AddCustomLinks() {
	var oFlash = $("#_ctl0_ContentPlaceHolder1_FlashPlaceholderControl1");
	var oSales = $("#_ctl0_ContentPlaceHolder1_SalesProcessUCl1_td_TravelControl");
	// is it homepage?
	//if (oFlash && oSales) oFlash.after('<div id="CommercialLink" >לצפייה  בפרסומת <a href="http://www.youtube.com/user/FNXinsurance" target="_blank" title="צפה בפרסומת בחלון חדש" >לחץ כאן</a></div>');
}

function FixDisplay() {
    if (location.search.toLowerCase().indexOf("displaymode=nomaster") > -1) {
        $("MiddlePage").css("width", "auto");
    }
    if (location.href.toLowerCase().indexOf("/adi") > -1) {
        $("#_ctl0_innerLeftMenu").hide();
        $("#innerRightMenu").hide();
        $("#_ctl0_McmsBreadcrumbControl1").hide();
        $("#_ctl0_MiddleDiv .SimplePageHebWrap ").css("margin-right", "0");
        //$("#_ctl0_MiddleDiv iframe ").attr("height" , "1300");
    }

}

function onLoad_FixInputClickEventsInsideTables() {
 $("input.GeneralDropDownButton")
    .parent("td")
    .prev()
    .css("cursor","pointer")
    .click(function() {
        $(this).parent("tr").find("input.GeneralDropDownButton").click();
    });
    
 $("input.GeneralDropDownButton")
    .parent("td")
    .next()
    .css("cursor","pointer")
    .click(function(){
        $(this).parent("tr").find("input.GeneralDropDownButton").click();
    });
 
 
 $("a.SearchBtnText")
    .parent("td")
    .prev()
    .click(function() {
        var aObj = $(this).parent("tr").find("a.SearchBtnText");
        switch (aObj.attr("title"))
        {
            case "חפש":
                aObj.click();
                break;
            case "נקה":
                eval(aObj.attr("href"));
                break;
        }
    });    
    
 $("a.SearchBtnText")
    .parent("td")
    .next()
    .click(function() {
        var aObj = $(this).parent("tr").find("a.SearchBtnText");
        switch (aObj.attr("title"))
        {
            case "חפש":
                aObj.click();
                break;
            case "נקה":
                eval(aObj.attr("href"));
                break;
        }
    });
}

function onLoad_MenuItemsTraversal() //right top corner menu items functionality during tab click
{

	$('<a href="#AFocus_Content" class="hiddenLinkMenu" title="דלג לתוכן" >דלג לתוכן</a>').appendTo('#HeaderSiteLinksMenu'); 

   $("#HeaderSiteLinksMenu a:first").focus(function(){ //focus anchor event for the first item (changing the height of container div also)
        $(this).parent()
               .addClass("visibleContainerTopMenu")
               .children("a").removeClass("visibleLinkMenu");
        $(this).addClass("visibleLinkMenu");
    });
    $("#HeaderSiteLinksMenu a:not(:first)").focus(function(){ //focus anchor event not for the first item
        $(this).parent().children("a").removeClass("visibleLinkMenu");
        $(this).addClass("visibleLinkMenu");
    });

    $("#HeaderSiteLinksMenu a").click(function(){ //click event
        $(this).parent().removeClass("visibleContainerTopMenu");
        $(this).blur();
    });

    $("#HeaderSiteLinksMenu a:not(:last)").blur(function(){ //blur anchor event not for the last item
        $(this).removeClass("visibleLinkMenu");
    });

    $("#HeaderSiteLinksMenu a:last").blur(function(){ //blur anchor event for the last item (reduces the height of the div container)
        $(this).removeClass("visibleLinkMenu");
        $(this).parent().removeClass("visibleContainerTopMenu");
    });
}

function onLoad_MenuToolbar() //tab option accesability mode of top menu toolbar (opens menu by tab press)
{
	$("li.submenu table a").bind("mouseenter focus", function() {
		$(this).closest("ul.first").find("ul.second").css("display", "none"); //hide every menu
		$(this).closest("table").next("ul.second").css("display", "block"); //open selected menu
		if (isIE6) { //hide all <select> elements in middle menu (bug in IE 6 showing selects faded behind drop-down lists)
			$("div[id$='MiddleDiv']").find("select").css("visibility", "hidden");
		}
		if ($(this).text().indexOf("כלים") > -1) {
			$(document.body).addClass("menuIsOpened");
		}
	});

    //li.submenu:not(:last)
    $("li.submenu").mouseleave ( function() {
        $(this).children("ul.second").css("display","none");
        if (isIE6) { //show all <select> elements in middle menu (bug in IE 6 showing selects faded behind drop-down lists)
             $("div[id$='MiddleDiv']").find("select").css("visibility","visible");
            }
            $(document.body).removeClass("menuIsOpened");
    });

    $("li.submenu:last ul.second a:last").blur(function(){ //hide the last menu when last element received blur event
    
        $(this).closest("ul.second").css("display","none");
        if (isIE6) { //show all <select> elements in middle menu (bug in IE 6 showing selects faded behind drop-down lists)
             $("div[id$='MiddleDiv']").find("select").css("visibility","visible");
            }
        $(document.body).removeClass("menuIsOpened");
    });
}


function addEvent(eventType,handlerFunc,addToObject){
	var o=(addToObject)?(addToObject):(window);if (o){
	if (window.attachEvent){o.attachEvent("on"+eventType,handlerFunc);}
	else if (window.addEventListener){o.addEventListener(eventType,handlerFunc,false);}
	}
}

function getNextNonTextSibling(el){
    while (el.nodeType==3) {
	    // whitespace in FireFox is a TextNode
		el = el.nextSibling;
    };
    return el;
}

function getPrevNonTextSibling(el){
    while (el.nodeType==3) {
	    // whitespace in FireFox is a TextNode
		el = el.previousSibling;
    };
    return el;
}

function AddStyleSheet(url, windowElement){

    if (!windowElement)windowElement=self;

    var link = windowElement.document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = url;

    var head = windowElement.document.head ? windowElement.document.head : windowElement.document.documentElement;
    head.appendChild (link);
}

function extendElements(){


     if ( typeof(HTMLElement)=="undefined" || typeof(HTMLElement.prototype.__defineGetter__)=="undefined" )return;

    var element = HTMLElement.prototype;
    if (element.__defineGetter__) {
         element.__defineGetter__("outerHTML",
               function () {
                      var parent = this.parentNode;
                      var el = document.createElement(parent.tagName);
                      el.appendChild(this);
                      var shtml = el.innerHTML;
                      parent.appendChild(this);
                      return shtml;
               }
         );
    }


    HTMLElement.prototype.__defineGetter__("innerText", function () {
        if (this.textContent){
            return(this.textContent)
        }else{
            var r=this.ownerDocument.createRange();
            r.selectNodeContents(this);
            return r.toString();
        }
    });
    HTMLElement.prototype.__defineSetter__("innerText", function (sText) {
        if  (this.textContent){
            this.innerHTML=sText.textContent;
        }else{
            this.innerHTML = sText;
        }
    });


}

function AddClasses() {

    var s = "";
    var qs = location.search;
    if (isIE)
	{
		 $(document.body).addClass("ie");

		 if (isIE6 || qs.indexOf("mimicie6") > -1) {
		     $(document.body).addClass("ie6");
		 } else if (isIE7 || qs.indexOf("mimicie7") > -1) {
		     $(document.body).addClass("ie7");
		 } else if (isIE8 || qs.indexOf("mimicie8") > -1) {
		     $(document.body).addClass("ie8");
		 }

	}else{

		if (isGecko){
			$(document.body).addClass("gecko");
		}
		if (isFirefox){
			$(document.body).addClass("firefox");
		}
		if (isChrome) {
			$(document.body).addClass("chrome");
		}
    }

}
function AddStylesheets(){
	var link = document.createElement("link");
	link.rel = "stylesheet";
	link.type = "text/css";
	link.href = "/PhoenixMarketing/SiteStyles/PersonalInfo/InfoPopUpStyleSheet.css";

	setTimeout(function() {document.body.appendChild(link)},2000);

}

function FixIframe(){
    var content = document.getElementById("content");
    if (!content)return;

	var arrIframes = content.getElementsByTagName("iframe");
	// var arrSelects = content.getElementsByTagName("select");

	var ifrmBtnSend = null;
	for (var i=0;i<arrIframes.length;i++){
		if (arrIframes[i].id && arrIframes[i].id.indexOf("ifrmBtnSend")>-1){
		  ifrmBtnSend = arrIframes[i];
		  break;
		}
	}


	if (ifrmBtnSend!=null){
		window.onscroll = function(){
			ifrmBtnSend.style.display = "none";
			setTimeout(function(){ifrmBtnSend.style.display = "";} , 100);
		}
	}
}

var myimages=new Array()
function preloadimages()
{
    for (i=0;i<preloadimages.arguments.length;i++)
    {
    myimages[i]=new Image()
    myimages[i].src=preloadimages.arguments[i]
    }
}

//Enter path of images to be preloaded inside parenthesis. Extend list as desired.
preloadimages("/PhoenixMarketing/Images/btn_90.jpg","/PhoenixMarketing/Images/header_nav_right.gif","/PhoenixMarketing/Images/header_nav_right_orange.gif","/PhoenixMarketing/Images/header_nav_orange_pixel.gif","/PhoenixMarketing/Images/header_nav_orange_pixel.gif","/PhoenixMarketing/Images/header_nav_pixel.gif","/PhoenixMarketing/Images/header_nav_pixel_on.gif","/PhoenixMarketing/Images/header_nav_left1.gif","/PhoenixMarketing/Images/header_nav_left_on.gif","/PhoenixMarketing/Images/nav_but_left.gif","/PhoenixMarketing/Images/header_nav_pixel.gif","/PhoenixMarketing/Images/nav_but_left_pixel.gif","/PhoenixMarketing/Images/dottedline_pixel.gif","/PhoenixMarketing/Images/Searchers/search_but_right.gif","/PhoenixMarketing/Images/Searchers/search_but_center.gif","/PhoenixMarketing/Images/Searchers/printtable_icon.gif","/PhoenixMarketing/Images/Searchers/search_but_left.gif","/PhoenixMarketing/Images/Master/Tab/tab_pixel_n.gif","/PhoenixMarketing/Images/ProductsFamily/search_orange_header_pixel.gif","/PhoenixMarketing/Images/Muzar/butt_info_pixel.gif","/PhoenixMarketing/Images/Muzar/registration_icon.gif","/PhoenixMarketing/Images/Homepage/logo.jpg","/PhoenixMarketing/Images/Master/600_800/icon_moked.gif","/PhoenixMarketing/Images/Master/600_800/icon_contact.gif","/PhoenixMarketing/Images/Searchers/but_ikon_send.gif","/PhoenixMarketing/Images/Searchers/printtable_icon.gif","/PhoenixMarketing/Images/Master/footer_gray_sep.gif","/PhoenixMarketing/Images/Master/footer_orange_sep.gif","/PhoenixMarketing/Images/Homepage/topandbox_notext.gif","/PhoenixMarketing/Images/Master/600_800/topandbox_notext.gif")


function registerClientEvent(){
	var oTxtSearch = document.getElementById("_ctl0_SearchBoxUC1_txtSearch");
	if(oTxtSearch){
		addEvent("keydown",
				function(e){
					var url = 'http://www.fnx.co.il/Services/SearchResult.htm?Advanced=yes&TextBoxWord={0}&TextBoxKeywords=&CheckInfoType=@&CheckCategory=@&CheckLookAt=@';
					clickOnEnter(e , oTxtSearch, url);
				},
				oTxtSearch);


	}
}

function clickOnEnter(evt , oTxt, url){
	var e = typeof(event)=="undefined" ? evt : event ;

	if (e){
		if (e.keyCode==10 || e.keyCode==13){
			if (oTxt.value.length>0){
				url = url.replace ("{0}" , encodeURIComponent(oTxt.value));
				location.href = url;
			}else{
				CancelEvent(e);
			}
		}
	}
}

function doFuncOnEnter(evt , oInput, func){
	var e = typeof(event)=="undefined" ? evt : event ;

	if (e){
		if (e.keyCode==10 || e.keyCode==13){
            func(oInput.value);
        }
	}
}

function RegisterEnterInContainerToButton(containerId, idToClick ){
    var oContainer = document.getElementById(containerId);
    if (!oContainer)return;

    var arrInputs = oContainer.getElementsByTagName("input");
    var arrDdls = oContainer.getElementsByTagName("select");

    for (var i=0;i<arrInputs.length;i++){
        if (arrInputs[i].type && arrInputs[i].type=="text"){
            RegisterEnterToButton(arrInputs[i], idToClick);
        }
    }

    for (var i=0;i<arrDdls.length;i++){
        RegisterEnterToButton(arrDdls[i], idToClick);
    }

}

//click another element programatically, when clicking an element
function RegisterEnterToButton(clickedIdOrElement, idToClick){

	if (!idToClick || idToClick=="")return;

	var oClicked = typeof(clickedIdOrElement)=="string" ? document.getElementById(clickedIdOrElement) : clickedIdOrElement;
	var oToClick = document.getElementById(idToClick);


	addEvent("keyup",function(evt){

            var e = typeof(event)=="undefined" ? evt : event ;

            if (e){
	            if (e.keyCode==10 || e.keyCode==13){
                    oToClick.click();
                    CancelEvent(evt);
                }
            }


		} ,oClicked);
}
// cancels the event passed
function CancelEvent(evt){
	var e = typeof(evt)!="undefined" ? evt : event;
	if (!e)return;
	var jEvent = jQuery.Event(e);
    jEvent.preventDefault()
    jEvent.isDefaultPrevented()
    jEvent.stopPropagation()
    jEvent.isPropagationStopped()
    jEvent.stopImmediatePropagation()
    jEvent.isImmediatePropagationStopped()

}



var lastInlineTermOpened  = null;
var oTermWrap = null;
function ShowInlineTerm(evt, title, desc ){

	oTermWrap = document.getElementById("inlineTermWrap");
	if (!oTermWrap){
		oTermWrap = document.createElement("div");
		oTermWrap.id = "inlineTermWrap";
		oTermWrap.style.position = "absolute";
		oTermWrap.style.left = "0";
		oTermWrap.style.top = "0";
		document.body.appendChild(oTermWrap);
	}

	 var layerContent = '<div class="InfoPopUpCloseDiv" >\
			</div>\
			<div class="InfoPopUpLowerMainText" >'+desc+'</div>\
			<div class="InfoPopUpBottomSection"></div>';



	var e = evt ? evt : window.event;

	var oLayer = document.createElement("div");
	oLayer.className = "InfoPopUpMainDiv inlineTerm";
	oLayer.style.visibility = "hidden";
	oLayer.style.left =  "-400px";
    oLayer.style.top =  "-400px";

	oLayer.innerHTML = layerContent;

	oTermWrap.appendChild(oLayer);


	var eX = (e.clientX ? e.clientX : e.x );
	var eY = (e.clientY ? e.clientY : e.y );
	var boxW = oLayer.clientWidth;
	var boxH = oLayer.clientHeight;

	var finalX = (eX - boxW/2 + (isIE ? 0 : 20 ));
	var finalY = (eY + document.documentElement.scrollTop - boxH  +(isIE ? 0  : 110 ));



    oLayer.style.visibility = "visible";
	oLayer.style.left =  finalX + "px";
    oLayer.style.top =  finalY + "px";

	HideInlineTerm();
	lastInlineTermOpened = oLayer;


}

function HideInlineTerm(){
	if (lastInlineTermOpened!=null){

		var oTermWrap = document.getElementById("inlineTermWrap");

		if (oTermWrap){
			try{
				oTermWrap.removeChild(lastInlineTermOpened);
			}catch(ex){}
		}


	}
}


function IsValidDate(date) {
    var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
    if (matches == null) return false;
    var d = matches[1];
    var m = matches[2] - 1;
    var y = matches[3];
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
    composedDate.getMonth() == m &&
    composedDate.getFullYear() == y;
}


function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}

//Intlock tracking code start

function __initCardioLogAgent() {
    if (typeof(document.__cardiolog) == "undefined") {
        document.__cardiolog = true;
	    var script = document.createElement("script");
	    script.src = "/CardioLogAgent/AgentEmbed.aspx?env=FNXCMS&r="+Math.random()*100000;
	    document.body.appendChild(script);
	}
}

if (location.host.toLowerCase().indexOf("fnx.co.il")>-1){
	if (typeof(document.__jsloaderInterval) == "undefined") {
	    if (navigator.userAgent.match(/Safari/i)) {
		    document.BrowserType = "safari";
		    document.__jsloaderInterval = window.setInterval(function() {
								    if(document.readyState == "loaded" || document.readyState == "complete") {
									    window.clearInterval(document.__jsloaderInterval);
									    __initCardioLogAgent();
								    }}, 10);
	    } else if (document.addEventListener) {
		    document.BrowserType = "ff";
		    document.addEventListener("DOMContentLoaded", __initCardioLogAgent, false);
	    } else if (document.all && !window.opera) {
		    document.BrowserType = "ie";
		    document.__jsloaderInterval = window.setInterval(function() {
								    if(document.readyState == "loaded" || document.readyState == "complete") {
									    window.clearInterval(document.__jsloaderInterval);
									    __initCardioLogAgent();
								    }}, 10);
	    }




	}
}
//Intlock tracking code end

function OpenSalesCollective(id) { 
	var Url = "https://www.fnx.co.il/Sales/Pages/Collective.aspx?id=" + id + "&cref=" + window.location.host; 
	window.open(Url,'','letf=0,top=0,width=735,height=680,toolbar=0,scrollbars=1,status=1,resizable=0'); 
}


