var MENU_FOCUSED = false;
var MENU_NAME = '';

IE4 = (document.all) ? 1 : 0;       // browser is Internet Explorer 4
NS4 = (document.layers) ? 1 : 0;    // browser is Netscape 4

ver4 = (IE4 || NS4) ? 1 : 0;  // know that we have version 4 browser
// this will be required for non-dhtml browsers

function hoverMenu(whichElement,status) {
	arrayOfLayers = ['CatalogMenu'];
	maxNbrOfLayers = 1;
	if (status == true) {
		setMenuFocused()
		vis = 'visible';
	}
	else if (status == false) {
		vis = 'hidden';
	}


	// checking which browser
	if (IE4) {
		for (i=0;i<maxNbrOfLayers;i++) {
			layerName = arrayOfLayers[i];
			if (layerName == whichElement) {
				// get its index first
				layerIndex = i;
				theElement = eval('document.all.'+arrayOfLayers[i]+'.style');
				theElement.visibility=vis;
			} // check if layer exists
			else {
				theElement = eval('document.all.'+arrayOfLayers[i]+'.style');
				theElement.visibility='hidden';
			} // set other layers to hidden

		} // end if for loop
	} // end of IE4

	else if (NS4) { // netscape or similar browser
		for (i=0;i<maxNbrOfLayers;i++) {
			layerName = arrayOfLayers[i];
			if (layerName == whichElement) {
				// get its index first
				layerIndex = i;
				theElement = eval("document." + arrayOfLayers[i]);
				theElement.visibility=vis;
			} // check if layer exists
			else {
				theElement = eval("document." + arrayOfLayers[i]);
				theElement.visibility='hidden';
			} // set other layers to hidden


		} // end if for loop
	} // end of NS
	else { // for Opera browser
		for (i=0;i<maxNbrOfLayers;i++) {
			layerName = arrayOfLayers[i];
			if (layerName == whichElement) {
				// get its index first
				layerIndex = i;
				theElement = eval(document.getElementById(arrayOfLayers[i])).style;
				theElement.visibility=vis;
			} // check if layer exists
			else {
				theElement = eval(document.getElementById(arrayOfLayers[i])).style;
				theElement.visibility='hidden';
			} // set other layers to hidden

		} // end if for loop
	} // end of Opera

} // end hoverOver function

function startHideMenu(whichElement) {
	MENU_FOCUSED = false;
	MENU_NAME = whichElement;
	setTimeout("hideMenu()",500);
	return;
} // end startHideMenu()

function hideMenu() {
	if (!MENU_FOCUSED) hoverMenu(MENU_NAME,false);
	return;
} // end hideMenu()


function setMenuFocused() {
	MENU_FOCUSED = true;
} // end setMenuFocused


function checklogin1(){

	var name=document.getElementById('UserUsername1');
	if(name.value == '' || name.value == 'username')
	{
		alert('Please insert username');
		name.focus();
		return false;
	}

	var password=document.getElementById('UserPassword1');
	if(password.value == '' || password.value == 'password')
	{
		alert('Please insert password');
		password.focus();
		return false;
	}
}

function checklogin(){

	var name=document.getElementById('UserUsername');
	if(name.value == '' || name.value == 'username')
	{
		alert('Please insert username');
		name.focus();
		return false;
	}

	var password=document.getElementById('UserPassword');
	if(password.value == '' || password.value == 'password')
	{
		alert('Please insert password');
		password.focus();
		return false;
	}
}

function checkPollForm()
{
	theForm = "PollForm";
	formlength = document.PollForm.length;
	var checkvalue = false;
	for (i=0, n=formlength; i<n; i++) {
		if(document.PollForm.elements[i].type == 'radio')
		{
			if (document.PollForm.elements[i].checked) {
				checkvalue = document.PollForm.elements[i].value;
				break;
			}
		}
	}
	if(checkvalue == false){
		alert("Please choose your Answer.");
		return false;
	}


	Event.observe("submit538660432", "click", function(event) { new Ajax.Updater("add_pollrow","/pollrows/vote", {asynchronous:true, evalScripts:true, onLoading:function(request) {Element.hide("add_pollrow");Element.show("poll_loading")}, onComplete:function(request) {Element.hide("poll_loading");Effect.Appear("add_pollrow")}, parameters:Form.serialize(Event.element(event).form), requestHeaders:["X-Update", "add_pollrow"]}) }, false);
}

