var gCountryCode="";
var gCountryName = "";
var gDevise="";
var gGlobalReduction=0;
//var gDefaultKeyEnvironment="dfd58e55fz";

/** to select the appropriate devise **/
var gCountryForEuro = new Array("AT","BE","CY","CZ","DK","EE","FI","FR","DE","EL","HU","IE","IT","LV","LT","LU","MT","NL","PL","PT","SK","SI","ES","SE");
var gCountryForPound = new Array("GB");

// auto generated
//var ORIGINAL_PRICES={'bz1':{'euro':37,'dollar':49,'pound':37},'bz2':{'euro':65,'dollar':89,'pound':65},'bz3':{'euro':35,'dollar':45,'pound':35},'bzp1':{'euro':89,'dollar':129,'pound':89},'bzp2':{'euro':159,'dollar':219,'pound':159},'bzp3':{'euro':79,'dollar':99,'pound':79},'bzp4':{'euro':57,'dollar':85,'pound':57},'bzp5':{'euro':99,'dollar':135,'pound':99},'id1':{'euro':59,'dollar':79,'pound':59},'id2':{'euro':109,'dollar':149,'pound':109},'id3':{'euro':30,'dollar':40,'pound':30},'id4':{'euro':55,'dollar':75,'pound':55},'vp1':{'euro':37,'dollar':49,'pound':37},'vp2':{'euro':65,'dollar':89,'pound':65},'vp3':{'euro':35,'dollar':45,'pound':35},'vphd1':{'euro':59,'dollar':79,'pound':59},'vphd2':{'euro':109,'dollar':149,'pound':109},'vphd3':{'euro':24,'dollar':33,'pound':24},'pmad1':{'euro':89,'dollar':129,'pound':89},'pmad2':{'euro':159,'dollar':219,'pound':159},'pmad3':{'euro':79,'dollar':99,'pound':79},'pmad4':{'euro':57,'dollar':85,'pound':57},'pmad5':{'euro':99,'dollar':135,'pound':99},'pmad7':{'euro':122,'dollar':170,'pound':122},'vphd4':{'euro':44,'dollar':60,'pound':44},'pm1V2':{'euro':37,'dollar':49,'pound':37},'snp1':{'euro':89,'dollar':129,'pound':89},'pm4V2':{'euro':12,'dollar':15,'pound':12},'pm2V2':{'euro':65,'dollar':89,'pound':65},'pm3V2':{'euro':35,'dollar':45,'pound':35},'snp2':{'euro':159,'dollar':219,'pound':159},'snp3':{'euro':79,'dollar':99,'pound':79}};

var ORIGINAL_PRICES={'bz1':{'euro':37,'dollar':49,'pound':37},'bz2':{'euro':65,'dollar':89,'pound':65},'bz3':{'euro':35,'dollar':45,'pound':35},'bzp1':{'euro':89,'dollar':129,'pound':89},'bzp2':{'euro':159,'dollar':219,'pound':159},'bzp3':{'euro':79,'dollar':99,'pound':79},'bzp4':{'euro':57,'dollar':85,'pound':57},'bzp5':{'euro':99,'dollar':135,'pound':99},'id1':{'euro':59,'dollar':79,'pound':59},'id2':{'euro':109,'dollar':149,'pound':109},'id3':{'euro':30,'dollar':40,'pound':30},'id4':{'euro':55,'dollar':75,'pound':55},'vp1':{'euro':37,'dollar':49,'pound':37},'vp2':{'euro':65,'dollar':89,'pound':65},'vp3':{'euro':35,'dollar':45,'pound':35},'vphd1':{'euro':59,'dollar':79,'pound':59},'vphd2':{'euro':109,'dollar':149,'pound':109},'vphd3':{'euro':24,'dollar':33,'pound':24},'pmad1':{'euro':89,'dollar':129,'pound':89},'pmad2':{'euro':159,'dollar':219,'pound':159},'pmad3':{'euro':79,'dollar':99,'pound':79},'pmad4':{'euro':57,'dollar':85,'pound':57},'pmad5':{'euro':99,'dollar':135,'pound':99},'pmad7':{'euro':122,'dollar':170,'pound':122},'vphd4':{'euro':44,'dollar':60,'pound':44},'pm1V2':{'euro':37,'dollar':49,'pound':37},'snp1':{'euro':89,'dollar':129,'pound':89},'pm4V2':{'euro':12,'dollar':15,'pound':12},'pm2V2':{'euro':65,'dollar':89,'pound':65},'pm3V2':{'euro':35,'dollar':45,'pound':35},'snp2':{'euro':159,'dollar':219,'pound':159},'snp3':{'euro':79,'dollar':99,'pound':79},
'bz23':{'euro':19,'dollar':25,'pound':19},'bzp23':{'euro':45,'dollar':59,'pound':45},
'bzp24':{'euro':76,'dollar':110,'pound':76}	
};

