var AQGlobal = {
	MANAGE_CART : 'script/cart/manageCart-present.php',
	PRESENT_PREFFIX : 'PRE',
	BACKGROUND_POPUP : 'http://www.aquafadas.com/store/images/kado/popup-kado.png',
	COMMAND : 'script/cart/command-28-06-2010.php',
	
	CART_PAGE : {
		'FR' : 'cart-present-fr.php',
		'EN' : 'cart-present.php'
	}
};

var Locale = {
	current : null,
	en : {
		friendemail : 'Your friend\'s email',
		friendfirstname : 'Your friend\'s first name',
		friendpersonalmessage : 'Write a personal message',
		invalidfields : 'One or more fields are invalid',
		choosemail : 'I prefer to send a gift card by email',
		chooseprint : 'I\'m choosing to send a printed gift card',
		chooseprint2 : 'In the invoice email you will receive a link to download the gift card'
	},
	
	fr : {
		friendemail : 'Email de votre ami(e)',
		friendfirstname : 'Nom de votre ami(e)',
		friendpersonalmessage : 'Ecrivez un message personnalisé ici',
		invalidfields : 'Un ou plusieurs champs sont invalides',
		choosemail : 'I prefer to send a gift card by email',
		chooseprint : 'Je choisi d\'envoyer une carte cadeau imprimée',
		chooseprint2 : 'Je recevrais dans mon mail facture un lien pour télécharger ma carte cadeau que je pourrais ensuite imprimer et plier'
		
	},
	
	value : function( key ) {
		return this.current[ key ]
	}
};

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={'pm1':{'euro':39,'dollar':49,'pound':39},'pm2':{'euro':65,'dollar':89,'pound':65},'pm3':{'euro':35,'dollar':45,'pound':35},'vp1':{'euro':39,'dollar':49,'pound':39},'vp2':{'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},'id4':{'euro':55,'dollar':75,'pound':55},'bzp4':{'euro':59,'dollar':85,'pound':59},'bzp5':{'euro':99,'dollar':135,'pound':99},'id1':{'euro':59,'dollar':79,'pound':59},'id2':{'euro':109,'dollar':149,'pound':109},'vp3':{'euro':35,'dollar':45,'pound':35},'bzp3':{'euro':79,'dollar':99,'pound':79},'bz1':{'euro':39,'dollar':49,'pound':39},'bz2':{'euro':65,'dollar':89,'pound':65},'id3':{'euro':30,'dollar':40,'pound':30},'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':59,'dollar':85,'pound':59},'pmad5':{'euro':99,'dollar':135,'pound':99},'pmad6':{'euro':35,'dollar':45,'pound':35},'pmad7':{'euro':122,'dollar':170,'pound':122},'pmad8':{'euro':65,'dollar':89,'pound':65},'bzw3':{'euro':28,'dollar':36,'pound':28},'bzpw1':{'euro':71,'dollar':103,'pound':71},'bzpw2':{'euro':127,'dollar':175,'pound':127},'bzpw4':{'euro':45,'dollar':68,'pound':45},'bzpw3':{'euro':63,'dollar':79,'pound':63},'bzw1':{'euro':29,'dollar':39,'pound':29},'bzw2':{'euro':52,'dollar':71,'pound':52},'bzpw5':{'euro':79,'dollar':108,'pound':79},'vphd4':{'euro':44,'dollar':60,'pound':44},'pm1V2':{'euro':39,'dollar':49,'pound':39},'pm2V2':{'euro':65,'dollar':89,'pound':65},'pm3V2':{'euro':35,'dollar':45,'pound':35},'pm4V2':{'euro':12,'dollar':15,'pound':12},'snp1':{'euro':89,'dollar':129,'pound':89},'snp3':{'euro':79,'dollar':99,'pound':79},'snp2':{'euro':159,'dollar':219,'pound':159},'bz23':{'euro':19,'dollar':25,'pound':19},'bzp23':{'euro':45,'dollar':59,'pound':45},'bzp24':{'euro':38,'dollar':55,'pound':38},'bz24':{'euro':35,'dollar':45,'pound':35},'bzp21':{'euro':89,'dollar':129,'pound':89},'bzp22':{'euro':159,'dollar':219,'pound':159},'bzp26':{'euro':59,'dollar':85,'pound':59},'bzp25':{'euro':79,'dollar':99,'pound':79},'bz21':{'euro':39,'dollar':49,'pound':39},'bz22':{'euro':65,'dollar':89,'pound':65},'bzw23':{'euro':15,'dollar':19,'pound':15},'bzpw23':{'euro':39,'dollar':49,'pound':39},'bz25':{'euro':29,'dollar':39,'pound':29},'bzp27':{'euro':65,'dollar':89,'pound':65},'bzp28':{'euro':76,'dollar':110,'pound':76},'ex0001':{'euro':19,'dollar':24.9,'pound':19},'ex0006':{'euro':19,'dollar':24.9,'pound':19},'id24':{'euro':55,'dollar':75,'pound':55},'id23':{'euro':19,'dollar':29,'pound':19},'id21':{'euro':59,'dollar':79,'pound':59},'id22':{'euro':109,'dollar':149,'pound':109},'ex0002':{'euro':19,'dollar':24.9,'pound':19},'ex0003':{'euro':19,'dollar':24.9,'pound':19},'ex0004':{'euro':19,'dollar':24.9,'pound':19},'ex0005':{'euro':19,'dollar':24.9,'pound':19},'ex0006':{'euro':19,'dollar':24.9,'pound':19},'pmad31':{'euro':89,'dollar':129,'pound':89},'pmad32':{'euro':159,'dollar':219,'pound':159},'pmad33':{'euro':79,'dollar':99,'pound':79},'pmad34':{'euro':59,'dollar':85,'pound':59},'pmad37':{'euro':122,'dollar':170,'pound':122},'pm1V3':{'euro':39,'dollar':49,'pound':39},'pm2V3':{'euro':65,'dollar':89,'pound':65},'pm3V3':{'euro':35,'dollar':45,'pound':35},'pm4V3':{'euro':19,'dollar':25,'pound':19},'pmad38':{'euro':45,'dollar':59,'pound':45},'pmad39':{'euro':79,'dollar':99,'pound':79},'pmad30':{'euro':65,'dollar':89,'pound':65},'pm5V3':{'euro':29,'dollar':39,'pound':29},'pmad36':{'euro':65,'dollar':89,'pound':65},'bzpc1':{'euro':39,'dollar':49,'pound':39},'bzppc1':{'euro':89,'dollar':129,'pound':89},'bzpc2':{'euro':65,'dollar':89,'pound':65},'bzppc2':{'euro':159,'dollar':219,'pound':159},'6zowdz':{'euro':59,'dollar':85,'pound':59}
};

/* 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();

// POPUP
(function() {
	var _popup = null;
	var _onclickOKHandler = null;
	var TEXT_MAX_LENGTH = 200;
	function createPopup() 
	{
		
		var popup = document.createElement('div');
		popup.id="offerToAFriendPopup";
		
		var selectprintormail = document.createElement('div');
		
		var selectprint = document.createElement('div');
		selectprint.innerHTML = "<table><tr valign='top'><td><input type='radio' id='okmail'/></td><td><b style='font-size:16px'>"+Locale.value('chooseprint')+"</b>. "+Locale.value('chooseprint2')+".<br /><br /></td></tr></table>";
		selectprint.style.width = "292px";
		selectprint.style.cursor = "pointer";
		
		var selectmail = document.createElement('div');
		selectmail.innerHTML = "<table><tr valign='top'><td><input type='radio' id='okprint'/></td><td><b style='font-size:16px'>"+Locale.value('choosemail')+"</b>.</td></tr></table>";
		selectmail.style.width = "292px";
		selectmail.style.cursor = "pointer";
		
		var cancelBtn = document.createElement('input');
		cancelBtn.id = "stfCancel";
		cancelBtn.style.marginLeft="170px";
		cancelBtn.style.position="absolute";
		cancelBtn.style.top="240px";
		cancelBtn.type="button";
		cancelBtn.value = "Cancel";
		cancelBtn.onclick = function() {
			OfferToAfriendPopup.close();
		};
		
		var message = document.createElement('div');
		message.id = 'oftf-message';
		
		selectprintormail.appendChild( selectprint );
		selectprintormail.appendChild( selectmail );
		selectprintormail.appendChild( cancelBtn );
		selectprintormail.appendChild( message );
		
		popup.appendChild( selectprintormail );
		
		////////////////////////////////////////////////
		var contentallinputmail = document.createElement('div');
		contentallinputmail.id="contentallinputmail";
		
		var contentinputEntitled = document.createElement('div');
		contentinputEntitled.className = "contentinput";
		var contentinputMail = document.createElement('div');
		contentinputMail.className = "contentinput";
		var contentinputText = document.createElement('div');
		contentinputText.className = "contentinput";
		contentinputText.style.height = "100px";
		
		var entitled = document.createElement('input');
		entitled.id="stfEntitled";
		entitled.className="inputPopup";
		entitled.maxlength='256'
		entitled.onclick = function() { 
			showInput('stfEntitled');
		}
		entitled.onkeypress = function(event) { 
			if(event.keyCode == 9){
				showInput('stfEmail');
			}
		}
		var entitledText = document.createElement('p');
		entitledText.innerHTML = Locale.value('friendfirstname');
		
		
		var email = document.createElement('input');
		email.id = "stfEmail";
		email.className="inputPopup";
		email.onclick = function() { 
			showInput('stfEmail');
		}
		
		email.onkeypress = function(event) { 
			if(event.keyCode == 9){
				showInput('stfText');
			}
		}
		email.maxlength='320';
		
		var emailText = document.createElement('p');
		emailText.innerHTML = Locale.value('friendemail');
		
		var text = document.createElement('textarea');
		text.id = "stfText";
		text.onclick = function() { 
			showInput('stfText');
		}
		
		var textText = document.createElement('p');
		textText.innerHTML = Locale.value('friendpersonalmessage');
		
		var okBtn = document.createElement('input');
		okBtn.id = "stfOK";
		okBtn.type="button";
		okBtn.value = "OK";
		okBtn.onclick = _onclickOKHandler;
		
		var cancelBtn = document.createElement('input');
		cancelBtn.id = "stfCancel";
		cancelBtn.type="button";
		cancelBtn.value = "Cancel";
		cancelBtn.onclick = function() {
			OfferToAfriendPopup.close();
			hideInput();
		};
		
		var count = document.createElement('span');
		count.id='stfCount';
		
		var message = document.createElement('div');
		message.id = 'oftf-message';
		
		var buttonBar = document.createElement('div');
		buttonBar.className = "buttonBar";
		buttonBar.appendChild( okBtn );
		buttonBar.appendChild( cancelBtn );
		buttonBar.appendChild( count );
		
		contentinputEntitled.appendChild( entitledText );
		contentinputEntitled.appendChild( entitled );
		contentinputMail.appendChild( emailText );
		contentinputMail.appendChild( email );
		contentinputText.appendChild( textText );
		contentinputText.appendChild( text );
		
		
		contentallinputmail.appendChild( message );
		contentallinputmail.appendChild( contentinputEntitled );
		contentallinputmail.appendChild( contentinputMail );
		contentallinputmail.appendChild( contentinputText );
		contentallinputmail.appendChild( buttonBar );
		
		StandardForm.affectStandardInput( email,_onclickOKHandler,function() {
			OfferToAfriendPopup.displayErrorMessage();
		} );
		StandardForm.affectStandardInput( entitled,_onclickOKHandler,function() {
			OfferToAfriendPopup.displayErrorMessage();
		} );
		StandardForm.affectStandardInput( text,_onclickOKHandler,function() {
			OfferToAfriendPopup.displayErrorMessage();
		} );
		
		text.onkeyup = text.onchange = function() {
			var t=null;
			var l=this.value.length;
			if( l > TEXT_MAX_LENGTH ) {
				t = '<i style="padding:2px;background-color:red;color:white">' + l + "/"+ TEXT_MAX_LENGTH + '</i>';
			} else {
				t = '<i style="padding:2px;color:red">' + l + "/"+ TEXT_MAX_LENGTH + '</i>';
			}
			
			document.getElementById('stfCount').innerHTML = t;
		};
		
		/////////////////////////////////////////////////////
		////////////////////////////////////////////////
		var contentallinputprint = document.createElement('div');
		contentallinputprint.id="contentallinputprint";
		
		var contentinputEntitled = document.createElement('div');
		contentinputEntitled.className = "contentinput";
		var contentinputMail = document.createElement('div');
		contentinputMail.className = "contentinput";
		
		var entitled = document.createElement('input');
		entitled.id="stfEntitled";
		entitled.className="inputPopup";
		entitled.maxlength='256'
		entitled.onclick = function() { 
			showInput('stfEntitled');
		}
		
		entitled.onkeypress = function(event) { 
			if(event.keyCode == 9){
				showInput('stfEmail');
			}
		}
		var entitledText = document.createElement('p');
		entitledText.innerHTML = Locale.value('friendfirstname');
		
		
		var email = document.createElement('input');
		email.id = "stfEmail";
		email.className="inputPopup";
		email.onclick = function() { 
			showInput('stfEmail');
		}
		
		
		email.maxlength='320'
		
		var emailText = document.createElement('p');
		emailText.innerHTML = Locale.value('friendemail');
		
		var okBtn = document.createElement('input');
		okBtn.id = "stfOK";
		okBtn.type="button";
		okBtn.value = "OK";
		okBtn.onclick = _onclickOKHandler;
		
		var cancelBtn = document.createElement('input');
		cancelBtn.id = "stfCancel";
		cancelBtn.type="button";
		cancelBtn.value = "Cancel";
		cancelBtn.onclick = function() {
			OfferToAfriendPopup.close();
			hideInput();
		};
		
		var message = document.createElement('div');
		message.id = 'oftf-message';
		
		var buttonBar = document.createElement('div');
		buttonBar.className = "buttonBar";
		buttonBar.style.position="absolute";
		buttonBar.style.top="200px";
		buttonBar.appendChild( okBtn );
		buttonBar.appendChild( cancelBtn );
		
		
		contentinputEntitled.appendChild( entitledText );
		contentinputEntitled.appendChild( entitled );
		contentinputMail.appendChild( emailText );
		contentinputMail.appendChild( email );
		
		contentallinputprint.appendChild( message );
		contentallinputprint.appendChild( contentinputEntitled );
		contentallinputprint.appendChild( contentinputMail );
		contentallinputprint.appendChild( buttonBar );
		
		StandardForm.affectStandardInput( email,_onclickOKHandler,function() {
			OfferToAfriendPopup.displayErrorMessage();
		} );
		StandardForm.affectStandardInput( entitled,_onclickOKHandler,function() {
			OfferToAfriendPopup.displayErrorMessage();
		} );
		
		/////////////////////////////////////////////////////////////////
		
		
		_popup = document.createElement('div');
		
		_popup.id="popupContainer";
		_popup.appendChild( popup );
		
		_popup.style.display="none";
		document.body.appendChild( _popup );
		
		// load the image, onload display the popup:
		var img = new Image();
		img.onload = img.onerror = function() {
			_popup.style.display="block";
			popup.style.backgroundImage="url("+this.src+")";
		};
		img.src = AQGlobal.BACKGROUND_POPUP;
		
		selectmail.onclick = function() {
			Dom.removeAllChildren( popup );
			popup.appendChild( contentallinputmail );
		};
		
		selectprint.onclick = function() {
			Dom.removeAllChildren( popup );
			popup.appendChild( contentallinputprint );
		};

	};
	
	var Dom={
		removeAllChildren : function( el ) {
			if ( el && el.hasChildNodes() ) {
				while ( el.childNodes.length >= 1 ) {
					el.removeChild( el.firstChild );       
				}
			}
		}
	};
	
	var OfferToAfriendPopup = {
		open : function ( onclick ) {
			_onclickOKHandler = onclick;
			createPopup();
			
		},
		close : function() {
			_popup.style.display="none";
			_popup.innerHTML="";
			//this.displayErrorMessage();
		},
		displayErrorMessage : function( message ) {
			message = message || '';
			document.getElementById('oftf-message').innerHTML = message;
		},
		getData : function() {				
			if(document.getElementById("stfText")){
				return {
					format	: "email",
					entitled	: document.getElementById('stfEntitled').getRealValue(),
					email	 	: document.getElementById('stfEmail').getRealValue(),
					text	 	: document.getElementById('stfText').getRealValue()
				};
			}else{
				return {
					format	: "pdf",
					entitled	: document.getElementById('stfEntitled').getRealValue(),
					email	 	: document.getElementById('stfEmail').getRealValue()
				};
			}
			
		}
		
	};
	window.OfferToAfriendPopup = OfferToAfriendPopup;
	
})();

function showInput(el){
	var stfEntitled = document.getElementById('stfEntitled');
	var stfEmail = document.getElementById('stfEmail');
	var stfText = document.getElementById('stfText');
	if(stfEntitled.id == el){
		stfEntitled.className = "selected";
	}
	if(stfEmail.id == el){
		stfEmail.className = "selected";
	}
	if(document.getElementById('stfText')){
		if(stfText.id == el){
			stfText.className = "selected";
		}
	}
};

function hideInput(){
	/*var stfEntitled = document.getElementById('stfEntitled');
	var stfEmail = document.getElementById('stfEmail');
	var stfText = document.getElementById('stfText');
	stfEntitled.className = "";
	stfEmail.className = "";
	if(document.getElementById('stfText')){
		stfText.className = "";
	}*/
};