function changeLang(lang)
{
	window.location.href = '/langs/change/' + lang + '/?ref=' + escape(window.location);
        return false;
}

function changeUserCountry(country)
{
	window.location.href = '/stores/changeuserstore/'+country;
        return false;
}

function changeUserCountry1(country, url)
{
	window.location.href = '/stores/changeuserstore/'+country+'/'+url;
        return false;
}



function checkquicksearchform()
{
	searchword = document.getElementById("SearchCriteria");
	if(searchword.value == "" || searchword.value == "search the site")
	{
		alert("Please enter your search criteria.");
		searchword.focus();
		return false;
	}
}

function CheckAdvSearchForm(nametxt,descriptiontxt,fromtxt,totxt)
{
	namee = document.getElementById("SearchName");
	description = document.getElementById("SearchDescription");
	from = document.getElementById("SearchFrom");
	to = document.getElementById("SearchTo");

	//alert(namee.value);
	if(namee.value == nametxt)
	{
		namee.value = '';
	}
	if(description.value == descriptiontxt)
	{
		description.value = '';
	}
	if(from.value == fromtxt)
	{
		from.value = '';
	}
	if(to.value == totxt)
	{
		to.value = '';
	}
}

function CheckNewsletterForm(nametxt,emailtxt)
{
	namee = document.getElementById("NewsletterFullname");
	email = document.getElementById("NewsletterEmail");

	if(namee.value == "" || namee.value == nametxt)
	{
		alert("Please enter your name.");
		namee.focus();
		return false;
	}

	var pattern = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;

	flag = email.value.match(pattern);
	if(!flag){
		alert('Please insert a valid email address.');
		email.focus();
		return false;
	}
	return true;
}

function ShowAjaxPopUpMsg()
{
	new Effect.Opacity("AjaxPopUpMsg", { from: 0, to: 1.0, duration: 0.2 });
	setTimeout('$("AjaxPopUpMsg").style.display = "block";',500);
}

function ShowAjaxPopUpMsg1()
{
	new Effect.Opacity("AjaxPopUpMsg1", { from: 0, to: 1.0, duration: 0.2 });
	setTimeout('$("AjaxPopUpMsg1").style.display = "block";',500);
}

function CloseAjaxPopUpMsg()
{
	if($('AjaxPopUpMsg')!=null){
		new Effect.Opacity("AjaxPopUpMsg", { from: 1.0, to: 0, duration: 1 });
		setTimeout('$("AjaxPopUpMsg").style.display = "none";',1000);
	}
	if($('AjaxPopUpMsg1')!=null){
		new Effect.Opacity("AjaxPopUpMsg1", { from: 1.0, to: 0, duration: 1 });
		setTimeout('$("AjaxPopUpMsg1").style.display = "none";',1000);
	}
}

function CloseAjaxPopUpMsg1(flag)
{
	/*new Effect.Opacity("AjaxPopUpMsg1", { from: 1.0, to: 0, duration: 1 });
	setTimeout('$("AjaxPopUpMsg1").style.display = "none";',1000);*/

	if(!flag){
		if($('AjaxPopUpMsg')!=null){
			new Effect.Opacity("AjaxPopUpMsg", { from: 1.0, to: 0, duration: 1 });
			setTimeout('$("AjaxPopUpMsg").style.display = "none";',1000);
		}
	}
	if($('AjaxPopUpMsg1')!=null){
		new Effect.Opacity("AjaxPopUpMsg1", { from: 1.0, to: 0, duration: 1 });
		setTimeout('$("AjaxPopUpMsg1").style.display = "none";',1000);
	}
}