/* BEGIN */
var Ajax={
	getHTTPRequest:function() {
		var ajx=null;
		if (window.XMLHttpRequest) { 
			ajx = new XMLHttpRequest();
		} else if (window.ActiveXObject){
			ajx = new ActiveXObject("Microsoft.XMLHTTP");
		}
		return ajx;
	},
	sendRequest:function( method, url, params, async, handler ){
		var vHttp = Ajax.getHTTPRequest();
		vHttp.open( "POST", url, false );
		vHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		vHttp.setRequestHeader("Content-length", params.length );
		vHttp.setRequestHeader("Connection", "close");
		vHttp.setRequestHeader("Cache-Control", "no-cache");
		// TODO method and async
		
		vHttp.send( params );
		//vResponse = vHttp.responseText
		if( handler ) {
			handler.call( vHttp );
			//vHttp = null;
		}
	}
};
var vHttp = Ajax.getHTTPRequest();

/* OBJECTS */
var Soft = function(inId, inSoftName, inHtmlDetail, inDetail, inDollar, inEuro, inPound) {
	this.id=inId;
	this.softName=inSoftName;
	this.htmlDetail=inHtmlDetail;
	this.detail=inDetail;
	this.dollar=inDollar*1.00;
	this.euro=inEuro*1.00;
	this.pound=inPound*1.00;
};

var Rules = function(inQuantity, inReduction) {
	this.quantity = inQuantity;
	this.reduction = inReduction;
};

var gSoftList = new Array();
var gQuantityRules = new Array();

// INIT 

function revealEnvironment() {
	initEnvironment("REVEAL");
};

function initEnvironment(inKey) {
	
	initSoft(inKey);
	//initQuantityRules(inKey);
	initCountryCode();
	updateCurrency(inKey);
	initCurrency(inKey);
	
	checkGlobalReduction(inKey);
};

function initQuantityRules(inKey) {
	// get all the quantity rules
	//
	Ajax.sendRequest( 
		"POST", 
		"script/cart/initEnvironment.php", 
		"key="+inKey+"&type=getQuantityRules", 
		false, 
		function() {
			var vResponse = this.responseText||"KO";
			if( vResponse == "KO" ) {
				// do nothing...
			} else {
				vResponse=vResponse.split("|");
				for( var i=0;i<vResponse.length;i++ ) {
					var vRules = vResponse[i].split(":");
					gQuantityRules.push(new Rules(vRules[0],vRules[1]));
				}
			}
		}
	);
};

function initSoft(inKey) {
	// get all the softs from database:
	//
	Ajax.sendRequest( 
		"POST", 
		"script/cart/initEnvironment.php", 
		"key="+inKey+"&type=getSoft", 
		false, 
		function() {
			var vResponse = null;
			try {
				vResponse = this.responseText.split("|");
				if( vResponse ) {
					for( var i=0;i<vResponse.length;i++ ) {
						var vSoft = vResponse[i].split(":");
						// soft details:
						gSoftList.push(
							new Soft(vSoft[0],vSoft[1],vSoft[2],vSoft[3],vSoft[4],vSoft[5],vSoft[6])
						);
					}
				}
			} catch( e ) {
				// ERROR	
			}
		}
	);
};

function checkGlobalReduction(inKey) {
	Ajax.sendRequest( 
		"POST", 
		"script/cart/initEnvironment.php", 
		"type=getGlobalReduction&value="+inKey, 
		false, 
		function() {
			var vResponse = this.responseText.split("|");
			if( vResponse[0] == 'OK' ) {
				gGlobalReduction = vResponse[1];
			} else {
				gGlobalReduction = 0;
			}
		}
	);
	/*
	var vRequest = "script/cart/initEnvironment.php?type=getGlobalReduction&value="+inKey;
	vHttp.open("GET", vRequest, false);
	vHttp.send(null);
	var vResponse = vHttp.responseText.split("|");
	if( vResponse[0] == 'OK' ) {
		gGlobalReduction = vResponse[1];
	} else {
		gGlobalReduction = 0;
	}
	*/
};

function initCurrency(inKey) {
	Ajax.sendRequest( 
		"POST", 
		"script/cart/initEnvironment.php", 
		"key="+inKey+"&type=getCurrency", 
		false, 
		function() {
			var vResponse = this.responseText.split("|");
			if( vResponse[0] == 'OK' ) {
				gDevise = vResponse[1];	
			} else {
				// vResponse[0] == 'ER'
				gDevise = 'dollar';
			}
		}
	);
	/*
	var vRequest = "script/cart/initEnvironment.php?key="+inKey+"&type=getCurrency";
	vHttp.open("GET", vRequest, false);
	vHttp.send(null);
	var vResponse = vHttp.responseText.split("|");
	if( vResponse[0] == 'OK' ) {
		gDevise = vResponse[1];	
	} else {
		// vResponse[0] == 'ER'
		gDevise = 'dollar'
	}
	*/
}

