

function loadPreviousCart() {   // See laetakse programmi käivitumisel

	if (document.getElementById("viewcart")) {
		//var viewCart=document.createElement("img")
		//viewCart.setAttribute("id","closename")
		//viewCart.setAttribute("src","close.gif")
		//viewCart.onclick=function() {closeit()}

		var viewCart=document.createElement("a")
		viewCart.setAttribute("href","#")
		viewCart.onclick=function() {viewCart(); return false;}
		document.getElementById("viewcart").appendChild(viewCart)
		tn = document.createTextNode('ostukorvis 0 toodet');
		viewCart.appendChild(tn);

		ajaxRequest('../shoppingcart/addToCart.php', 2);
	}


}

//ViewCart==========================================================

// Avame korvivaatamise akna ("teie ostukorvis on X toodet")
function viewCart() {

	//loadwindow("Ostukorvi sisu","<table width=100% height=100%><tr><td align=center valign=center>Loading</td></tr></table>",600,500);
	//document.location.href="/index.php?pg=cart&act=view"; 	
	document.location.href="/index.php?pg=cart"; 	
	//UpdateCartView();
	
}

// Laeme alla ostukorvi akna sisu (kas peidetud voi nähtaval aken)  Step 2
function UpdateCartView() {
	ajaxRequest('../shoppingcart/viewCart.php', 1);
	setWindowCaption("Ostukorvi sisu");
}


// Täidame korviakna sisu HTMLi Step 3
function drawCartView(strHTML) {
	if (document.getElementById("shoppingcart_content")) {
		document.getElementById("shoppingcart_content").innerHTML=strHTML;
	}
}

function setWindowCaption(strCaption) {
	if (document.getElementById("shopping_cart_header")) {
		document.getElementById("shopping_cart_header").innerHTML=strCaption;
	}
}

function DealWithJavascript() {
	// Vaatame kas meile on antud mingeid hoiatusi või käske?
	if (document.getElementById("Js")) {
		var t = document.getElementById("Js");
		if (t.innerHTML.length > 0) {
//		alert(t.innerHTML);
			eval(t.innerHTML);
			t.innerHTML='';
		}
		var p = t.parentNode;
		p.removeChild(t);
	}
}

function AddScriptOnly(strH) {
//alert(strH);
	if (!document.getElementById('JsHolder')) {
			var bog=document.createElement("div")
			bog.setAttribute("id","JsHolder")
			bog.style.display='none'
			document.body.appendChild(bog)
	}
	
	//if (document.getElementById('JsHolder')) {
		document.getElementById('JsHolder').innerHTML = strH;
	//}
	
}		
		
//end ViewCart==========================================================


// Start Checkout

function checkOut(f_order) {

	if (f_order == 1) {
		ajaxRequest('../shoppingcart/Login.php', 1);
		setWindowCaption("Maksja ja tarneandmed");
	} else {
		ajaxRequest('../shoppingcart/Checkout.php', 1);
		setWindowCaption("Maksja ja tarneandmed");
	}
}

// end Checkout


function addToCart(ItemID, Amount) {
//alert(ItemID);
	var lAmount = 1;
	if (IsNumeric(Amount)) {
		lAmount = parseFloat(Amount);
	}

	if (parseFloat(ItemID)!=0) {
		ajaxRequest('../shoppingcart/addToCart.php?ItemID=' + ItemID + '&Amount=' + lAmount, 2);
	} else {

		//loadwindow("Lisa enda leitud toode ostukorvi","<table width=100% height=100%><tr><td align=center valign=center>Loading</td></tr></table>",600,500);
		ajaxRequest('../shoppingcart/AddOwnProduct.php', 1);

	}

}

