function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
		window.onload = func;
	else
	{
		window.onload = function()
		{
			if (oldonload) oldonload();
			func();
		}
	}
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain )
{
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// this function gets the cookie, if it exists
function Get_Cookie( name )
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
	return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function checkEmail(str) {
///// function for validating email address
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)

		if (str.indexOf(at)==-1){
		    return false
		} else if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		    return false
		} else 	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		} else  if (str.indexOf(at,(lat+1))!=-1){
		    return false
		} else 	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		   return false
		} else  if (str.indexOf(dot,(lat+2))==-1){
		    return false
		} else if (str.indexOf(" ")!=-1){
		     return false
		} else {
 		 	return true
 		}
}

function getFlashMovieObject(movieName)
{
  if (window.document[movieName])
  {
      return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[movieName])
    {
      return document.embeds[movieName];
    }
  }
  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
  {
    return document.getElementById(movieName);
  }
}

function checkMultipleEmail(emails, split_char)
{
	emails_array = emails.split(split_char);
	checkStatus = true;
	for (e in emails_array)
	{
		if (trim(emails_array[e]) != "" && !checkEmail(trim(emails_array[e])))
			checkStatus =false;
	}
	return checkStatus;
}

function checkML(emailValue)
{
	if(!checkEmail(emailValue))
	{
		alert (_tpl_emailNotValid);
		document.joinML.focus();
		return false;
	} else {
		var url = _baseLang+"/xmlJoinML.php?joinML_email="+emailValue+"&heb="+heb;
		var xml = LoadXML(url);
		if(xml != null)
		{
			var message = xml.getElementsByTagName('rsp')[0].firstChild.data;
			alert(message);
			var response = xml.getElementsByTagName('rsp_stat')[0].firstChild.data;
			if (response)
				document.joinML.reset();
			else
				document.joinML.focus();
		}
		return false;
	}
}

function getHTTPObject()
{
	try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
	try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
	try { return new XMLHttpRequest(); } catch(e) {}
	alert("XMLHttpRequest not supported");
	return null;
 }

function LoadHTML(url)
{

	var xmlHttp = getHTTPObject();
	xmlHttp.open("GET",url, false);
	xmlHttp.onreadystatechange = function()
	{
		   if (xmlHttp.readyState != 4)  { return; }
		   var serverResponse = xmlHttp.responseText;

	}
	xmlHttp.send(null);
	return xmlHttp.responseText;
}
function LoadXML(url)
{
	var xmlHttp = getHTTPObject();
	xmlHttp.open("GET",url, false);
	xmlHttp.onreadystatechange = function()
	{
		   if (xmlHttp.readyState != 4)  { return; }
		   var serverResponse = xmlHttp.responseText;
	};
	xmlHttp.send(null);
	return xmlHttp.responseXML.documentElement;
}

function PostXML(url,params)
{
	xmlHttp = false;
	// branch for native XMLHttpRequest object
	if(window.XMLHttpRequest && !(window.ActiveXObject))
	{
		try {
			xmlHttp = new XMLHttpRequest();
		} catch(e) {
			xmlHttp = false;
		}
		// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject)
	{
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				xmlHttp = false;
			}
		}
	}

	if (xmlHttp)
	{
		xmlHttp.open( "POST", url, false );
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.send(params);
		return xmlHttp.responseXML.documentElement;
	}
}

// bulid string with the form values, fobj the form object, valFunc is validate function
function getFormValues(fobj)
{
   var str = "";
   var valueArr = null;
   var val = "";
   var cmd = "";

   for(var i = 0;i < fobj.elements.length;i++)
   {
       switch(fobj.elements[i].type)
       {
      	case "text":
           case "hidden":
           case "textarea":
           	str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&";
           break;

           case "radio":
           case "checkbox":
               if(fobj.elements[i].checked)
               		str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&";
           break;

           case "select-one":
                str += fobj.elements[i].name + "=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
           break;
       }
   }

   str = str.substr(0,(str.length - 1));
   return str;
}