function ClosePopMsg()
{
	new Effect.Opacity("MessagePopUp", { from: 1.0, to: 0, duration: 1 });
	setTimeout('$("MessagePopUp").style.display = "none";',1000);
}

function HideShow_Slide(obj)
{
	if($(obj).style.display == "none")
	{
		new Effect.SlideDown(obj);
		setTimeout('$("'+obj+'").style.display = "";',1000);
	} else if($(obj).style.display == '')
	{
		new Effect.SlideUp(obj);
		setTimeout('$("'+obj+'").style.display = "none";',1000);
	}
}

function Getquantity(ElId1, ElId2)
{
	qty = $(ElId2).value;
	eval('$("'+ElId1+'").value = '+qty+';');
	//alert(qty);

	//	if(isNaN(qty))
	//	{
	//		alert("Please enter a valid number.");
	//		return false;
	//	} else {
	//		eval('$("'+ElId1+'").value = '+qty+';');
	//		return true;
	//	}
	//	alert(qty);
	//return false;
}

function GetAgentItems(itemID)
{
	new Ajax.Updater('AgentItems', '/store_items/getagentitems/'+itemID, {
		parameters: { itemid: itemID }
	});
}

function GetShippingCostAjax(CountryId, TotalWeight)
{
//	new Ajax.Updater('ShippingCostTrans', '/orders/getshippingcostajax/'+CountryId+'/'+TotalWeight, {
//		parameters: { CountryId: CountryId, TotalWeight: TotalWeight }
//	});
	
	new Ajax.Request('/orders/getshippingcostajax/'+CountryId+'/'+TotalWeight, {
		onSuccess: function(response) {
			var value=response.responseText;
			/// update div shipping cost
			
			if($('sub_total_div').innerHTML != $('sub_total_divTrans').innerHTML){
				value_trans=translate_to_arabic(value);
			}else{
				value_trans=value;
			}
			$('ShippingCostTrans').innerHTML=value_trans;
			
			if($('tax_div'))
           		 var totalAmount = parseFloat( $('sub_total_div').innerHTML ) + parseFloat( $('tax_div').innerHTML ) + parseFloat(value);
           	else var totalAmount = parseFloat( $('sub_total_div').innerHTML ) + parseFloat(value);
           	
			totalAmount=totalAmount.toFixed(2);

			if($('sub_total_div').innerHTML != $('sub_total_divTrans').innerHTML){
				totalAmount=translate_to_arabic(totalAmount);
			}
			
			
            $('total_amount_divTrans').innerHTML = totalAmount;
            
            new Ajax.Updater('citiesSelectDiv', '/orders/get_cities_list/'+CountryId+'/'+TotalWeight, {
			});

		}
	});
	
}

function updateShippingCityCostAjax(cityId,TotalWeight){
	var countryId=document.getElementById('shippingCountryId').value;
	if (cityId == '') return;
        
	new Ajax.Request('/orders/getshippingcitycostajax/'+countryId+'/'+cityId+'/'+TotalWeight, {
		onSuccess: function(response) {
			var value=response.responseText;
			/// update div shipping cost
			
			
			if($('sub_total_div').innerHTML != $('sub_total_divTrans').innerHTML){
				value_trans=translate_to_arabic(value);
			}else{
				value_trans=value;
			}
			$('ShippingCostTrans').innerHTML=value_trans;
			
			if($('tax_div'))
           		 var totalAmount = parseFloat( $('sub_total_div').innerHTML ) + parseFloat( $('tax_div').innerHTML ) + parseFloat(value);
           	else var totalAmount = parseFloat( $('sub_total_div').innerHTML ) + parseFloat(value);
           	
			totalAmount=totalAmount.toFixed(2);

			if($('sub_total_div').innerHTML != $('sub_total_divTrans').innerHTML){
				totalAmount=translate_to_arabic(totalAmount);
			}
			
			
            $('total_amount_divTrans').innerHTML = totalAmount;

		}
	});
}