function initCountryCode() {
	if( !gCountryCode ) {
		
		Ajax.sendRequest( 
			"POST", 
			"script/cart/ip_toc.php", 
			"", 
			false, 
			function() {
				var vResponse = this.responseText;
				var vArr=vResponse.split("|");
				if( vArr.length > 0 ) {
					gCountryCode = vArr[0];
					gCountryName = vArr[1];
				} else {
					gCountryCode = "";
					gCountryName = "";
				}
			}
		);
		
		/*
		var vRequest = "script/cart/ip_toc.php";
		vHttp.open("GET", vRequest, false);
		vHttp.send(null);
		var vResponse = vHttp.responseText;
		var vArr=vResponse.split("|");
		if( vArr.length > 0 ) {
			gCountryCode = vArr[0];
			gCountryName = vArr[1];
		} else {
			gCountryCode = "";
			gCountryName = "";
		}
		*/
	}		
}

function updateCurrency(inKey) {
	var found=false;
	if( gCountryCode == "GB" ) {
		found=true;
		gDevise = "pound";
	} else {
		for( var index in gCountryForEuro ) {
			if( gCountryCode == gCountryForEuro[index] ) {
				gDevise="euro";
				found=true;
				break;
			} 
		
		}
	}
	
	if( found == false ) {
		gDevise = "dollar";
	}
	
	Ajax.sendRequest( 
		"POST", 
		"script/cart/initEnvironment.php", 
		"key="+inKey+"&type=setCurrency&value="+gDevise, 
		false
	);
	/*
	var vRequest = "script/cart/initEnvironment.php?key="+inKey+"&type=setCurrency&value="+gDevise;
	vHttp.open("GET", vRequest, false);
	vHttp.send(null);
	var vResponse = vHttp.responseText;
	*/
	
};

function getSoftById(inId) {
	var outSoft = "";
	for( var i=0;i<gSoftList.length;i++ ) {
		outSoft = gSoftList[i];
		if( outSoft.id == inId ) {
			break;
		}		
	}
	return outSoft;
}

/*
	inDevise:
		- dollar
		- euro
		- pound
*/
function getTotalForDevise(inDevise) 
{
	var outTotal = 0,
		vRequest = "script/cart/manageCart.php",
		vParams = "type=update",
		vResponse = "";	
	vHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	vHttp.setRequestHeader("Content-length", vParams.length);
	vHttp.setRequestHeader("Connection", "close");
	vHttp.setRequestHeader("Cache-Control", "no-cache");
	vHttp.open( "POST", vRequest, false );
	vHttp.send( vParams );
	vResponse = vHttp.responseText.split("|");	
	if( vResponse[0] == "OK" ) {		
		// get all the elements in card
		for( var i=1,len=vResponse.length;i<len;i++ ) {
			var cartForElement = vResponse[i].split(":");
			var id = cartForElement[0];
			var quantity = cartForElement[1];
			var element = getSoftById(id);
			outTotal += element[inDevise]*quantity;
		}
	}	
	return outTotal;
}

var gTotalForCheck=0;
function goToCart(countryCode) {
	if( gTotalForCheck > 0 ) {
		var checkBtn = document.getElementById("cart_checkout");
		checkBtn.style.color="#fff";
		
		if( countryCode == "en") cartLocation = "cart.php";
		else cartLocation = "cart_fr.php";
		
		window.location.href = cartLocation;
	}
};

/*
 
 	TOTAL
 
*/
var Total = function(inCurrency, inTotal) {
	this.currency=inCurrency;
	//this.type=inType;
	this.total=inTotal;
};

function getTotalForKey(inTotals, inCurrency) {
	var outTotal = 0;
	for( var i=0;i<inTotals.length;i++ ) {
		var tt = inTotals[i];
		if( tt.currency == inCurrency ) {
			outTotal=tt.total;
			break;
		}
	}
	return outTotal;
};