/////////////////
var AquaCart={
	
	addPresent : function( pid ) {
		////////////////
		// TODO closure dysfunctional
		OfferToAfriendPopup.pid = pid;
		OfferToAfriendPopup.open( 
			function( p ) {
				return function(){
					var data = OfferToAfriendPopup.getData();
					var invalidData = false;
					// check the data:
					for( var key in data ) 
					{
						var d = data[key];
						if( trim( d.toString() ).length == 0 ) {
							invalidData = true;
						} else {
							if( key == 'email' ) {
								if( checkMail( d ) == false ) {
									invalidData = true;
								}
							}
						}
					}
					
					if (invalidData == true) {
						OfferToAfriendPopup.displayErrorMessage(
							Locale.value( 'invalidfields' )
							
						);
					}
					else {
						var cleanData = {};
						for (var key in data) {
							cleanData[key] = data[key].toString().replace(/&/g,'');
						}
						
						//console.log( cleanData );
						
						// get back all infos from the popup:
						// format data with JSON
						var params = {
							sendtofriend: JSON.stringify(cleanData)
						};
						AquaCart.manageCart(1, 
							OfferToAfriendPopup.pid, 'simple', 
							params, function(){
								OfferToAfriendPopup.close();
							}
						);
					}
				};
			}( pid )
		);
		
	},
	
	manageCart : function( type, pid, mode, params, oncomplete ) {
		manageCart( type, pid, mode, params, oncomplete );
	},
	
	isPresent : function( id ) {
		return (id.indexOf(AQGlobal.PRESENT_PREFFIX) == 0);
	}
};