function updateUserCountryIdAjax(country, url, weight){
	//window.location.href = '/stores/changeuserstoreAjax/'+country+'/'+url;
	
	//var countryId=document.getElementById('shippingCountryId').value;
	
	new Ajax.Request('/stores/changeuserstoreAjax/'+country+'/'+url+'/'+weight , {
		onSuccess: function(response) {
			var value=response.responseText;
				if(value !=0){
					$('citiesSelectDiv').update(value);
					
					refresh_order_total(country,weight);
				}

		}
	});
	
}

function refresh_order_total(country,weight){
	
	sub_total=$('sub_total_div').innerHTML;
	
	new Ajax.Request('/orders/change_total/'+country+'/'+sub_total+'/'+weight , {
		onSuccess: function(response) {
			var value=response.responseText;
				$('shipping_tax_div').update(value);
				var index=value.indexOf("%%");
				var substr=value.substring(index+2);
				var index2=substr.indexOf("%%");
				total=substr.substring(0,index2);
				
				if($('sub_total_div').innerHTML != $('sub_total_divTrans').innerHTML){
					total=translate_to_arabic(total);
				}
			
				$('total_amount_divTrans').innerHTML=total;
				

		}
	});
}


function validChars(e,goods,itemId) {

	var key, keychar;

	key = (window.event) ? window.event.keyCode : ((e) ? e.which : null);
	if(key==48){
		var qty=eval('document.getElementById('+itemId+').value');

		if(qty == ''){
			return false;
		}

	}
	if (key == null) return true;



	keychar = String.fromCharCode(key);
	keychar = keychar.toLowerCase();
	goods = goods.toLowerCase();
	if (goods.indexOf(keychar) != -1)
	return true;

	if (key==null || key==0 || key==8 || key==9 || key==13 || key==27){
		return true;
	}

	return false;

}


function AddToWishlistAjax(type, id)
{

	new Ajax.Updater('AjaxPopUpMsg','/wishlists/add1/'+type+'/'+id, {
		asynchronous:true,
		evalScripts:true,

		onLoading:function(request) {
			Element.hide("ShopCartId");
			Element.show("ShopLoading")
		},

		onComplete:function(request) {
			ShowAjaxPopUpMsg();
			Element.hide("ShopLoading");
			Effect.Appear("ShopCartId")
		},
		//parameters:Form.serialize('WishlistAdd1'),
		requestHeaders:['X-Update', 'AjaxPopUpMsg']
	});
	return false;
}

function HideShowPoll()
{
	var obj = "add_pollrow";
	if($(obj).style.display == "none")
	{
		new Effect.SlideDown(obj);
		setTimeout('$("'+obj+'").style.display = "";',1000);

		$('ImgBtnPoll').fade({duration: 0.3, delay: 0, from:1, to:0});
	} else if($(obj).style.display == '')
	{
		new Effect.SlideUp(obj);
		setTimeout('$("'+obj+'").style.display = "none";',1000);
		//$('ImgBtnPoll').show();
		Effect.Appear("ImgBtnPoll", {duration: 1, delay: 0.5});
	}
}