// Lisab toote DIV strutkuurist
function addToCartSpecial(prodObj) {

	var ExternalID = 0;
	var ItemID = -1;
	var ProductName = "";
	var ProductURL = "";
	var WeightKG = 0;
	var Amount = 0;
	var PriceUSD = 0;
	var USTransportPriceUSD = 0;
	var Description = "";
	
	if (document.getElementById(prodObj)) {
	
		var node = document.getElementById(prodObj);
		ExternalID = prodObj;
		var len = node.childNodes.length;

		for(var i = 0; i < len; i++)
		{
			if (node.childNodes[i].id == "ProductName")
				ProductName = node.childNodes[i].innerHTML;
			if (node.childNodes[i].id == "ProductURL")
				ProductURL = node.childNodes[i].innerHTML;
			if (node.childNodes[i].id == "Description")
				Description = node.childNodes[i].innerHTML;
			if (node.childNodes[i].id == "WeightKG")
				WeightKG = parseFloat(node.childNodes[i].innerHTML);
			if (node.childNodes[i].id == "Amount")
				Amount = parseFloat(node.childNodes[i].innerHTML);
			if (node.childNodes[i].id == "PriceUSD")
				PriceUSD = parseFloat(node.childNodes[i].innerHTML);
			if (node.childNodes[i].id == "USTransportPriceUSD")
				USTransportPriceUSD = parseFloat(node.childNodes[i].innerHTML);
		}
		
		//Validate
		var validated = true;
		if (ProductName.length < 1) {
			validated = false;
			alert('Puudulik tootenimi.');
		}
		if (ProductURL.length < 1) {
			validated = false;
			alert('Puudub URL toote kodulehele.');
		}
		if (WeightKG <= 0) {
			validated = false;
			alert('Toote kaal peab olema positiivne number kilogrammides.');
		}
		if (PriceUSD <= 0) {
			validated = false;
			alert('Toote hind peab olema positiivne number USA dollarites.');
		}
		
		if (validated == true) {
			var params = 'ItemID=' + ItemID;
			params+='&ExternalID='+escape(ExternalID);
			params+='&ProductName='+escape(ProductName);
			params+='&ProductURL='+escape(ProductURL);
			params+='&Description='+escape(Description);
			params+='&WeightKG='+WeightKG;
			params+='&Amount='+Amount;
			params+='&PriceUSD='+PriceUSD;
			params+='&USTransportPriceUSD='+USTransportPriceUSD;
			
			//alert(params);
			
			ajaxPost('../shoppingcart/addToCart.php', params, 2);
			
		}
		
	}

}


function updateCart(CartItemId, Amount) {

	var lAmount = 1;
	if (IsNumeric(Amount)) {
		lAmount = parseFloat(Amount);
	}

	if (parseFloat(CartItemId)!=0) {
		ajaxRequest('../shoppingcart/addToCart.php?CartItemID=' + CartItemId + '&Amount=' + lAmount, 4);
	}

}

function applyGiftCertificate(SertValue, giftRemove, ajax_target) {


	if (SertValue.length > 2) {
		if (ajax_target == 5) {  // ViewCart update
			ajaxRequest('../shoppingcart/addToCart.php?GiftCertificate=' + SertValue + '&remove='+giftRemove, 4);
		} else {   // ajax_target=6
			ajaxRequest('../shoppingcart/Checkout.php?GiftCertificate=' + SertValue + '&GoReview=yes&remove='+giftRemove, 3);
		}
	}
}

// Uuendame nupu "Ostukorvis on X" teksti
function alterCartUpdated(NewContent) {

	//alert('Cart updated');
	var uTag = document.getElementById('viewcart');
	uTag.innerHTML=NewContent;
	//UpdateCartView();
	

}



function PoundToKg(Tpound) {
	//1 pound = 0.45359237 Kg
	var test = (1 / 2) + "";
	if (test.indexOf(",") > 0) {
		Tpound = Tpound.replace(".", ",");
		Tpound = Tpound * 0,45359237;
		
	} else {
		Tpound = Tpound.replace(",", ".");
		Tpound = Tpound * 0.45359237;
	}

	if (Tpound > 0) {

		Tpound = Math.round( Math.round( Tpound * Math.pow( 10, 1 + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,1);
		return Tpound;
	}
	else {
		return 0.0;
	}
}

function cleanEditBoxValue(Obj, strValue) {
	if (Obj.value == strValue) {
		Obj.style.color="#000000";
		Obj.value = '';
	}
}
function restoreEditBoxValue(Obj, strValue) {
	if (Obj.value.length == 0) {
		Obj.style.color="#CCCCCC";
		Obj.value = strValue;
	}
}




function AjaxToElement(Url, ElementName) {


	if (Url.indexOf('?') > 0) {
		Url = Url + '&t=' + Date();
	} else {
		Url = Url + '?t=' + Date();
	}

	var xmlhttp;
	if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
			var f=document.getElementById(ElementName);
			f.innerHTML = xmlhttp.responseText; 
		}
		DealWithJavascript();

	}
	xmlhttp.open("GET",Url,true);
	xmlhttp.send(null);
	return "loading...";
}