// INIT 

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

function initEnvironment(inKey,lang) {
	// init locale
	Locale.current = Locale[ lang ];
	
	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;
			}
		}
	);
};

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

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 = "";
				}
			}
		);
	}		
};

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

function getSoftById( inId ) {
	var outSoft = "";
	var id = inId;
	// special case
	// PRESENT case:
	if( id.indexOf( AQGlobal.PRESENT_PREFFIX ) == 0 ) {
		// get back the soft id from data
		// EXAMPLE: 'PRES1-bz21'
		var t=id.split('-');
		id = t[1];
		
	}

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

/*
	inDevise:
		- dollar
		- euro
		- pound
*/
function getTotalForDevise(inDevise) 
{
	var outTotal = 0,
		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", AQGlobal.MANAGE_CART, 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 = AQGlobal.CART_PAGE['EN'];
		} else {
			cartLocation = AQGlobal.CART_PAGE['FR'];
		} 		
		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");
		
	var ajxHttp = Ajax.getHTTPRequest();
	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(":");
				//console.log( tt[0] + ' ' + tt[1] );
				totals.push( new Total(tt[0],tt[1]) );
			}
		//	htElement.innerHTML = (inMode == "full") ?"":"Total: ";
			// update the web page:
			var currencyUsed = 'dollar';
			var deviseReduction = 'reductionDollar';
			var sign = '$';
			switch (inDevise) {
				case 'dollar':
					currencyUsed = 'dollar';
					deviseReduction = 'reductionDollar';
					break;
				case 'euro':
					currencyUsed = 'euro';
					deviseReduction = 'reductionEuro';
					break;
				case 'pound':
					currencyUsed = 'pound';
					deviseReduction = 'reductionPound';
					break;
			}
			
			var deviseHT = currencyUsed+'HT';
			var deviseTTC = currencyUsed+'TTC';
			var deviseWR = currencyUsed+'WR';
			var deviseCouponReduction = currencyUsed + 'CPNReduction';

				
			if( inMode == "full" ) 
			{	
				if( htElement )
					htElement.innerHTML = formatCurrencyWithSign( inDevise, formatCurrency( getTotalForKey( totals,deviseHT ) ) );	
				
				var ttcElement = document.getElementById("totalCartTTC");
				ttcElement.innerHTML=formatCurrencyWithSign( inDevise, formatCurrency(getTotalForKey(totals,deviseTTC )) );
				
				var htWrElement = document.getElementById("totalCartWR");
				htWrElement.innerHTML = formatCurrencyWithSign( inDevise, formatCurrency(getTotalForKey(totals,deviseWR)) );
				
				/////////////////////
				// QUANTITY DISCOUNT:
				/////////////////////
				var quantityDiscountElement = document.getElementById("quantityDiscountNumber");
				var reduction = getTotalForKey(totals,deviseReduction);
				if( reduction == '0' || reduction == 0 ) {
					//reduction=" - - ";
					document.getElementById('qd-amount').style.display="none";
					document.getElementById('qd-discount').style.display="none";
				} else {
					document.getElementById('qd-amount').style.display="block";
					document.getElementById('qd-discount').style.display="block";
					reduction="- " + formatCurrencyWithSign(inDevise, reduction );
				}
				quantityDiscountElement.innerHTML=reduction;
				/////////////////////
				
				
				// get back all the needed informations:
				var reductionCoupon = formatCurrencyWithSign( inDevise, getTotalForKey(totals,deviseCouponReduction) );
				updateTotalsWithCoupon(totals,reductionCoupon);

			} else {
				if( htElement )
					htElement.innerHTML = 'Total: ' + formatCurrencyWithSign( inDevise, formatCurrency( getTotalForKey( totals,deviseHT ) ) );	
				
				/////////////////////
				// QUANTITY DISCOUNT:
				/////////////////////
				var reductionElement=document.getElementById("reduction");
				if( reductionElement ) 
				{
					var reduction = getTotalForKey( totals, deviseReduction );
					if( reduction == '0' || reduction == 0 ) {
						reduction=" - - "
					} else {
						reduction="- "+formatCurrencyWithSign(inDevise, reduction);
					}
					reductionElement.innerHTML="Quantity Discount: "+reduction;
				}
				/////////////////////
				
				var twrElement=document.getElementById("totalCartHTWR");
				gTotalForCheck = formatCurrency(getTotalForKey( totals,deviseWR ) );
				twrElement.innerHTML= "Total: " +formatCurrencyWithSign(inDevise,  gTotalForCheck );			
			}
		}
		
	};
	ajxHttp.open( "POST", AQGlobal.MANAGE_CART, 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);
};