function setTotal(inDevise, inMode) {	
	/*
		// totals ht
		"dollarHT"
		"euroHT"
		"poundHT"
		
		// totals ht with quantity discount reduction
		"dollarWR"
		"euroWR"
		"poundWR"
		
		// totals ttc with quantity discount reduction
		"dollarTTC"
		"euroTTC"
		"poundTTC"
		
		// quantity discount reductions: 
		"reductionDollar"
		"reductionEuro"
		"reductionPound"
		
		// quantity discount percent reduction:
		"reduction"
		
		// global reduction percent:
		"globalReduction"
	
	*/

	// get back totals:
	var totals = new Array();
	var htElement = document.getElementById("totalCartHT");
	htElement.innerHTML = (inMode == "full") ?"":"Total: ";
	
	var ajxHttp = Ajax.getHTTPRequest();
	var vRequest = "script/cart/manageCart.php";
	var vParams = "getTotal=all";
	ajxHttp.onreadystatechange = function() 
	{
		if( ajxHttp.readyState == 4 && ajxHttp.status == 200 ) {
			var vResponse = ajxHttp.responseText.split("|");	
			for( var i=0;i<vResponse.length;i++ ) {
				var tt = vResponse[i].split(":");
				totals.push( new Total(tt[0],tt[1]) );
			}
		
			// update the web page:
			switch(inDevise) {
				case 'dollar':
					// HT:
					htElement.innerHTML += "$" + formatCurrency(getTotalForKey(totals,'dollarHT')) ;
								
					if( inMode == "full" ) {
						var ttcElement = document.getElementById("totalCartTTC");
						ttcElement.innerHTML="$"+formatCurrency(getTotalForKey(totals,'dollarTTC'));
						
						var htWrElement = document.getElementById("totalCartWR");
						htWrElement.innerHTML="$"+formatCurrency(getTotalForKey(totals,'dollarWR'));
						
						var quantityDiscountElement = document.getElementById("quantityDiscountNumber");
						var reduction = getTotalForKey(totals,'reductionDollar');
						if( reduction == '0' || reduction == 0 ) {
							reduction=" - - ";
						} else {
							reduction="- $"+reduction;
						}
						quantityDiscountElement.innerHTML=reduction;
						
						// get back all the needed informations:
						var reductionCoupon="$"+getTotalForKey(totals,"dollarCPNReduction");
						updateTotalsWithCoupon(totals,reductionCoupon);
						
								
					} else {
						var reductionElement=document.getElementById("reduction");
						var reduction = getTotalForKey(totals,'reductionDollar');
						if( reduction == '0' || reduction == 0 ) {
							reduction=" - - "
						} else {
							reduction="- $"+reduction;
						}
						reductionElement.innerHTML="Quantity Discount: "+reduction;
						
						var twrElement=document.getElementById("totalCartHTWR");
						gTotalForCheck = formatCurrency(getTotalForKey(totals,'dollarWR'));
						twrElement.innerHTML= "Total: $" + gTotalForCheck;
					}
				break;
				case 'euro':
					htElement.innerHTML += formatCurrency(getTotalForKey(totals,'euroHT')) +" &euro;";
					
					if( inMode == "full" ) {
						var ttcElement = document.getElementById("totalCartTTC");
						ttcElement.innerHTML=formatCurrency(getTotalForKey(totals,'euroTTC')) +" &euro;";
						
						var htWrElement = document.getElementById("totalCartWR");
						htWrElement.innerHTML=formatCurrency(getTotalForKey(totals,'euroWR')) +" &euro;"
						
						var quantityDiscountElement = document.getElementById("quantityDiscountNumber");
						var reduction = getTotalForKey(totals,'reductionEuro');
						if( reduction == '0' || reduction == 0 ) {
							reduction=" - - "
						} else {
							reduction="- "+reduction+ " &euro;";
						}
						quantityDiscountElement.innerHTML=reduction;
						
						// get back all the needed informations:
						var reductionCoupon=getTotalForKey(totals,"euroCPNReduction")+" &euro;";
						updateTotalsWithCoupon(totals,reductionCoupon);						
						
					} else {
						var reductionElement=document.getElementById("reduction");
						var reduction = getTotalForKey(totals,'reductionEuro');
						if( reduction == '0' || reduction == 0 ) {
							reduction=" - - "
						} else {
							reduction="- "+reduction+" &euro;";
						}
						reductionElement.innerHTML="Quantity Discount: "+reduction;
						
						var twrElement=document.getElementById("totalCartHTWR");
						gTotalForCheck = formatCurrency(getTotalForKey(totals,'euroWR'));
						twrElement.innerHTML= "Total: " + gTotalForCheck + " &euro;";
					}
				break;
				case 'pound':
					htElement.innerHTML += formatCurrency(getTotalForKey(totals,'poundHT')) +" &pound;";
					
					if( inMode == "full" ) {
						var ttcElement = document.getElementById("totalCartTTC");
						ttcElement.innerHTML=formatCurrency(getTotalForKey(totals,'poundTTC')) +" &pound;" ;
						
						var htWrElement = document.getElementById("totalCartWR");
						htWrElement.innerHTML=formatCurrency(getTotalForKey(totals,'poundWR'))+" &pound;";
						
						var quantityDiscountElement = document.getElementById("quantityDiscountNumber");
						var reduction = getTotalForKey(totals,'reductionPound');
						if( reduction == '0' || reduction == 0 ) {
							reduction=" - - "
						} else {
							reduction="- "+reduction+ " &pound;";
						}		
						quantityDiscountElement.innerHTML=reduction;
						
						// get back all the needed informations:
						var reductionCoupon=getTotalForKey(totals,"poundCPNReduction")+" &pound;";
						updateTotalsWithCoupon(totals,reductionCoupon);
						
					} else {				
						var reductionElement=document.getElementById("reduction");
						var reduction = getTotalForKey(totals,'reductionPound');
						if( reduction == '0' || reduction == 0 ) {
							reduction=" - - "
						} else {
							reduction="- "+reduction+" &pound;";
						}
						reductionElement.innerHTML="Quantity Discount: "+reduction;
						
						var twrElement=document.getElementById("totalCartHTWR");
						gTotalForCheck = formatCurrency(getTotalForKey(totals,'poundWR'));
						twrElement.innerHTML= "Total: " + gTotalForCheck +" &pound;";
					}
				break;		
			}
		}
		
	};
	ajxHttp.open( "POST", vRequest, true );
	ajxHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajxHttp.setRequestHeader("Content-length", vParams.length);
	ajxHttp.setRequestHeader("Connection", "close");
	ajxHttp.setRequestHeader("Cache-Control", "no-cache");	
	ajxHttp.send(vParams);
};

