var m_xmlHttp		= createXmlHttpRequestObject();
var script_name;
var destination	= new Array();	
var cache		= new Array();	
var showError	= true;
var dest_current;
var ajax_req;
var br_iE;
var Browser = {  Version: function() {    var version = 999;    
																					if (navigator.appVersion.indexOf("MSIE") != -1)     
																						version = parseFloat(navigator.appVersion.split("MSIE")[1]);    
																					return version;  }
							}

function createXmlHttpRequestObject()
{
	var _xmlHttp;
	
	try
	{
		br_iE = 0;
		_xmlHttp = new XMLHttpRequest;
	}
	catch(e)
	{
		br_iE = 1;
		var XmlHttpVersion = new Array(
									   "MSXML2.XMLHTTP.6.0",
									   "MSXML2.XMLHTTP.5.0",
									   "MSXML2.XMLHTTP.4.0",
									   "MSXML2.XMLHTTP.3.0",
									   "MSXML2.XMLHTTP",
									   "Microsoft.XMLHTTP"
									   );
		for (var i=0; i<XmlHttpVersion.length && !_xmlHttp; i++)
		{
			try
			{
				_xmlHttp = new ActiveXObject(XmlHttpVersion[i]);
			}
			catch(e)
			{}
		}
	}
	if (!_xmlHttp) 
	{
		alert("Build Error XMLHttpRequest.");
	}
	else
	{
		return _xmlHttp;
	}
}



function handleRequestStateChange()
{

	if (m_xmlHttp.readyState == 4)
	{
	
		if(m_xmlHttp.status == 200)
		{
			try
			{
				readResponse();
			}
			catch(e)
			{
				displayError(e.toString());
			}
		}
		else
		{
			displayError(m_xmlHttp.statusText);
		}
	}
}


function fnShowProps(obj, objName)
{
    var result = "";
	
 
	for (var i in obj) 
	{
		result += objName + "." + i + " = " + obj[i] + "";
	}
    alert(result);
}



//  (טקסט פשוט לא XML ) תוצאות הבקשה
function readResponse()
{
	//  ID לדיב מהקובץ
	var div_id = destination.shift();
	
	
	
	// Если при вызове AJAX не был указан DIV, в который необходимо
	// вывести HTML с результатами работы скрипта, 
	// то не будем обрабатывать вывод результатов совсем.
	if ( div_id != '' && document.getElementById(div_id) )
	{
		// Если передан ID дива для вывода результатов работы скрипта
		// и такой див найден...
		var div = document.getElementById(div_id);		
		var response =m_xmlHttp.responseText;		
		try
		{
			div.innerHTML = response;
		}
		catch(er)
		{
			div.innerHTML = response;
		}
	}

	/*if(!response || !response.documentElement)
		throw("Неправильная структура XML"+xmlHttp.responseText);

	var rootNodeName = response.documentElement.nodeName;

	if(rootNodeName=="parsererror")
		throw("Неправильная структура XML"+xmlHttp.responseText);	*/
	//var arrCnt = response.getElementsByTagName('content');

	// заменим HTML на результат запроса

	//только в случае корзины
	//if(div_id=="cnt_basket")
	//	ChangeBasket();

	//следующий запрос (если есть в очереди запросы, это проверятся в самом методе)
	getAjaxRequest();
}

function displayError($message)
{
	if (showError)
	{
		alert("Error: \n" + $message);
	}
}


// בקשה לשרת XMLHttpRequest (תבנית - xmlHttp)
function getAjaxRequest()
{
	document.body.style.cursor = 'default';	
	
	if (m_xmlHttp)
	{		 
		try
		{
			if ( (m_xmlHttp.readyState == 4 ||m_xmlHttp.readyState == 0) && cache.length >0 )
			{
				document.body.style.cursor = 'wait';		
				
				var cacheEntry = cache.shift();
				m_xmlHttp.open("POST", script_name, true);
				m_xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				m_xmlHttp.onreadystatechange = handleRequestStateChange;
				m_xmlHttp.send(cacheEntry);
			}
		}
		catch (e)
		{
			location.reload();
			/*fnShowProps(location, "location");*/
			/*displayError(e.toString());*/
		}
	}
}

function SetTabImage(path)
{
	var base = "url(Images/Main/Zap/";
	if(location.href.indexOf("news") > 0)
	{
		if(path.indexOf("Tab") > 0)
			return "url(../Images/News/Design/KoogleTab.gif)";
		else 
			return base.replace("(Images", "(../Images") + path + ")";
	}
	else
		return base + path + ")";
}