function formatCurrencyWithSign( currency, amount  ) {
	switch( currency ) {
		case 'dollar':
			return '$' + amount;
			break;
		case 'euro':
			return amount + ' &euro;';
			break;
		case 'pound':
			return amount + ' &pound;';
			break;
	}
};

/*
	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 vParams = "currency="+inDevise;
	vHttp.open("POST", AQGlobal.MANAGE_CART, 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" ) 
			{
				if( soft.id && ORIGINAL_PRICES.hasOwnProperty( 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, params, oncomplete ) {	
	var vResponse = "";
	var vParams = "";
	switch( inType ) {
		case 0:
			// UPDATE CART
			vParams = "type=update";
			vHttp.open("POST", AQGlobal.MANAGE_CART, 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) {
						var isPresent = AquaCart.isPresent( id );
						var presentClass = "";
						var qtyForDisplay = quantity;
						if( isPresent == true ) {
							presentClass = " present";
							// do not display quantity
							//qtyForDisplay = '&nbsp;';
						}
						
						
						if( inMode != "full" && inMode != "minicart" ) inMode="simple";
						if( inMode == "simple" ) {				
							var html = "<div class='line"+presentClass+"'>"
								+ "<div class='title'>"
								+ "<div class='product'>" + soft.softName + "</div>"
								+ "<div class='detail'>" + soft.detail + "</div>"
								+ "</div>"
								+ "<div class='details'>"
								+ "<div class='quantity'>" + qtyForDisplay + "</div>"
								+ "<div class='price'>" + getFormattedValueForCurrency(soft[gDevise], gDevise) + "</div>"
								+ "<div class='moins"+ presentClass +" ' onClick=\"manageCart(2," + "\'" + id + "\'" + ",'simple');\">&nbsp;</div>"
								+ "</div></div>";
							element.innerHTML += html;
						} else if( inMode == "full" ) {
							vSoftCount += quantity*1.00;
							var softDetail = soft.softName;
							if( soft.detail.length > 0 ) {
								softDetail += " - " + soft.detail
							}

							var html = "<div class='line"+presentClass+"'>";
							html += "<div class='productTitle'>" + softDetail + "</div>";
							html += "<div class='productCount'>" + qtyForDisplay + "</div>";
								
							if( isPresent == false )	{
								html += "<div class='manage'><div class='plus' onClick=\"manageCart(1,"+ "\'" + id + "\'" + ",'full');\"></div>";
							} else {
								html += "<div class='manage'><div class='plus' ></div>";
							}
							
							html +=	"<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>";								
							html += "</div><div class='lineSeparator'></div>";
							element.innerHTML += html;	
								
						} 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="";
						
					} else {
						element.style.width="";
					}
					setTotal(gDevise,inMode);
				}
				
				if( inMode == "minicart" ) {
					updateMiniCart(vSoftCount);
				}
				
				
			} else {
				// error	
			}			
			setSpinnerVisible(false);
			break;
		case 1:
			// ADD PRODUCT			
			vParams = "type=add&element="+inId;
			if( params && typeof params['sendtofriend'] != 'undefined' ) {
				vParams += '&sendtofriend=' + params['sendtofriend'];
			}
			
			vHttp.open( "POST", AQGlobal.MANAGE_CART, 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 );
			}
			
			if (oncomplete) {
				setTimeout(function(){
					oncomplete()
				}, 1);
			}
			break;
		case 2:
			// REMOVE PRODUCT
			vParams = "type=delete&element="+inId;
			vHttp.open("POST", AQGlobal.MANAGE_CART, 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( trim(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 adress = document.getElementById("address");	
	var city = document.getElementById("city");	
	var phone = document.getElementById("phone");
	
	
	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);
	} else {
		isFieldsOK = false;
		invalidForm(email);
	}
		
	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 alternativeEmail = document.getElementById("alternativeEmail").value;
		
		var company = document.getElementById("company").value;
		var address = document.getElementById("address").value;
		var city = document.getElementById("city").value;
		var state = document.getElementById("state").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 params = "paymenttype="+paymenttype+"&firstname="+firstname+"&lastname="+lastname+"&email="+email;
		params += "&alternativeEmail="+alternativeEmail;
		params += "&country="+country+"&countryCode="+countryCode;
		params += "&currencySelect="+currencySelect+"&vatNumber="+vatNumber+"&vatCountryCode="+vatCountryCode;
		params += "&address1="+encodeStringForParam( address );
		params += "&city="+encodeStringForParam( city )+"&state="+encodeStringForParam( state )+"&phone="+phone;
		params += "&company="+encodeStringForParam( company )+"&cansendproductoffers="+cspof;

		if ( paymenttype == 'creditcard' ) {
			formId = 'credit_mutuel';
		}
		else {
			formId = 'paypalForm';
		}

		vHttp.open("POST", AQGlobal.COMMAND, 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");
		vHttp.send(params);
		
		var vResponse = vHttp.responseText.split("|");		

		if ( vResponse[0] != "OK" ) {
			// ERROR redirect to store page
			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 {
			// OK submit the form
			document.getElementById('div_credit_mutuel').innerHTML = vResponse[1];
			document.getElementById( formId ).submit();
		}
	} else {
		// retype...
	}
}

//TODO: MOVE to common
var StandardForm={
	
	affectInputForKeyEnter : function( input, onKeyEnterPress ) {
		input.onkeyup = function(event){
			if( this.nodeName.toUpperCase() != 'TEXTAREA' ) {
				if (event == null) 
					event = window.event;
				if (event && event.keyCode == 13) {
					onKeyEnterPress();
				}
			}
		};
	},
	
	affectStandardInput : function( input, onKeyEnterPress, onfocusaddon ) {
		// create a function
		input.getRealValue = function() {
			if (this.value == this.defaultValue) {
				return '';
			}
			return this.value;
		};
		//input.value = input.defaultValue;
		input.onfocus = function(){
			if ( this.value == this.defaultValue ) {
				this.value = "";
			}
			if( onfocusaddon ) {
				onfocusaddon();
			}
		};
		var oldOnBlur = input.onblur;
		input.onblur = function(){
			if (this.value == "") {
				this.value = this.defaultValue;
			}
			if( oldOnBlur ) {
				oldOnBlur.call( this );
			}
		};
		if( onKeyEnterPress ) {
			StandardForm.affectInputForKeyEnter( input, onKeyEnterPress )
		}
	}
	
};

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

var Event = {
	
	target: function(e) {
		if (!e) var e = window.event;
		var t=null;
		if (e.target) 
			t = e.target;
		else 
			if (e.srcElement) 
				t = e.srcElement;
		if ( t.nodeType == 3 ) // defeat Safari bug
			t = t.parentNode;
			
		return t;
	}
};

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