// validate is got the validate function, if false then skip the validation
function submitAjaxForm(f,url)
{
   var str = getFormValues(f);
   xmlReq = postAjaxForm(url ,str);

 }

 function postAjaxForm(url,str)
{
   var doc = null
   if (typeof window.ActiveXObject != 'undefined' )
   {
       doc = new ActiveXObject("Microsoft.XMLHTTP");

   }
   else
   {
       doc = new XMLHttpRequest();
       doc.onload = displayState;
   }

   doc.open( "POST", url, true );
   doc.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
   doc.send(str);
   return doc.responseXML.documentElement;
}

function showMessage(message, elementID)
{
	document.getElementById(elementID).innerText=message;
}

function clearMessage(elementID)
{
	document.getElementById(elementID).innerText="";
}


function IsNumeric(sText)
{
   var ValidChars = "0123456789.-, ";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
 }

function trim(strText) {
/// TRIM STRING FUNCTION
    // this will get rid of leading spaces
    while (strText.substring(0,1) == ' ')
        strText = strText.substring(1, strText.length);
    // this will get rid of trailing spaces
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);
   return strText;
}

function escapeString(sString)
{
// DETECT WHAT TO PUT STRING IN FOR HTML FORM ( ' OR " ) DEPANDING ON STRING CONTENTS
	if (sString.indexOf("'") == -1)
		valSep = "'";
	else
		valSep = '"';
	return valSep+sString+valSep;
}

function replaceSubstring(inputString, fromString, toString) {
 // GOES THROUGH THE INPUTSTRING AND REPLACES EVERY OCCURRENCE OF FROMSTRING WITH TOSTRING
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
}

function popupWin(popUrl, width, height)
{
	if (!navigator.appName.indexOf("Microsoft")) width+=20;
	height+=5;
	topVar=((screen.height / 2)-(height/2));
	leftVar=((screen.width / 2)-(width/2));
	window.open(popUrl, "PopUp", "height="+height+", width="+width+", top="+topVar+", left="+leftVar+", scrollbars=yes, status=no, location=no, resize=yes, menubar=no, titlebar=no, toolbar=no");
}

function switchElementDisplay(elementID){
// SWITCH SELECTED ELEMENT DISPLAY: NONE/INLINE
	if (document.getElementById(elementID).style.display=="none")
		document.getElementById(elementID).style.display="inline";
	else
		document.getElementById(elementID).style.display="none";
}

// function used to initiate sound on homepage after page is loaded
function init_sound()
{
	soundStat = (Get_Cookie("soundStat")) ? Get_Cookie("soundStat") : 1;

	flashMovie=getFlashMovieObject("eq_button");
	flashMovie.SetVariable('soundStat', soundStat);
	flashMovie.Play();
}

function redirect(url)
{
	if (!url)
		return;
	location.href = url;
}


/**
Same as PHP's number format
*/
function number_format(num)
{
	var str = '' + num;		//no it's a string
	//is it real number?
	var real = false;
	var i;
	for (i=0; i<str.length; i++) {
		if (str.charAt(i) == '.') {
			real = i;
			break;
		}
	}

	var work_str = '';
	if (real === false)
		work_str = str;
	else
		work_str = str.substring(0, real);

	//group by 3's
	var temp_string = '';
	var j=0;
	for (i=work_str.length-1; i >= 0; i--) {
		if (j == 3) {
			j = 0;
			temp_string += ',';
		}

		temp_string += work_str.charAt(i);
		j++;
	}
	//reverse back
	var final_string = '';
	for (i=temp_string.length-1; i>=0; i--)
		final_string += temp_string.charAt(i);
	if (real != false)
		final_string += str.substring(real);
	return final_string;
}


/**
Fixes firefox input button text alignment
*/
function fixInputs(id)
{
	if (userAgentString) {
		if (userAgentString.match(/Firefox/)) {
			var obj = document.getElementById(id);
			obj.style.paddingBottom = '4px';
		}
	}
}