function KoogleTads_MouseOver(index, sender)
{		
	var defaultTab = document.getElementById("KoogleTabsMid");
	var FormBG =SetTabImage("KoogleTabs.gif");
	var ListBG =SetTabImage("TabsBox.gif");
	var TourBG = SetTabImage("TourismIcon.png");
	var RestBG = SetTabImage("RestIcon.png");
	
	
	if(index < 2)
	{
		defaultTab.style.display = "block";
		document.getElementById("OtherTabs").style.display = "none";
		document.getElementById("KoogleTabs").style.backgroundImage = FormBG;
		
		if(index==0)
		{
			sender.innerHTML = "מסעדות כשרות";
			document.getElementById("KoogleTabsMid").style.backgroundImage = RestBG;
			document.getElementById("dvFoodType").style.display = "block";
			document.getElementById("KosherChkBoxes").style.display = "block";
			document.getElementById("TourismChkBox").style.display = "none";
			document.getElementById("ctl00_ContentPlaceHolder1_hdnIsTourism").value = "0";	
			document.getElementById('FoodDdl').style.display='block';
			document.getElementById('ZimmersLinks').style.display='none'		
		}
		else
		{
			document.getElementById("KoogleTabsRest").innerHTML = "מסעדות";
			document.getElementById("KoogleTabsMid").style.backgroundImage = TourBG;			
			document.getElementById("dvFoodType").style.display = "none";
			document.getElementById("KosherChkBoxes").style.display = "none";
			document.getElementById("TourismChkBox").style.display = "block";	
			document.getElementById("ctl00_ContentPlaceHolder1_hdnIsTourism").value = "1";
			document.getElementById("ctl00_ContentPlaceHolder1_rdHotel").checked = true;					
		} 				
	}
	else
	{
		
		script_name	= "HomeLinks.aspx";
		destination.push("OtherTabs");
		//ajax_req ="subject=" + index;
		cache.push(ajax_req);
		getAjaxRequest();	
		defaultTab.style.display = "none";
		document.getElementById("OtherTabs").style.display = "block";
		
		document.getElementById("KoogleTabs").style.backgroundImage =  ListBG; 
	}
	
	var tabs = sender.parentNode.parentNode.getElementsByTagName("div");
	for ( i = 0; i < tabs.length; i++)
		tabs[i].className = "Tabs";
		
	sender.parentNode.className = "TabChosen";
		
}

function Title_Click(id,sender,HasMail)
{
	var TheDiv = document.getElementById("Details" + id);			
	if(trim(TheDiv.innerHTML) == "" || TheDiv.style.display == "none")
		Details_Click(id,sender,HasMail);
	else
		btnClose_Click(id,sender);
	
	
	
}

function Details_Click(id,sender,HasMail)
{
	var TheDiv = document.getElementById("Details" + id);	
	var DivBtns = document.getElementById("Buttons" + id);;
	var lnkDetails = document.getElementById("lnkDetails" + id);	
	var Close =  document.getElementById("closeDetails" + id);	
	var hdnIsOpen =	document.getElementById("hdnDetailsStatus" + id);
	var ShowGallery = "";
	var ShowContact = "";
	
	if(hdnIsOpen.value == "0")
	{
			if(sender.id	== "lnkContact" || sender.className == "Contact")
						ShowContact = "&Contact=1";	
			else if(sender.id	== "lnkGallery" || sender.className == "GalleryTrue")
					ShowGallery += "&ShowGallery=1";
						
				if(TheDiv.innerHTML == "" || (/^\s*$/.test(TheDiv.innerHTML)) )
				{
					script_name	= "SingleItem.aspx";
					destination.push("Details" + id);
					
					// Create AJAX query
					ajax_req = "ID=" + id;
					ajax_req += document.getElementById("hdnIsTabs" + id).value == "True"? "&Gallery=1" : "";					
					ajax_req += ShowContact + ShowGallery;					
					// Add new query
					cache.push(ajax_req);
					
					// Send AJAX request to server
					getAjaxRequest();			
				}
				else		
					TheDiv.style.display = "block";					
			
					
				script_name	= "ItemTabs.aspx";
				var additionalDiv = document.getElementById("ItemTabs" + id);
				additionalDiv.OldHTML = additionalDiv.innerHTML;
						
				destination.push("ItemTabs" + id);
				ajax_req = document.getElementById("hdnIsTabs" + id).value == "True"? "Gallery=1" : "";
				ajax_req += ShowContact + ShowGallery;	
					
				ajax_req += "&HasMail=" + HasMail.toString();
				cache.push(ajax_req);
				getAjaxRequest();
				TheDiv.className = "TabsContainer";				
				lnkDetails.OldValue =	 lnkDetails.innerHTML;
				DivBtns.style.display = "none";
				if(Browser.Version() < 7)
				{
					var Bottom = document.getElementById("Bottom" + id);
					Bottom.style.position = "relative";
					Bottom.style.top = "-20px";	
				}	
				Close.style.display = "block";				
				hdnIsOpen.value = "1";					
	}
	
	
}

