var AQ = {};

(function(){ // début de scope local

    //LSP.utils = LSP.utils || {}; // création d'un sous namespace pour y stocker nos classes utilitaires si celui-ci n'est pas déjà été créé
    //LSP.subscription = LSP.subscription || {}; // création d'un sous namespace pour y stocker nos classes utilitaires si celui-ci n'est pas déjà été créé

    /**
	* constructeur utils
	*/
	AQ.panier= function(lang) {
		this.lang = lang;
    	this.T = new AQ.translation(lang);
    };
	
    /**
	* variables et méthodes publiques propres à chaque instance
	* $amount.$order.$code.$currency.$clave;
	*/
    AQ.panier.prototype = {
    	totalProduits:"",
    	amount:"",
    	order:"",
    	code:"",
    	currency:"",
    	clave:"",
    	paysLivraison:"na",
    	tarifsFraisPort:{'ES':0,'FR':0,'OT':25, 'na':0},
    	fraisPort:"0",
    	totalCommande:"",
        setPaysLivraison:function(PL){
        	this.paysLivraison = PL;
        	this.calcFraisPort();
        	this.calcTotalCommande();
        	this.listTotal();
        	if(this.paysLivraison != "na"){
        		this.calcSignature();
        	}
        },
        setMessage:function(message){
        	this.message = message;
        },
        calcSignature:function(){
        	var instance= this;
        	this.setMessage(String(this.amount)+String(this.order)+String(this.code)+String(this.currency)+String(this.clave));
        	this.updateMessage();
        	this.updateAmount();
        	$j.post('../../includes/ajax.php', {action:"getSignature", message:this.message}, 
        			function(data){
        			instance.updateSignature(data);
        	}, "text");
        },
        updateSignature:function(data){
        	$j('input[name=Ds_Merchant_MerchantSignature]').val(data);
        },
        updateMessage:function(){
        	$j('input[name=message]').val(this.message);
        },
        updateAmount:function(){
        	$j('input[name=Ds_Merchant_Amount]').val(this.amount);
        },
        calcFraisPort:function(){
        	this.fraisPort = parseInt(this.tarifsFraisPort[this.paysLivraison]);
        },
        setMessageInfos:function(totalCommande, order,code, currency, clave){
        	this.setTotalCommande(totalCommande);
        	this.setOrder(order);
        	this.setCode(code);
        	this.setCurrency(currency);
        	this.setClave(clave);
        },
        setTotalProduits:function(totalProduits){
        	this.totalProduits = parseInt(totalProduits);
        },
        setTotalCommande:function(totalCommande){
        	this.totalCommande = totalCommande;
        	this.setAmount();
        },
        setAmount:function(){
        	this.amount= this.totalCommande*100;
        },
        setOrder:function(order){
        	this.order = order;
        },
        setCode:function(code){
        	this.code = code;
        },
        setCurrency:function(currency){
        	this.currency = currency;
        },
        setClave:function(clave){
        	this.clave = clave;
        },
        calcTotalCommande:function(){
        	this.setTotalCommande(parseInt(this.totalProduits) + parseInt(this.fraisPort));
        },
        resetPaysLivraison:function(){
        	$j('select[name=paysLivraison] > option:eq(0)').attr('selected','selected');
        },
        extractItemFromCookie:function(){
        	 if (document.cookie !='') {   //....search cookie, extract the list of items
       	      Cookies = document.cookie.split('; ');
       	      for (i=0; i<Cookies.length; i++) {
       	            if ('ckItem' == Cookies[i].split('=')[0]) {
       	               strCookie = Cookies[i].split('=')[1];
       	               strCookie = unescape(strCookie);
       				}
       		  }
       	  }
       	  var qitems = Array();
       	  if (strCookie !='') {   //...........extract each item
       	      //var msg='Votre Panier :\n\n';
       		  var content = '';
       	      items = strCookie.split(':::'); 
       	      dataCount = items.length;	  
       		  
       		  qitems = new Array();
       		  
       		  for (i=0; i<litems.length; i++){
       			  qitems[i] = 0;
       		  }
       	      for (i=1; i<items.length; i++) {
       	            k = parseInt(items[i]);
       				qitems[k] = qitems[k]+1;
       	            tot = parseFloat(tot + lprices[k]);
       	            //msg += i + '  -' + litems[k] + '...'+ lprices[k] + ' Euros\n';		
       			}
       	      this.setTotalProduits(tot);
       	      this.calcTotalCommande();
       	   }
       	  return qitems;
        },
        list_items:function() { //-------------------------------
        	var qitems = this.extractItemFromCookie();
        	var tableProduits = $j("<table style='border:1px #FFFFFF solid;width:100%;text-align:center;' cellspacing='1'>" +
        		"<tr style='white-space:nowrap;background-color:white;color:#0061A5;'>" +
        	    "<td>"+this.T.getT('PRODUITS')+"</td><td>"+this.T.getT('QTE')+"</td>"+
        	    "</tr>" +
        	    "</table>");
        	var content = "";
        	for (i=0; i<qitems.length; i++){
        		if (qitems[i] != 0){
        			tableProduits.append("<tr><td>"+litems[i]+"</td><td>"+qitems[i]+"</td></tr>");
        		}
        	}
        	$j('#tabPanier').append(tableProduits);
        	this.listTotal();
        },
        removelistTotal:function(){
        	$j('#tabPanier tr.totalCommande').remove();
        },
        listTotal:function(){
        	var a = $j("<tr class='totalCommande'><td>"+this.T.getT('TOTAL_PRODUITS')+" <span class='totalCommande'>"+this.totalProduits+"</span> "+this.T.getT('EUROS')+"</td><td></td></tr>");
        	var b = $j("<tr class='totalCommande'><td>"+this.T.getT('FRAIS_PORT')+" <span class='totalCommande'>"+this.fraisPort+"</span> "+this.T.getT('EUROS')+"</td><td></td></tr>");
        	var c = $j("<tr class='totalCommande'><td>"+this.T.getT('TOTAL_COMMANDE')+" <span class='totalCommande'>"+this.totalCommande+"</span> "+this.T.getT('EUROS')+"</td><td></td></tr>");
        	this.removelistTotal();
        	$j('#tabPanier > table').append(a,b,c);
        },
        check:function(paiement){
		/*	Ajouter dans cette fonction l'ensemble des controles à faires sur les champs de formulaires avant soumission du formulaire.	*/
        if (paiement == ""){
        	return false;
        }
		var compra=true;
		var message='';
				
		if (isEmpty(document.compra.Nom.value))
		{
			message+='\n  '+this.T.getT('MISSING_NAME');
			compra=false;
		} 
		else if (isEmpty(document.compra.Prenom.value))
		{
			message+='\n '+this.T.getT('MISSING_PRENOM');
			compra=false;
		}		
		else if (isEmpty(document.compra.Adresse.value))
		{
			message+='\n '+this.T.getT('MISSING_ADDRESS');
			compra=false;
		}		
		else if (isEmpty(document.compra.Ville.value))
		{
			message+='\n '+this.T.getT('MISSING_TOWN');
			compra=false;
		}		
		else if (isEmpty(document.compra.CP.value))
		{
			message+='\n '+this.T.getT('MISSING_ZIPCODE');
			compra=false;
		}		
		else if (isEmpty(document.compra.Pays.value))
		{
			message+='\n '+this.T.getT('MISSING_COUNTRY');
			compra=false;
		}		
		else if (isEmpty(document.compra.Tel.value))
		{
			message+='\n '+this.T.getT('MISSING_TEL');
			compra=false;
		}		
		else if (isNotEmailAdress(document.compra.Email.value))
		{
			message+='\n  '+this.T.getT('INVALID_MAIL');
			compra=false;
		}
		else if (this.paysLivraison == "na")
		{
			message+='\n  '+this.T.getT('INVALID_SHIPPING_COUNTRY');
			compra=false;
		}
		
		
		if (message!='') {
			alert(message);
			return false;
			}
		var order = $('order').value;
		var email = document.compra.Email.value;
		var nom = document.compra.Nom.value;
		var prenom = document.compra.Prenom.value;
		var adresse = document.compra.Adresse.value;
		var cp = document.compra.CP.value;
		var ville = document.compra.Ville.value;
		var telephone = document.compra.Tel.value;
		var fax = document.compra.Fax.value;
		var pays = document.compra.Pays.value;
		var amount = $('amount').value/100;
				
		var lstItems = decrit_commande();
		// those two next functions must stay in this order
		this.calcFraisPort();
		var cart = this.cart_to_Json();
		switch (paiement){
		case'PAYPAL':
			var folderPays = {'fr':"francais", 'es':'espagnol', 'en':'anglais'};
			var paypalLC = {'fr':"FR", 'es':'ES', 'en':'GB'};
			jQuery('form[name=PAYPAL]').html(''); 
			//jQuery('form[name=PAYPAL]').append('<input type="hidden" name="business" value="aqua_1307387496_biz@e64.net">');
			jQuery('form[name=PAYPAL]').append('<input type="hidden" name="business" value="info@aquamusique.com">');
			jQuery('form[name=PAYPAL]').append('<input type="hidden" name="cmd" value="_cart"> ');
			jQuery('form[name=PAYPAL]').append('<input type="hidden" name="upload" value="1"> ');
			jQuery('form[name=PAYPAL]').append('<input type="hidden" name="lc" value="'+paypalLC[this.lang]+'"> ');
			jQuery('form[name=PAYPAL]').append('<input type="hidden" name="custom" value="'+order+'"> ');
			jQuery('form[name=PAYPAL]').append('<input type="hidden" name="currency_code" value="EUR">');
			jQuery('form[name=PAYPAL]').append('<input type="hidden" name="return" value="http://www.aquamusique.com/'+folderPays[this.lang]+'/tarifs/urlok.php">');
			jQuery('form[name=PAYPAL]').append('<input type="hidden" name="cancel_return" value="http://www.aquamusique.com/'+folderPays[this.lang]+'/tarifs/urlko.php">');
			
			// add items to form
			
			var qitems = this.extractItemFromCookie();
			var n = 1;
        	for (i=0; i<qitems.length; i++){
        		if (qitems[i] != 0){
        			jQuery('form[name=PAYPAL]').append('<input type="hidden" name="item_name_'+n+'" value="'+litems[i]+'"><input type="hidden" name="amount_'+n+'" value="'+(qitems[i]*lprices[i])+'.00">');
        			n = n+1;
        		}
        	}
        	
        	// add shipping tax
        	if (this.fraisPort > 0){
        		jQuery('form[name=PAYPAL]').append('<input type="hidden" name="item_name_'+n+'" value="'+this.T.getT('SHIPPING_TAX')+'"><input type="hidden" name="amount_'+n+'" value="'+this.fraisPort+'.00">');	
        	}
        	
        	
			break;
		case'CAIXA':
			var poststr = "contenuMail="+ order+"&idCommande="+ order+"&email="+ email+"&nom="+ nom+"&prenom="
			+ prenom+"&adresse="+ adresse+"&cp="+ cp+"&ville="+ ville+"&telephone="+ telephone+"&fax="+ fax+"&pays="+ pays+"&commande="+lstItems+"&amount="+ amount;
			calc(poststr);
			break;
		}
		this.saveOrder({'order':order, 'email':email, 'nom':nom, 'prenom':prenom, 'adresse':adresse, 'cp':cp, 'ville':ville, 'telephone':telephone, 'fax':fax, 'pays':pays, 'amount':amount, 'cart':cart});
		return false;
		
		return compra;
        },
        cart_to_Json : function(){
        	var qitems = this.extractItemFromCookie();
			var n = 1;
			var orderJson = {};
        	for (i=0; i<qitems.length; i++){
        		if (qitems[i] != 0){
        			orderJson[n] = {'item':litems[i],'qte': qitems[i], 'price':(qitems[i]*lprices[i])};
        			n = n+1;
        		}
        	}
        	if (this.fraisPort > 0){
        		orderJson[n] = {'item':'frais de port','qte': 1, 'price':this.fraisPort};	
        	}else{
        		orderJson[n] = {'item':'frais de port','qte': 0, 'price':this.fraisPort};
        	}
        	return orderJson;
        },
        saveOrder:function(orderJson){
        	jQuery.post('../../../includes/ajax.php', {'action':'saveOrder', 'order':orderJson}, function(data){
        		jQuery('form[name=PAYPAL]').submit();
    			return false;
        	});
        }
    };
    
    /**
	* constructeur utils
	*/
	AQ.translation= function(language) {
		this.language = language;
    };
	
    /**
	* variables et méthodes publiques propres à chaque instance
	* $amount.$order.$code.$currency.$clave;
	*/
    AQ.translation.prototype = {
    		language:'',
    		fr:{"MISSING_NAME":"Nom est un champ obligatoire !",
    			"MISSING_PRENOM":"Prenom est un champ obligatoire !",
    			"MISSING_ADDRESS":"Adresse est un champ obligatoire !",
    			"MISSING_TOWN":"Ville est un champ obligatoire !",
    			"MISSING_ZIPCODE":"Code Postal est un champ obligatoire !",
    			"MISSING_COUNTRY":"Pays est un champ obligatoire !",
    			"MISSING_TEL":"Tel est un champ obligatoire !",
    			"INVALID_MAIL":"Email doit etre une adresse email valide !",
    			"INVALID_SHIPPING_COUNTRY":"Veuillez choisr un pays de livraison.",
    			"TOTAL_PRODUITS":"TOTAL PRODUITS",
    			"EUROS":"Euros",
    			"FRAIS_PORT":"Frais de port",
    			"TOTAL_COMMANDE":"TOTAL COMMANDE",
    			"PRODUITS":"PRODUITS",
    			"QTE":"QTE",
    			"SHIPPING_TAX":"Frais de livraison"},
    		es:{"MISSING_NAME":"Los datos marcados con asterisco (*) son obligatorios !",
        		"MISSING_PRENOM":"Los datos marcados con asterisco (*) son obligatorios !",
        		"MISSING_ADDRESS":"Los datos marcados con asterisco (*) son obligatorios !",
        		"MISSING_TOWN":"Los datos marcados con asterisco (*) son obligatorios !",
        		"MISSING_ZIPCODE":"Los datos marcados con asterisco (*) son obligatorios !",
        		"MISSING_COUNTRY":"Los datos marcados con asterisco (*) son obligatorios !",
        		"MISSING_TEL":"Los datos marcados con asterisco (*) son obligatorios !",
        		"INVALID_MAIL":"Los datos marcados con asterisco (*) son obligatorios !",
        		"INVALID_SHIPPING_COUNTRY":"Los datos marcados con asterisco (*) son obligatorios !",
        		"TOTAL_PRODUITS":"PRODUCTOS",
        		"EUROS":"Euros",
        		"FRAIS_PORT":"Frais de port",
        		"TOTAL_COMMANDE":"TOTAL PEDIDO",
        		"PRODUITS":"PRODUCTOS",
        		"QTE":"CNT.",
        		"SHIPPING_TAX":"Cargos de transporte"},
        	en:{"MISSING_NAME":"You must specify a Last Name !",
            	"MISSING_PRENOM":"You must specify a First Name !",
            	"MISSING_ADDRESS":"You must specify an Address !",
            	"MISSING_TOWN":"You must specify a City !",
            	"MISSING_ZIPCODE":"You must specify a Postal Code !",
            	"MISSING_COUNTRY":"You must specify a Country !",
            	"MISSING_TEL":"You must specify a Phone !",
            	"INVALID_MAIL":"You must specify a valid Email Address !",
            	"INVALID_SHIPPING_COUNTRY":"You must specify a shipping country !",
            	"TOTAL_PRODUITS":"PRODUCTS",
            	"EUROS":"Eur",
            	"FRAIS_PORT":"Frais de port",
            	"TOTAL_COMMANDE":"TOTAL ORDER",
            	"PRODUITS":"PRODUCTS",
            	"QTE":"QTY",
            	"SHIPPING_TAX":"Shipping tax"},
    		setLanguage:function(language){
    			this.language = language;
    		},
    		getT:function(translation){
    			var t = this[this.language][translation];
    			return t;
    		}
    };
    
})();