function ajaxRequest(Url,  uMethod) {

//alert(readCookie('CurrentCart'));

	if (Url.indexOf('?') > 0) {
		Url = Url + '&CurrentCart=' + readCookie('CurrentCart') + '&t=' + Date();
	} else {
		Url = Url + '?CurrentCart=' + readCookie('CurrentCart') + '&t=' + Date();
	}
	
	var xmlhttp;
	if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	  
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {

			if (uMethod == 1) {
				drawCartView(xmlhttp.responseText);   // Vaata korvi sisu
			} else if (uMethod==2) {
				alterCartUpdated(xmlhttp.responseText);  // Lisa toode ostukorvi
				document.location.reload(true); 

			} else if (uMethod==3) {					// Uuendame ostukaardi vaate sisu
				if (document.getElementById("shoppingcart_content")) {
					document.getElementById("shoppingcart_content").innerHTML=xmlhttp.responseText;
				}			
			} else if (uMethod==4) {
				alterCartUpdated(xmlhttp.responseText);  // Uuendame toote kogust ostukorvis
				document.location.reload(true); 
				//UpdateCartView();
			} else if (uMethod==8) {                     // AddScriptOnly
				AddScriptOnly(xmlhttp.responseText);
			} else {
				alert('Other');
			}
			DealWithJavascript();
			
		}
	}
	xmlhttp.open("GET",Url,true);
	xmlhttp.send(null);
}

function ajaxPost(URL, params, uMethod) {

//alert(URL + ' ' + params + ' ' + uMethod);

	var xmlhttp;
	if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

	//URL = "get_data.php";
	//params = "lorem=ipsum&name=binny";
	params = params + '&CurrentCart=' + readCookie('CurrentCart');
	
	xmlhttp.onreadystatechange=function() {
		if(xmlhttp.readyState==4) {
		
			if (uMethod == 1) {
				drawCartView(xmlhttp.responseText);   // Vaata korvi sisu
			} else if (uMethod==2) {
				alterCartUpdated(xmlhttp.responseText);  // Lisa toode ostukorvi
				document.location.reload(true);
			} else if (uMethod==3) {					// Uuendame ostukaardi vaate sisu
				if (document.getElementById("shoppingcart_content")) {
					document.getElementById("shoppingcart_content").innerHTML=xmlhttp.responseText;
				}			
			} else if (uMethod==4) {
				alterCartUpdated(xmlhttp.responseText);  // Uuendame toote kogust ostukorvis
				UpdateCartView();
			} else if (uMethod==8) {                     // AddScriptOnly
				AddScriptOnly(xmlhttp.responseText);
			} else {
				alert('Other');
			}
			DealWithJavascript();

		}
	}
	
	xmlhttp.open("POST", URL, true);

	//Send the proper header information along with the request
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.send(params);


}


function ParseForm(Obj, Resets, uMethod) {

	var i;
	var j;
	var strtype;
	var strname;
	var strvalue;
	var Url;
	var postparam;
	postparam = "";


	Url = Obj.action;
	
	for (i=0;i<Obj.length;i++) {

		strtype = Obj[i].type;
		strname = encodeURI(Obj[i].name);

		if ((strtype == "text") || (strtype == "hidden") || (strtype == "textarea") || (strtype == "password") || (strtype == "submit")) {
			strvalue = escape(Obj[i].value);
			postparam+= strname + "=" + strvalue + "&"
		}
		else if (strtype == "radio") {
			if (Obj[i].checked == true) {
				strvalue = escape(Obj[i].value);
				postparam+= strname + "=" + strvalue + "&"
			}
		} else if (strtype == "checkbox") {

			if (Obj[i].checked == true) {
				strvalue = escape(Obj[i].value);
				postparam+= strname + "=" + strvalue + "&"
			} else {
				postparam+= strname + "=&"
			}

		} else if (strtype == "select-one") {
			strvalue = escape(Obj[i].value);
			postparam+= strname + "=" + strvalue + "&"

		} else if (strtype == "select-multiple") {
			for (j=0;j<Obj[i].length;j++) {
				if (Obj[i][j].selected) {
					strvalue = escape(Obj[i][j].value);
					postparam+= strname + "=" + strvalue + "&"
				}
			}
		}
	}
	postparam+="1=1";

	if (Resets == 1) {
		Obj.reset();  //clean form
	}

	if (Url.length > 0) {
		ajaxPost(Url, postparam, uMethod);
		
	}

}


function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}



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;
   
 }

 
//if (window.addEventListener)
//window.addEventListener("load", loadPreviousCart, false)
//else if (window.attachEvent)
//window.attachEvent("onload", loadPreviousCart)
//else if (document.getElementById)
//window.onload=loadPreviousCart