/*
	udate coupon fields if needed:
*/
function updateTotalsWithCoupon(inTotals,inReduction) {
	// update global reduction:
	gGlobalReduction=getTotalForKey(inTotals,'globalReduction');
	var couponReductionElement=document.getElementById("couponReduction");

	if( gGlobalReduction > 0 ) {		
		var couponContent="<table><tr><td width=\"110\" align=\"center\"><div class=\"totalDetail\">-"+gGlobalReduction+"% rebate </div></td><td width=\"100\" align=\"center\"></td>";
		couponContent+="<td width=\"100\" align=\"center\"><div class=\"productTotal\">- "+ inReduction +"</div></td></tr></table>";
		couponReductionElement.innerHTML=couponContent;
		couponReductionElement.className="line";
	} else {
		couponReductionElement.innerHTML="";
		couponReductionElement.className="";
	}
};

/*
	inFlag --> true, false
*/
function setSpinnerVisible(inFlag) {
	if ($("spinnerButton")) {
		if (inFlag == true) {
			$("spinnerButton").className = "loading";
		}
		else {
			$("spinnerButton").className = "";
		}
	}
};

/*
	inMode --> "" or "full"
*/
function changeDevise(inDevise,inMode) {
	// store currency in session:
	var vRequest = "script/cart/manageCart.php";
	var vParams = "currency="+inDevise;
	vHttp.open("POST", vRequest, false);
	vHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	vHttp.setRequestHeader("Content-length", vParams.length);
	vHttp.setRequestHeader("Connection", "close");
	vHttp.setRequestHeader("Cache-Control", "no-cache");
	vHttp.send(vParams);
	
	var vResponse = vHttp.responseText;
	gDevise = inDevise;
	
	var element = getElementsByClass(document,"softPrice","*");
	var soft=null;
	
	for( var i=0;i<element.length;i++ ) 
	{
		soft = getSoftById(element[i].id);
		element[i].innerHTML = getFormattedValueForCurrency(soft[inDevise], inDevise);
		// When promo or reduction required
		var children=element[i].parentNode.getElementsByTagName("div");
		for( var j=0;j<children.length;j++ ) {
			var ch = children[j];
			if( ch.className == "oldSoftPrice" ) 
			{
				//console.log( soft.id );
				//console.log( ORIGINAL_PRICES[ soft.id ] );
				var amount=ORIGINAL_PRICES[ soft.id ][inDevise];
				if( amount ) {
					ch.innerHTML = getFormattedValueForCurrency(amount, inDevise);
				}
			}
		}	
	}
	
	manageCart(0,"",inMode);
}

function initPrices() {
	changeDevise(gDevise);
}

function enterCoupon() {
	var cpel=document.getElementById("coupon");
	if( cpel ) {
		setSpinnerVisible(true);
		if( cpel.value.length > 0 ) {
			checkGlobalReduction(cpel.value);
			manageCart(0,"", "full");
		} else {
			// remove global reduction div
			//initEnvironment(gDefaultKeyEnvironment);
			revealEnvironment();
			manageCart(0,"", "full");
		}
	}
};


function formatCurrency(num) {
	var fnum=num.toString(),
		tn=0;
	var idot=fnum.indexOf(".");
	if( idot > 0 ) {
		tn = fnum.substring(idot, fnum.length-1);
		if( tn.length==1 ) {
			fnum = num + "0";
		}
	}
	return fnum;
};

function getFormattedValueForCurrency(inValue, inDevise) {	
	
	var outFormattedText = "";
	switch(inDevise) {
		case 'dollar':
			outFormattedText = "$" + formatCurrency(inValue);
		break;
		case 'euro':
			outFormattedText = formatCurrency(inValue) + " &euro;";
		break;
		case 'pound':
			outFormattedText = formatCurrency(inValue) + " &pound;";
		break;		
	}
	return outFormattedText;
};