//function HideShow_Slide(obj)
//{
//	if($(obj).style.display == "none")
//	{
//		new Effect.SlideDown(obj);
//		setTimeout('$("'+obj+'").style.display = "";',1000);
//	} else if($(obj).style.display == '')
//	{
//		new Effect.SlideUp(obj);
//		setTimeout('$("'+obj+'").style.display = "none";',1000);
//	}
//}


	function checkordertrackform(){
		

		tracknumber = document.getElementById("OrderNumber");
		if(tracknumber.value == "" || tracknumber.value == "enter your tracking number"){
			alert("Please enter your tracking number.");
			tracknumber.focus();
			return false;
		}
		
		//window.open("http://www.dhl.com.lb/publish/lb/en/eshipping/track.high.html?pageToInclude=RESULTS&type=fasttrack&AWB="+tracknumber, "Tracknumber", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=650,height=650,top=100,left=100");
		
		$('OrderTrackForm').request({
				onLoading:function(request) {
				},
				onComplete: function(response){
					var returnText=response.responseText;
					window.open(""+returnText+"", "Tracknumber", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=650,height=650,top=100,left=100");
		
				}
			})
			
		return false;
	}


	function checkordertrackform_(){
		
		var tracknumber = document.getElementById("OrderNumber").value;
		
		if(tracknumber.value == "" || tracknumber.value == "enter your tracking number"){
			alert("Please enter your tracking number.");
			tracknumber.focus();
			return false;
		}
		
//		var url="http://www.dhl.com.lb/publish/lb/en/eshipping/track.high.html?pageToInclude=RESULTS&type=fasttrack&AWB="+tracknumber;
		var url="http://www.dhl.com.lb/content/lb/en/express/tracking.shtml?brand=DHL&pageToInclude=RESULTS&type=fasttrack&AWB="+tracknumber;
		
		var pageRequest = false //variable to hold ajax object
		/*@cc_on
		   @if (@_jscript_version >= 5)
		      try {
		      pageRequest = new ActiveXObject("Msxml2.XMLHTTP")
		      }
		      catch (e){
		         try {
		         pageRequest = new ActiveXObject("Microsoft.XMLHTTP")
		         }
		         catch (e2){
		         pageRequest = false
		         }
		      }
		   @end
		@*/
		
		if (!pageRequest && typeof XMLHttpRequest != 'undefined')
		   pageRequest = new XMLHttpRequest()
		
		if (pageRequest){ //if pageRequest is not false
		   pageRequest.open('GET', url, false) //get page synchronously 
		   pageRequest.send(null)
		   embedpage(pageRequest)
		 }
		 alert('here');
		return false;
	}

	function embedpage(request){
		//if viewing page offline or the document was successfully retrieved online (status code=2000)
		if (window.location.href.indexOf("http")==-1 || request.status==200)
		   document.write(request.responseText)
	}

	function fillShoppingCart(){
		new Ajax.Request('/shopping_carts/fillShoppingCart/', {
		onSuccess: function(response) {
			var value=response.responseText;
			/// update div shipping cost
			$('ShopCartId').innerHTML=value;
			Element.hide("ShopLoading");
			Element.show("ShopCartId");

		}
	});
	}
	
function fill_shipping_address(TotalWeight){
	if($('fill_same_box').checked==true)
		$('OrderFirstname').value=$('OrderBillingFirstname').value;
		$('OrderLastname').value=$('OrderBillingLastname').value;
		$('OrderEmail').value=$('OrderBillingEmail').value;
		$('OrderPhone').value=$('OrderBillingPhone').value;
//		$('shippingCountryId').value=$('OrderBillingCountryId').value;
//		updateUserCountryIdAjax($('shippingCountryId').value, '/orders',TotalWeight);
//		$('OrderCity').value=$('OrderBillingCity').value;
		$('OrderState').value=$('OrderBillingState').value;
		$('OrderPostcode').value=$('OrderBillingPostcode').value;
}

function translate_to_arabic(str){
	str=str.replace(/0/g, "\u0660");
	str=str.replace(/1/g, "\u0661");
	str=str.replace(/2/g, "\u0662");
	str=str.replace(/3/g, "\u0663");
	str=str.replace(/4/g, "\u0664");
	str=str.replace(/5/g, "\u0665");
	str=str.replace(/6/g, "\u0666");
	str=str.replace(/7/g, "\u0667");
	str=str.replace(/8/g, "\u0668");
	str=str.replace(/9/g, "\u0669");
	
	return str;
}

function openImagePreview(container,img,id){
	$(container).innerHTML += "<img src='"+img+"' alt=''/>";
}

function closeImagePreview(container,img){
	$(container).innerHTML = "";
}