/*
Join mailing list
*/
function addToML(valObj)
{
	valObj = eval(valObj);
	ret = valObj.validateForm();
	if (!ret)
		return;

	var obj = document.getElementById('email');
	if (!obj)
		return;

	var email = obj.value;
	var cnt = document.getElementById('formContainer');
	var rsp = document.getElementById('formResponse');
	if (!cnt || !rsp)
		return;
	//hide form
	cnt.style.display = "none";
	//show progress bar
	rsp.innerHTML = '<div class="loaderBar"></div>'

	//add to mailing list
	advAJAX.get({
	    url: "tyco_joinML.ajax.php",
	    parameters : {
	      "joinML_email" : email
	    },
	    onSuccess : function(obj) {
	    	var xml = obj.responseXML.documentElement;
	    	var response = xml.getElementsByTagName('rsp_stat')[0].firstChild.data;
	    	var rsp = document.getElementById('formResponse');
	    	if (response == 'ok')
	    		rsp.innerHTML = _email_success;
	    	else
	    		rsp.innerHTML = _email_failure;
	    },
	    onError : function(obj) {
	    	var rsp = document.getElementById('formResponse');
    		rsp.innerHTML = _email_failure;
	    }
	});
}

function sendDealsForm(valObj)
{
	valObj = eval(valObj);
	ret = valObj.validateForm();
	if (!ret)
		return;

	//get data from form
	var first = document.getElementById('first').value;
	var last = document.getElementById('last').value;
	var phone = document.getElementById('phone').value;
	var email = document.getElementById('email').value;

	var cnt = document.getElementById('specialDealsJoin');
	var rsp = document.getElementById('formResponse');

	if (!cnt || !rsp)
		return;
	//hide form
	cnt.style.display = "none";
	rsp.innerHTML = '<div class="loaderBar"></div>'

	//add to list
	advAJAX.post({
	    url: "join_deals.ajax.php",
	    parameters : {
	      "first" : first,
	      "last" : last,
	      "phone" : phone,
	      "email" : email
	    },
	    onSuccess : function(obj) {
	    	var xml = obj.responseXML.documentElement;
	    	var response = xml.getElementsByTagName('rsp_stat')[0].firstChild.data;
	    	var rsp = document.getElementById('formResponse');
	    	if (response == 'ok')
	    		rsp.innerHTML = _deals_success;
	    	else
	    		rsp.innerHTML = _deals_failure;
	    },
	    onError : function(obj) {
	    	var rsp = document.getElementById('formResponse');
    		rsp.innerHTML = _email_failure;
	    }
	});

}

/*
Join special offers
*/

function openDealsForm()
{
	$("specialDealsJoin").show("slow");
	$("openForm").hide();
}

function fix_external_links() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");

	var basicPattern = new RegExp('^(http:\/\/|https:\/\/)');
	var pattern = new RegExp('^(http:\/\/|https:\/\/)'+location.hostname);

	for (var i = 0; i < anchors.length; i++)
	{
		var anchor = anchors[i];
		if (anchor.getAttribute("rel") && anchor.getAttribute("rel") == "external") {
			anchor.target = "_blank";
		}
		else if (!anchor.href.match(basicPattern))  // this is for links such as "javascript" or "#" which do not include http or https at all !!
			continue;
		else if (!anchor.href.match(pattern) && !anchor.getAttribute("rel") || (anchor.getAttribute("rel") && anchor.getAttribute("rel") != "ibox")) {
			anchor.target = "_blank";
		}
	}
}


function clearfld(curinput)
{
	if ((curinput.value==username_t))
	{
		curinput.value="";
	}
	else if (curinput.value==password_t && curinput.name=="passwordtxt")
	{
		curinput.style.display="none";
		document.getElementById('passwordlogin').style.display="inline";
		document.getElementById('passwordlogin').focus();
	}
	
}


function chkfld(curinput)
{
	if (curinput.value=="" && curinput.name=="userNamelog")
	{
		curinput.value=username_t;
	}
	else if (curinput.value=="" && curinput.name=="passwordlogin")
	{
		curinput.style.display="none";
		document.getElementById('passwordtxt').style.display="inline";
	}
	
}