function getElementsByClass(node,searchClass,tag) {
	var classElements = new Array();
	var els = document.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = RegExp("(^|\\s)" + searchClass + "(\\s|$)");
	for (var i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
};

/*
	inMode: 'simple' 'full'
	inType: 0 -> update cart
			1 -> add product to cart
			2 -> delete product from cart

*/
function manageCart(inType, inId, inMode) {	
	var vRequest = "script/cart/manageCart.php";
	var vResponse = "";
	var vParams = "";
	switch( inType ) {
		case 0:
			// UPDATE CART
			vParams = "type=update";
			vHttp.open("POST", vRequest, false);		
			vHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			vHttp.setRequestHeader("Content-length", vParams.length);
			vHttp.setRequestHeader("Connection", "close");
			vHttp.setRequestHeader("Cache-Control", "no-cache");
			vHttp.send(vParams);
			vResponse = vHttp.responseText.split("|");
			var vSoftCount=0;			
			if( vResponse[0] == "OK" ) {
				
				var element = document.getElementById('products');
				if( element ) {
					element.innerHTML = "";//"<div id='cartBody'>";
					
					if( inMode == "full") {
						// sort array by name
						vResponse.sort();	
					}
					
					// get all the elements in card				
					for( var i=1;i<vResponse.length;i++ ) {
						// name : quantity
						var cartForElement = vResponse[i].split(":");
						var id = cartForElement[0];
						var quantity = cartForElement[1];
						
						// add element to card
						var soft=getSoftById(id);
						if( soft != "" && quantity > 0) {
							//
							if( inMode != "full" && inMode != "minicart" ) inMode="simple";
							if( inMode == "simple" ) {
								element.innerHTML += "<div class='line'>"
									+ "<div class='title'>"
									+ "<div class='product'>" + soft.softName + "</div>"
									+ "<div class='detail'>" + soft.detail + "</div>"
									+ "</div>"
									+ "<div class='details'>"
									+ "<div class='quantity'>" + quantity + "</div>"
									+ "<div class='price'>" + getFormattedValueForCurrency(soft[gDevise], gDevise) + "</div>"
									+ "<div class='moins'onClick=\"manageCart(2," + "\'" + id + "\'" + ",'simple');\">&nbsp;</div>"
									+ "</div></div>";
							} else if( inMode == "full" ) {
								vSoftCount += quantity*1.00;
								element.innerHTML += "<div class='line'>"
									+ "<div class='productTitle'>" + soft.softName + " - " + soft.detail + "</div>"
									+ "<div class='productCount'>" + quantity + "</div>"
									+ "<div class='manage'><div class='plus' onClick=\"manageCart(1,"+ "\'" + id + "\'" + ",'full');\"></div>"
									+ "<div class='moins' onClick=\"manageCart(2," + "\'" + id + "\'" + ",'full');\"></div></div>"
									+ "<div class='productPrice'>" + getFormattedValueForCurrency(soft[gDevise], gDevise) + "</div>"
									+ "<div class='productTotal'>"+ getFormattedValueForCurrency(quantity*soft[gDevise], gDevise) +"</div>";								
								element.innerHTML+="</div><div class='lineSeparator'></div>";
									
									
							} else if( inMode == "minicart" ) {
								 vSoftCount += quantity*1.00;
							}
						}
					}
					
					//if( vResponse.length == 2 ) {
						//alert(vResponse.length);
					//} 
					
					if( inMode == "full" ) {
						// update currency select combo box:
						var element = document.getElementById("currencySelect");
						if( gDevise == 'dollar') element.options[0].selected=true
						else if( gDevise == 'pound') element.options[1].selected=true;
						else if( gDevise == 'euro') element.options[2].selected=true;
						setTotal(gDevise,inMode);
					}	
					
					if( inMode == "simple" ) {
						// update the medium cart width for the vertical scrollbar
						var element = document.getElementById("products");
						//console.log( vResponse );
						
						var prd=null, pdt=null,pdCount=0;
						for( var i=1,len=vResponse.length;i<len;i++ )
						{
							prd=vResponse[i];
							pdt = prd.split(':');
							//console.log( pdt );
							pdCount+=parseInt(pdt[1]);
						}
						//console.log( "product count "+pdCount );
						
						if( pdCount == 1 ) {
							var off = document.getElementById("5off");
							off.style.display = "block";
						} else {
							var off = document.getElementById("5off");
							off.style.display = "none";
						}
						
						
						if( vResponse.length > 9 ) {
							element.style.width="188px";
							
						} else {
							element.style.width="170px";
						}
						setTotal(gDevise,inMode);
					}
					
					if( inMode == "minicart" ) {
						updateMiniCart(vSoftCount);
					}
				
				}
			} else {
				// error	
			}			
			setSpinnerVisible(false);
			break;
		case 1:
			// ADD PRODUCT			
			vParams = "type=add&element="+inId;
			vHttp.open( "POST", vRequest, false );
			vHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			vHttp.setRequestHeader("Content-length", vParams.length);
			vHttp.setRequestHeader("Connection", "close");
			vHttp.setRequestHeader("Cache-Control", "no-cache");
			
			vHttp.send( vParams );
			vResponse = vHttp.responseText;
			if( vResponse == "OK" ) {
				manageCart( 0, "", inMode );
				
			}
			break;
		case 2:
			// REMOVE PRODUCT
			vParams = "type=delete&element="+inId;
			vHttp.open("POST", vRequest, false);
			vHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			vHttp.setRequestHeader("Content-length", vParams.length);
			vHttp.setRequestHeader("Connection", "close");
			vHttp.setRequestHeader("Cache-Control", "no-cache");
			
			vHttp.send(vParams);
			vResponse = vHttp.responseText;
			if( vResponse == "OK" ) {
				manageCart(0,"",inMode);
			}
			break;
	}	
}

/* VAT */
function checkVATNumber(countryCode) {
	var countryCodeEl = document.getElementById("vatCountryCode");	
	var vatNumberEl = document.getElementById("vatNumber");
	var countryCodeValue = countryCode;	
	if( countryCodeEl ) {
		if( countryCodeEl.value.length > 0 ) {
			countryCodeValue = countryCodeEl.value;
		} else {
			var selectCountryElement = document.getElementById( "country" );
			var userCountryCode = selectCountryElement.options[selectCountryElement.selectedIndex].id;
			countryCodeValue = userCountryCode;
		}
	}
	
	var vatNumberValue = "";
	if( vatNumberEl ) {
		vatNumberValue = vatNumberEl.value;
	}
	
	var vResult = "";
	var vARequest = "script/cart/getTVA.php";
	var vParams = "country="+countryCodeValue +"&vat="+vatNumberValue;
	vHttp.open("POST", vARequest, false);
	vHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	vHttp.setRequestHeader("Content-length", vParams.length);
	vHttp.setRequestHeader("Connection", "close");
	vHttp.setRequestHeader("Cache-Control", "no-cache");
	vHttp.send(vParams);
	var vResult = vHttp.responseText;
	var taxeElement = document.getElementById("tvaValue");
	if( taxeElement ) {
		// --> update TVA
		if(  vResult > 0 ) {
			taxeElement.innerHTML =  vResult+" %";
		} else {
			taxeElement.innerHTML = " - - ";
		}
		// recalculate all the totals:
		setTotal(gDevise,"full");
	}
}

/*
	if there's no country 'programmatically' found
	try to use the user's choice...

*/
function checkVatCountryCode() {
	// if there's no country found:
	var countryCodeEl = document.getElementById("vatCountryCode");
	if( countryCodeEl.value == "" ) {
	 
		// get the country code specified by user by selecting
		// it country:
		var countryComboBx=document.getElementById("country");
		var selectedIndex = countryComboBx.selectedIndex;
		var countryCode = countryComboBx.options[selectedIndex].id;
		
		if( countryCode == "Unknown" ) countryCode="";
		
		// ...
		// no set the input with the country found:
		//countryCodeEl.value = countryCode;
		checkVATNumber(countryCode);
	}
}

function initCountry() {
	if( !gCountryCode ) {
		var vRequest = "script/cart/ip_toc.php";
		vHttp.open("GET", vRequest, false);
		vHttp.send(null);
		var vResponse = vHttp.responseText;
		var vArr=vResponse.split("|");
		if( vArr.length > 0 ) {
			gCountryCode = vArr[0];
			gCountryName = vArr[1];
		} else {
			gCountryCode = "";
			gCountryName = "";
		}
	}
	
	updateInterestedZone();
	checkVATNumber();
	
}

function updateInterestedZone() {
	
	// Write country code in the 
	// VAT country code text field
	var element = document.getElementById("vatCountryCode");
	if( element ) {
		if( gCountryCode == "" ) {
			//element;
			element.readOnly = false;
		} else {
			element.value = gCountryCode;
			if( VAT_READONLY ) {
				element.readOnly = true;
			} else {
				element.readOnly = false;
			}
		}
	}
	
	// select the country in combo box
	// depends the founded country code
	var countryCmb = document.getElementById("country");
	if( countryCmb ) {
		var options = countryCmb.options;
		options[0].selected=true;
		if( gCountryCode != "" ) {
			for( var i=0;i<options.length;i++ ) {
				if( options[i].id == gCountryCode ) {
					options[i].selected=true;
					break;
				}	
			}
		}
	}
}

// MINI CART
//
function updateMiniCart(productCount) {
	var mcCount = document.getElementById("mcCount");
	if( mcCount ) {
		if( productCount >= 1 ) {
			var itemText=( productCount == 1 ) ? "item":"items";
			htmlText="<a href=\"http://www.aquafadas.com/store/cart.html\">&gt;"+productCount+" "+itemText+" in cart</a>";
		} else {
			htmlText=productCount+" item";
		}
		mcCount.innerHTML=htmlText;
	}
}
		

/*
	Check the validity of the required information fields
*/
function checkFields() {

	var isFieldsOK = true;
	// required fields:
	var firstName = document.getElementById("firstname");
	var lastName = document.getElementById("lastname");
	var countrySelection = document.getElementById("country");
		
	var email = document.getElementById("email");	
	var emailRetype = document.getElementById("emailretype");
		
	var adress = document.getElementById("address1");	
	var city = document.getElementById("city");	
	var phone = document.getElementById("phone");
	var zip = document.getElementById("zip");
	
	if( trim(firstName.value).length <= 0 ) {
		isFieldsOK = false;
		invalidForm(firstName);
	} else {
		validForm(firstName);
	}
	
	if( trim(lastName.value).length <= 0 ) {
		isFieldsOK = false;
		invalidForm(lastName);
	} else {
		validForm(lastName);
	}
	
	if( countrySelection.selectedIndex == 0 ) {
		isFieldsOK = false;
		invalidForm(countrySelection);
	} else {
		validForm(countrySelection);
	}
	
	if( checkMail(email.value) ) {
		validForm(email);
		// check the email retype:
		if( email.value != emailRetype.value ) {
			// retype email is required
			isFieldsOK = false;
			invalidForm(emailRetype);
		} else {
			validForm(emailRetype);
		}
	} else {
		isFieldsOK = false;
		invalidForm(email);
	}
		
	if( trim(adress.value).length <= 0 ) {
		isFieldsOK = false;
		invalidForm(adress);
	} else {
		validForm(adress);
	}
	
	if( trim(city.value).length <= 0 ) {
		isFieldsOK = false;
		invalidForm(city);
	} else {
		validForm(city);
	}
	
	
	if( trim(phone.value).length <= 0 ) {
		isFieldsOK = false;
		invalidForm(phone);
	} else {
		validForm(phone);
	}

	if( trim(zip.value).length <= 0 ) {
		isFieldsOK = false;
		invalidForm(zip);
	} else {
		validForm(zip);
	}
	
	if( isFieldsOK ) {
		var paymenttype;
		var cc = document.getElementById("creditcard");
		//var pp = document.getElementById("paypal").selected;
		if( cc.checked ) {
			paymenttype = "creditcard";
		} else {
			paymenttype = "paypal";
		}
		
		var currencySelect = document.getElementById("currencySelect").value;
		var firstname = document.getElementById("firstname").value;
		var lastname = document.getElementById("lastname").value;
		
		var countryComboBx=document.getElementById("country");
		var country = countryComboBx.value;
		// country code:
		var selectedIndex = countryComboBx.selectedIndex;
		var countryCode = countryComboBx.options[selectedIndex].id;
		
		var email = document.getElementById("email").value;
		//var emailretype = document.getElementById("emailretype").value;
		var alternativeEmail = document.getElementById("alternativeEmail").value;
		
		var company = document.getElementById("company").value;
		var address1 = document.getElementById("address1").value;
		var address2 = document.getElementById("address2").value;
		var city = document.getElementById("city").value;
		var state = document.getElementById("state").value;
		var zip = document.getElementById("zip").value;
		var phone = document.getElementById("phone").value;
		// VAT:
		var vatCountryCode = document.getElementById("vatCountryCode").value;
		var vatNumber = document.getElementById("vatNumber").value;
		
		var cansendproductoffers = document.getElementById("cansendproductoffers");
		var cspof=(cansendproductoffers.checked)?1:0;
		
		var vGetParam = "?paymenttype="+paymenttype+"&firstname="+firstname+"&lastname="+lastname+"&email="+email;
		vGetParam += "&alternativeEmail="+alternativeEmail;
		vGetParam += "&country="+country+"&countryCode="+countryCode;
		vGetParam += "&currencySelect="+currencySelect+"&vatNumber="+vatNumber+"&vatCountryCode="+vatCountryCode;
		vGetParam += "&address1="+encodeStringForParam( address1 );
		vGetParam += "&address2="+encodeStringForParam(address2);
		vGetParam += "&city="+encodeStringForParam( city )+"&state="+encodeStringForParam( state )+"&zip="+zip+"&phone="+phone;
		vGetParam += "&company="+encodeStringForParam( company )+"&cansendproductoffers="+cspof;
		
		
		if( paymenttype == 'creditcard' ) {
			var vRequest = "script/cart/cybermutCommand.php"+vGetParam;	
			vHttp.open("get", vRequest, false);
			vHttp.send(null);
	
			vResponse = vHttp.responseText.split("|");		
	
			if ( vResponse[0] != "OK" ) {
				document.getElementById('alertMessage').innerHTML = "Request timeout, you will be redirect on the main page of the store";
				window.scroll(0,0);
				setTimeout( 
					function() {
						location.href='/store/';
					},1000
				);
			}
			else {
				document.getElementById('div_credit_mutuel').innerHTML = vResponse[1];
				document.getElementById('credit_mutuel').submit();
			}
			
		} else {	
			var vRequest = "script/cart/paypalCommand.php"+vGetParam;
			vHttp.open("get", vRequest, false);
			vHttp.send(null);
			
			vResponse = vHttp.responseText.split("|");

			if ( vResponse[0] != "OK" ) {
				document.getElementById('alertMessage').innerHTML = "Request timeout, you will be redirect on the main page of the store";
				window.scroll(0,0);
				setTimeout( 
					function() {
						location.href='/store/';
					},1000
				);
			} else {
				document.getElementById('div_credit_mutuel').innerHTML = vResponse[1];
				document.getElementById('paypalForm').submit();
			}
		
		}

	} else {
		// retype...
	}
}

function encodeStringForParam( url ) {
	return url.replace( "&", "%26" );
}

function trim(s) { 
    var l=0; var r=s.length -1; 
    while(l < s.length && s[l] == ' ') 
    {     l++; } 
    while(r > l && s[r] == ' ') 
    {     r-=1;     } 
    return s.substring(l, r+1); 
} 

function invalidForm(inFormElement) {
	inFormElement.style.borderColor="#ff9900";
	inFormElement.style.borderStyle="solid";
}

function validForm(inFormElement) {
	inFormElement.style.borderColor="";
	inFormElement.style.borderStyle="";
}

function checkMail(inEmail) {
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(inEmail)) {
		return true;
	} else {
		return false;
	}
}
function $(id){
	return document.getElementById(id);
}