function btnClose_Click(id,sender)
{
		var TheDiv = document.getElementById("Details" + id);	
		var DivBtns = document.getElementById("Buttons" + id);;
		var ItemContainer = sender.parentNode;
		var Close =  document.getElementById("closeDetails" + id);
		var hdnIsOpen =	document.getElementById("hdnDetailsStatus" + id);
		
		if(hdnIsOpen.value == "1")
		{			
			TheDiv.style.display = "none";
			Close.style.display = "none";
			DivBtns.style.display = "block";
			if(Browser.Version() < 7)
			{
					var Bottom = document.getElementById("Bottom" + id);
					Bottom.style.position = "static";	
			}									
			hdnIsOpen.value = "0"; 						
			var additionalDiv = document.getElementById("ItemTabs" + id);
			additionalDiv.innerHTML = additionalDiv.OldHTML;
			
		}
	
}

function GetWebControl(id)
{
	var Prefix = "";
	var arrPrefix = new Array("","ctl00_","ContentPlaceHolder1_");
	var Elemnt = null;
	for(var i = 0 ; i < arrPrefix.length; i++)
	{
		Prefix += arrPrefix[i];
		Elemnt = document.getElementById(Prefix + id);
		if(Elemnt != null)
			return Elemnt;
	}
	
}

function SendContact()
{
	
	var name = GetWebControl("txtName");
	var phone = GetWebControl("txtPhone");
	var mail = GetWebControl("txtEmail");
	var id = GetWebControl("hdnItemID");
	var Message =	GetWebControl("txtContent");
	var companyMail = GetWebControl("hdnEmail");
	var CompanyName = GetWebControl("hdnCompanyName");
	var iSubject = GetWebControl("txtSubject");
	var bValid = true;
	bValid = ValidateContact(name);
	bValid = true? ValidateContact(mail): false;		
	
	if(!bValid)
		return;
	if(!emailCheck(mail.value))
	{
		 document.getElementById("EmailValidation").innerHTML = "!";
		 return;
	}
		 
	
	var _name =  "Name="	 + encodeURIComponent(name.value); 
	var _phone = "&Phone="	 + encodeURIComponent(phone.value); 
	var _mail = "&Mail="	 + encodeURIComponent(mail.value);
	var _id = id.value != "" ? "&ID="	 + id.value  : ""; 
	var _Message =	Message.value != "" ? "&Message="	 + Message.value  : ""; 
	var _companyMail = companyMail.value != "" ? "&MailCom="	 + encodeURIComponent(companyMail.value)  : ""; 
	var _CompanyName= CompanyName.value !=""? "&NameCom=" + encodeURIComponent(CompanyName.value) : "";
	var _iSubject = "&Subject="	 + encodeURIComponent(iSubject.value); 
	
	script_name	= "SendContact.aspx";
	destination.push("Confirm");
	// Create AJAX query
	ajax_req = _name + _phone + _mail  + _id + _Message + _CompanyName + _companyMail + _iSubject;
	
	
	// Add new query
	cache.push(ajax_req);
	
	// Send AJAX request to server
	getAjaxRequest();	
	
	name.value = "";
	phone.value = "";
	mail.value = "";
	id.value = "";
	Message.value = "";
	companyMail.value = "";
	iSubject.selectedIndex = 0;
	
}

function ValidateContact(field)
{
	var validationId = field.id;
	validationId = validationId.replace("txt","");
	validationId += "Validation";
	var validationfield = document.getElementById(validationId);
	if(field.value == "")
	{
		validationfield.innerHTML = "!";
		return false;
	}
	else
	{
		validationfield.innerHTML = "";
		return true;
	}	
	
}