function clearemail(curinput)
{
	if ((curinput.value==email_t))
	{
		curinput.value="";
	}
	
}


function chkemail(curinput)
{
	
	if (curinput.value=="")
	{
		curinput.value=email_t;
	}
	
}

function checkpass(curForm)
{
	if(curForm.reminderEmail.value=="")
	{
		alert(_alert_email);
		curForm.reminderEmail.focus();
		return false;
	}
	if (!checkEmail(curForm.reminderEmail.value))
	{
		alert(_tpl_emailNotValid);
		curForm.reminderEmail.focus();

		return false;
	}
}

function updateSubCat(f, cValue, subCateogory)
{
	subCat = f[subCateogory];
	subCat.options.length = 0;
	if (cValue != "" && cValue != "none")
	{
		var url = _baseLang+"/xml_TreeFunctions.php?operation=getChildren&parentID="+cValue;
		var xml = LoadXML(url);
		if(xml != null || xml.getElementsByTagName('rsp')[0].firstChild.data != "0")
		{
			total_subcat = xml.getElementsByTagName('num_rows')[0].firstChild.data;
			if (total_subcat == 1)
			{
				window.location.replace('?subgal='+xml.getElementsByTagName('id_0')[0].firstChild.data+'&selgal='+cValue+'#titleancor');
				document.getElementById('seclevel').style.display="none";
			}
			else
			{
				document.getElementById('seclevel').style.display="inline";
				subCat.options[0] = new Option (_choosegal,'');
				for (i=0; i<total_subcat; i++)
				{
					cOption = new Option (xml.getElementsByTagName('desc_'+i)[0].firstChild.data, xml.getElementsByTagName('id_'+i)[0].firstChild.data, false, false);
					subCat.options[i+1] = cOption;
				}
			}
			
		}
	}
	//window.location.replace('?subgal='+subCat.options[0].value+'&selgal='+cValue);
}

function selectOption(f, cValue)
{
	for (i=0; i<f.length; i++)
	{
		if (f[i].value == cValue)
		{
			f.selectedIndex = i;
			break;
		}
	}
}

function reloadCaptcha(cScheme)
{
	var captcha = document.getElementById("captcha_image");
	captcha.innerHTML = "<img src=\"CaptchaSecurityImages.php?cScheme="+cScheme+"&width=70&height=25&characters=5\" align=\"absmiddle\">";
}

function popupWinall(popUrl, width, height)
{
	window.open(popUrl);
	return false;
}

function corner_banner_max(banner_id) {
	b = document.getElementById(banner_id);
	b.style.width = "700px";
	b.style.height = "546px";
}

function corner_banner_min(banner_id) {
	b = document.getElementById(banner_id);
	b.style.width = "120px";
	b.style.height = "120px";
}

function checkCupon(cuoponid,crsid)
{
	cuponinpt = document.getElementById(cuoponid);
	if(cuponinpt.value=="")
	{
		alert(_alert_coupon_number);
		cuponinpt.focus();
		return false;
	}
	var url="mano_ajax.php?action=set_cuopon&id="+crsid+"&coupon_number="+cuponinpt.value;
	var xml = LoadHTML(url);
	if (xml != null && xml != "error") {
		alert (_cuopon_set_ok);
		window.location.reload();
	}
	else
	{
		alert (_cuopon_number_wrong);
		return false;
	}
	return false;
	
	
}

//open meesage smart
function openmessage(c_href)
{
	avalue=c_href.className;
	container = document.getElementById("faq_mc");
	cAnswer = c_href.nextSibling;
	cDisplay = cAnswer.style.display;
	for (i=0; i<container.childNodes.length; i++)
	{
		cElement = container.childNodes[i];
		if (cElement.className == "faq_answer")
			cElement.style.display = "none";
			/*if (cElement.className == "opened")
			cElement.className = "open";*/
	}
/*	if(avalue=="open")
	{
		c_href.className="opened";
	}
	else
	{
		c_href.className="open";
	}*/
	cAnswer.style.display = (cDisplay == "block" ) ? "none" : "block";
	return false;
}