function emailCheck(emailStr)
{	
		/* The following pattern is used to check if the entered e-mail address
		fits the user@domain format. It also is used to separate the username
		from the domain. */
		//var emailPat=/^(.+)@(.+)$/
		var emailPat=/^([a-zA-Z0-9._-]+)@(.+)$/;	
		/* The following string represents the pattern for matching all special	
		characters. We don't want to allow special characters in the address. 
		These characters include ( ) < > @ , ; : \ " . [ ] */	
		var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
		/* The following string represents the range of characters allowed in a 
		username or domainname. It really states which chars aren't allowed. */
		var validChars="\[^\\s" + specialChars + "\]"; 
		/* The following pattern applies if the "user" is a quoted string (in
		which case, there are no rules about which characters are allowed	 
		and which aren't; anything goes). E.g. "jiminy cricket"@disney.com 
		is a legal e-mail address. */	 
		var quotedUser="(\"[^\"]*\")"; 
		/* The following pattern applies for domains that are IP addresses,	
		rather than symbolic names. E.g. joe@[123.124.233.4] is a legal
		e-mail address. NOTE: The square brackets are required. */
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;	
		/* The following string represents an atom (basically a series of	
		non-special characters.) */	
		var atom=validChars + '+';
		/* The following string represents one word in the typical username.
		For example, in john.doe@somewhere.com, john and doe are words.
		Basically, a word is either an atom or quoted string. */ 
		var word="(" + atom + "|" + quotedUser + ")";	
		// The following pattern describes the structure of the user
		var userPat=new RegExp("^" + word + "(\\." + word + ")*$");	
		/* The following pattern describes the structure of a normal symbolic
		domain, as opposed to ipDomainPat, shown above. */ 
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$"); 	  
		/* Finally, let's start trying to figure out if the supplied address is
		valid. */   
		/* Begin with the coarse pattern to simply break up user@domain into
		different pieces that are easy to analyze. */	
		var matchArray=emailStr.match(emailPat);	  
		if (matchArray==null)
		{
			/* Too many/few @'s or something; basically, this address doesn't
			even fit the general mould of a valid e-mail address. */
			alert("Your email is wrong!"); 
			return false;
		}	
		var user=matchArray[1];
		var domain=matchArray[2];	 
		// See if "user" is valid 
		if (user.match(userPat)==null)
		{
			// user is not valid	
			alert("Your email is wrong!");
			return false;
		}	
		/* if the e-mail address is at an IP address (as opposed to a symbolic
		host name) make sure the IP address is valid. */
		var IPArray=domain.match(ipDomainPat);
		if (IPArray!=null)
		{
			// this is an IP address 
			for (var i=1;i<=4;i++)
			{
				if (IPArray[i]>255)	
				{
					alert("Your email is wrong!");
					return false;	
				}
			}
		 return true;
		}	
		// Domain is symbolic name 
		var domainArray=domain.match(domainPat);
		if (domainArray==null) 
		{
			alert("Your email is wrong!");
			return false;
		}
		/* domain name seems valid, but now make sure that it ends in a
		three-letter word (like com, edu, gov) or a two-letter word, 
		representing country (uk, nl), and that there's a hostname preceding	
		the domain or country. */	 	  
		/* Now we need to break up the domain to get a count of how many atoms
		it consists of. */ 
		var atomPat=new RegExp(atom,"g");	
		var domArr=domain.match(atomPat);		
		var len=domArr.length; 
		if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3)
		{
			// the address must end in a two letter or three letter word.
			alert("Your email is wrong!");
			return false;
		} 
	 	// Make sure there's a host name preceding the domain.
		if (len<2)
		{
			var errStr="Your email is wrong!"; 
			alert(errStr); 
			return false;
		}
	 // If we've gotten this far, everything's valid!	
		return true;

 }
 
 function GetTalkback(Id, ContentLength)
 {
	
		var TheDiv = document.getElementById("dvTalkback" + Id);	
		var hdnIsOpen =	document.getElementById("hdnTalkbackStatus" + Id);
		var warper = 	document.getElementById("talkbackwarper" + Id);
			
		if(hdnIsOpen.value == "0")
		{								
			if(TheDiv.innerHTML == "" || (/^\s*$/.test(TheDiv.innerHTML)) )
			{
				script_name	= "Talkback.aspx";
				destination.push("dvTalkback" + Id);				
				ajax_req = "id=" + Id;	
				// Add new query
				cache.push(ajax_req);
				getAjaxRequest();			
			}
			else		
				TheDiv.style.display = "block";	
			
			
			warper.className = "talkbackChosen";			
			hdnIsOpen.value = "1";
		}
		else
		{
			TheDiv.style.display = "none";
			warper.className = "";
			hdnIsOpen.value = "0";
		}		
 }
 
 //TRIM
 
 // Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}

 

