
// WRAP ARROW IMAGES INTO LINK POINTING TO TOP OF PAGE
    $(document).ready(function(){
        $("img[@src*='files/icones/fleche.png']").wrap('<a class="toHeader" href="#header"></a>');
    });

/*
 * HONET WEBSITE 
 * Cart management for CMS web site
 * Copyright (C) 2006 H.O.net - http://www.honet.be/
 *
 * For further information visit:
 * 		http://www.honet.be/
 * 
 * 
 * File Authors:
 * 		Pierre WAESELYNCK (pierre.w@honet.be)
*/

//TODO
//Shipping cost per product

//Gestion affichage du caddie

//Taille min en Y
var iMinY = 300;

//Taille min en X
var iMinX = 500;



//Paypal Informations

//Merchant Account Name
//var paypalAccount = "pierre_1210321236_biz@honet.be";
var paypalAccount = "info@laparenthese.be";

//Shipping (True/False)
var bShipping = false;

//shipping cost
var fShippingCost = 0;

//return Url
var strReturnUrl = "http://www.laparenthese.be/fr/ok/index.htm";
//return

//Continue Text
var strContinueText = "Revenir sur la parenthese";

//Cancel URL
var strCancelUrl = "http://www.laparenthese.be/fr/cancel/index.htm";

//Logo Url
//image_url L'URL Internet est l'image de 150 X50 pixels que vous souhaitez utiliser comme logo. 
var strLogoUrl = "http://www.laparenthese.be/js/hd-bg.gif";

//strGetPost
//only 2 possibilities GET or POST
var strGetPost = "POST";

//Note information mandatory in paypal forms values : 0 or 1
var strNote = "0"

//Note information include in paypal forms
var strListName = "Nom de votre liste"


/*
cpp_header_image
Place l’image en haut à gauche de la page de paiement. La taille
maximale de l’image est de 750 pixels en largeur et de 90 pixels
en hauteur et doit être encodée dans l’URL. PayPal vous
recommande de fournir une image stockée uniquement sur un
serveur sécurisé (https). Pour en savoir plus, reportez-vous à la
section « Conserver l’apparence de votre boutique sur les
pages de paiement PayPal ».
*/

/*var strURLcpp_header_image = "http://test.laparenthese.be/files/hd-bg.gif";*/
var strURLcpp_header_image = "https://www.e-junkie.com/sslpic/5643.ace92d95020b2451d121ea82774f1cc8.gif";

/*
cpp_headerback_color
Définit la couleur d’arrière-plan de l’en-tête de la page de
paiement.
La valeur correcte est un code couleur hexadécimal HTML de
six caractères en ASCII qui ne différencie pas les majuscules
des minuscules.
*/

var cpp_headerback_color = "FFFFFF"; 

/*
cpp_headerborder_color
Définit la couleur de bordure de l’en-tête de la page de
paiement. La bordure est un périmètre de 2 pixels autour
de l’espace d’en-tête, qui dispose d’une taille maximale de
750 pixels de large sur 90 pixels de haut.
La valeur correcte est un code couleur hexadécimal HTML de
six caractères en ASCII qui ne différencie pas les majuscules
des minuscules.
*/

var cpp_headerborder_color= "FFFFFF";




/*************** cookie Management *************************************************************/
// retrieve the cookie called #name
function Get_Cookie(name) { 
   var start = document.cookie.indexOf(name+"="); 
   var len = start+name.length+1; 
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
   if (start == -1) return null; 
   var end = document.cookie.indexOf(";",len); 
   if (end == -1) end = document.cookie.length; 
   return unescape(document.cookie.substring(len,end)); 
} 


/*************** Browser Detection *************************************************************/

var d, dom, ie, ie4, ie5x, moz, mac, win, lin, old, ie5mac, ie5xwin, op;

d = document;
n = navigator;
na = n.appVersion;
nua = n.userAgent;
win = ( na.indexOf( 'Win' ) != -1 );
mac = ( na.indexOf( 'Mac' ) != -1 );
lin = ( nua.indexOf( 'Linux' ) != -1 );

if ( !d.layers ){
	dom = ( d.getElementById );
	op = ( nua.indexOf( 'Opera' ) != -1 );
	konq = ( nua.indexOf( 'Konqueror' ) != -1 );
	saf = ( nua.indexOf( 'Safari' ) != -1 );
	moz = ( nua.indexOf( 'Gecko' ) != -1 && !saf && !konq);
	ie = ( d.all && !op );
	ie4 = ( ie && !dom );

	/*
	ie5x tests only for functionality. ( dom||ie5x ) would be default settings. 
	Opera will register true in this test if set to identify as IE 5
	*/

	ie5x = ( d.all && dom );
	ie5mac = ( mac && ie5x );
	ie5xwin = ( win && ie5x );
}

/*************** HONET Cart  *************************************************************/

// Cart Constructor
// Each article buy by the client is save in an array (call caddie)
// Product property : REF, INFO, QUANTITY,PRICE 
function HOnet_Cart()  {
this.caddie = new Array();
this.DeserializeCart("HOnetCart");
}

//delete the cart
function Delete_HOnet_Cart(){
delete MyCart;
MyCart = null;
}


// HOnet Cart Prototype : Valid
// Check if the cart exist and is not empty
HOnet_Cart.prototype.Valid = function() {
if ( this.caddie != null && this.caddie.length > 0 ) {
	return true;
	}
	else {
	return false;
	}
}

// HOnet Cart Prototype : Save
// if there something in the caddie save the cart in the cookie : HOnetCart
// else delete the HOnetCart cookie's
HOnet_Cart.prototype.Save = function() {
	szCart = this.SerializeCart();
	//alert (szCart);
	if ( szCart != null )
	{
		var myDate = new Date();
		myDate.setMonth(myDate.getMonth() + 6);
	    var cookieString = "HOnetCart=" +escape(szCart) + 
       ( (myDate) ? ";path=/; domain=www.laparenthese.be;expires=" + myDate.toGMTString() : "");
		document.cookie = cookieString; 	
	}
	else
	{
		var myDate = new Date();
		myDate.setMonth(myDate.getMonth() - 6);
	    var cookieString = "HOnetCart=" +escape("") + 
       ( (myDate) ? ";path=/; domain=www.laparenthese.be;expires=" + myDate.toGMTString() : "");
		document.cookie = cookieString; 
	}
	
}

// HOnet Cart Prototype : SerializeCart
// if there something in the caddie serialize the cart in a string
// Used separator is :
// -> |$| for separation of an article
// -> || for elements of an article
HOnet_Cart.prototype.SerializeCart = function() {
if ( this.caddie != null && this.caddie.length > 0 ) {
	szCart="";
	for (i=0;i<this.caddie.length;i++) {
		szCart += this.caddie[i][0]+"||";
		szCart += this.caddie[i][1]+"||";
		szCart += this.caddie[i][2]+"||";
		szCart += this.caddie[i][3]+"|$|";
	}
	return szCart;
	}
	else {
	return null;
	}
}


// HOnet Cart Prototype : DeserializeCart
// create the caddie and read cookie string to retrieve the cart content
// if there's something in the cart, deserialize it and set the article to the caddie
// -> |$| for separation of an article
// -> || for elements of an article
HOnet_Cart.prototype.DeserializeCart = function(CookieName) {
var iNbArticle=0;
var tempString="";
var serialization = Get_Cookie(CookieName);
this.caddie = new Array();
 if ( serialization != null && serialization.length > 0 ) 
	{
	var article=serialization.split("|$|");
	for (j=0;j<article.length;j++) 
		{
		tempString = article[j];
			if (tempString != null && tempString.length > 0)
			{
				var tab=tempString.split("||");
				if ( tab.length == 4 )
				{
					var tab_Art = new Array(tab[0],tab[1],tab[2],tab[3]);
					this.setInsert(tab_Art);
				}
			}
		}
	}
}


// HOnet Cart Prototype : getCaddie
// create the caddie output HTML the cart is represent by a html table
HOnet_Cart.prototype.getCaddie = function() {
	if ( this.caddie.length == 0 ) {

	return "<div id='vide'><p>Votre panier est vide !</p></div>";
	}
	else {
		var totalamount = 0;
		var tab_html="";
		
        tab_html += "<div id='achat'><table id='TB_HonetCart'><tr id='categorie'><td>R&eacute;f&eacute;rence</td><td>Description</td><td>Quantit&eacute;</td><td>Prix</td><td>Montant</td><td>&nbsp;</td></tr>";
		for (i=0;i<this.caddie.length;i++) {
		tab_html += "<tr>";
		tab_html += "<td>" + this.caddie[i][0] + "</td>";
		tab_html += "<td>" + this.caddie[i][1] + "</td>";
		tab_html += "<td><INPUT type='text' ID='txtQ'"+this.caddie[i][0]+" value='"+this.caddie[i][2]+"'></td>";
		tab_html += "<td>" + parseFloat((this.caddie[i][3])).toFixed(2).replace(".",",")  + "</td>";
		tab_html += "<td>" + (this.caddie[i][2]*this.caddie[i][3]).toFixed(2).replace(".",",") + "</td>";
		totalamount += this.caddie[i][2]*this.caddie[i][3];
		tab_html += "<td><INPUT type='button' value='Supprimer' ID='UpdateCart' onclick='deletefromcart(\""+this.caddie[i][0]+"\")'></td>";
		tab_html +="</tr>";
		}
		tab_html += "<tr id='total'><td colspan='3'><INPUT type='button' value='Recalculer' ID='UpdateCart' onclick='UpdateCart()'></td><td>Total</td><td>";
		tab_html +=totalamount.toFixed(2).replace(".",",");
		tab_html +=" &euro;</td><td>&nbsp;</td></tr></table></div>";
		
		return tab_html;
	}
}



// HOnet Cart Prototype : setInsert
// add the product in the caddie an new product is a new array
HOnet_Cart.prototype.setInsert = function(value) {
	this.caddie[this.caddie.length] = value;
}

// HOnet Cart Prototype : search
// search the article's reference in the cart an return the index
HOnet_Cart.prototype.search = function(ref) {
var result = null;
var tab = this.caddie;
for(i=0;i<tab.length;i++) {
	//alert("search for loop");
	if( tab[i][0] == ref ) {
	result = i;
	break;
	}
}
return result;
}


// HOnet Cart Prototype : Delete
// delete an article
HOnet_Cart.prototype.Delete = function(index) {
	if ( this.caddie.length > 0 ) {
		this.caddie = del_index(this.caddie,index);
	}
}


/*************** Using  Cart  *************************************************************/

var MyCart = new HOnet_Cart();		


// Buy Product is an external function to encapsulte all step to add a product in the cart
function buy_product(ref,info,quantity,price){

quantity = parseInt(quantity);
price = parseFloat(price);

// create cart if necessary
if (MyCart == null) 
{
	MyCart = new HOnet_Cart();
}
MyCart.DeserializeCart("HOnetCart");

var tab_int = new Array(ref,info,quantity,price);

//check if the ref isn't duplicate
var ind =  MyCart.search(ref);


// delete it if already exist
	if ( ind != null ) {
	   //MyCart.Delete(ind);
	   MyCart.caddie[ind][2] = parseInt(MyCart.caddie[ind][2])+1;
	}
	else
	{
        MyCart.setInsert(tab_int);
    }

//add article


MyCart.Save();
//alert("L'article est dans le panier.");
windowCenter('viewcartcontent');


}


// showCart is an external function to encapsulte all step to show the cart
function showCart()
{
    windowCenter('viewcartcontent');
}

// deletefromcart is an external function to encapsulte all step to delete an item from the cart
// the function can be used only in a child window
function deletefromcart(ref)
{
	var ind =  MyCart.search(ref);
	
	if ( ind != null ) {
		MyCart.Delete(ind);
		MyCart.Save();
		
		// Update cart window HTML content
		windowCenter("viewcartcontent");

	}
}

function PaypalHTML()
{
	var paypalcontent="";
	
	
	//test purpose only
	
	//paypalcontent +="<form action='https://www.sandbox.paypal.com/cgi-bin/webscr' method='post'>";

	paypalcontent +="<form action='https://www.paypal.com/cgi-bin/webscr' method='post'>";
	paypalcontent +="<input type='hidden' name='cmd' value='_cart'/>";
	paypalcontent +="<input type='hidden' name='upload' value='1'/>";
	
	

	//shipping
	if ( !bShipping )
		{paypalcontent +="<input type='hidden' name='no_shipping' value='1'>";}
	else
		{paypalcontent +="<input type='hidden' name='shipping' value='"+fShippingCost+"'>";}

	//return url
	paypalcontent +="<input type='hidden' name='return' value='"+strReturnUrl+"'>";
	
	//Note for the name of the list
	paypalcontent +="<input type='hidden' name='no_note' value='"+strNote+"'>";
	paypalcontent +="<input type='hidden' name='cn' value='"+strListName+"'>";
		
	//Cancel URL
	paypalcontent +="<input type='hidden' name='cancel_return' value='"+strCancelUrl+"'>";

	//strURLcpp_header_image
	paypalcontent +="<input type='hidden' name='cpp_header_image' value='"+strURLcpp_header_image+"'>";

	//cpp_headerback_color
	paypalcontent +="<input type='hidden' name='cpp_headerback_color' value='"+cpp_headerback_color+"'>";

	//cpp_headerback_color
	paypalcontent +="<input type='hidden' name='cpp_headerborder_color' value='"+cpp_headerborder_color+"'>";
	
	
	//Continue Text
	paypalcontent +="<input type='hidden' name='cbt' value='"+strContinueText+"'>";
	
	//strLogoUrl
	paypalcontent +="<input type='hidden' name='image_url' value='"+strLogoUrl+"'>";
	
	//strGetPost
	paypalcontent +="<input type='hidden' name='rm' value='"+strGetPost+"'>";
	
	paypalcontent +="<input type='hidden' name='business' value='"+paypalAccount+"'/>";
	for (i=0;i<MyCart.caddie.length;i++) {
		paypalcontent +="<input type='hidden' name='item_name_"+(i+1)+"' value='" + MyCart.caddie[i][1]+ " | " + MyCart.caddie[i][0]+ "'/>";
		paypalcontent +="<input type='hidden' name='quantity_"+(i+1)+"' value='"+(MyCart.caddie[i][2])+"'/>";
		paypalcontent +="<input type='hidden' name='amount_"+(i+1)+"' value='"+(MyCart.caddie[i][3])+"'/>";
	}
	paypalcontent +="<input type='hidden' name='currency_code' value='EUR'/>";
	paypalcontent +="<input type='submit' value='Payer'/>";
	paypalcontent +="</form>";
	return paypalcontent;
}

function ShowPaypal()
{
	var myDIV = document.getElementById('DIV_HonetPayPal');	
	
	if ( null != myDIV )
	{
		myDIV.innerHTML = PaypalHTML();
	}
}

//update caddie content if there is a modification from a child
function UpdateCartArray()
{
	MyCart.DeserializeCart("HOnetCart");
}


//external function to update cart content quantity an total cost in the cart viewer window
function UpdateCart()
{
	//var tab_int = new Array(ref,info,quantity,price);
	//alert ("UpdateCart")
	var mytabletable = document.getElementById('TB_HonetCart');
	var nbRows = mytabletable.rows.length;
	//alert (nbRows);
	var	myrow;var	mycel; var ref; var quantity; ;var ind;
	var chercheind;
	var limit = nbRows-1;
	var TotalAmount=0;
	
	
	var ItemQuantity; 
	
	
	for (chercheind=1;chercheind<limit;chercheind++) 
	{
	
	
	myrow = mytabletable.getElementsByTagName("tr")[chercheind];
	ref = myrow.getElementsByTagName("td")[0].childNodes[0].data;
	quantity = myrow.getElementsByTagName("td")[2].childNodes[0].value;
	ind =  MyCart.search(ref);
	
	//Update Paypal quantity
	ItemQuantity = document.getElementById('quantity_'+chercheind);
	if (null != ItemQuantity)
	{
		ItemQuantity.value = quantity; 
	}
	
	TotalAmount += MyCart.caddie[ind][3]*quantity;
	
		if ( ind != null ) {
			if ( quantity != MyCart.caddie[ind][2] ) 
			{
				MyCart.caddie[i][2] = quantity;
				myrow.getElementsByTagName("td")[4].childNodes[0].data = MyCart.caddie[ind][3]*quantity;
				MyCart.Save();
				MyCart.DeserializeCart("HOnetCart");
				
			}
		}
	}
	
	//update Total
	myrow = mytabletable.getElementsByTagName("tr")[limit];
	mycell = myrow.cells;
	mycell[2].innerHTML = TotalAmount + " &euro;"
	
}


//Array helper function
function del_index(tab,indice) {
	var longueur = tab.length;
	if (indice < 0 || indice >= longueur) {
		alert ("problème avec le choix des arguments...");
		return tab;
	}
	else {
		var result;
		var bool = false;
		//traitement si début ou fin tableau
			switch(indice) {
				case 0:
				if ( longueur == 1 )
				{
					tab = new Array();
				}
				else
				{
					tab.shift();
				}
				break;
				case longueur-1:
				tab.pop();
				break;
				default:
				bool = true;
				break;
			}
		// traitement du tableau autre cas de figure
			if(bool) {
				var tab2 = tab.slice(indice+1,longueur);
				var tab1 = tab.slice(0,indice);
				result = tab1.concat(tab2);
			} else {
				result = tab;
			}
		return result;
	}
}


//Aurore JavaScript gestion de div au centre de la page
function returnSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  var result = new Array(myWidth,myHeight);
  return result;
}



function hiddenelement(myId){
    if ( null != myId  ) 
    {
        
	   document.getElementById(myId).style.display="none";
	}
}

function windowCenter(myId) {
       
        var myDiv = document.getElementById(myId);
        var myPage = document.getElementById("content");
    
        myDiv.style.position = "absolute";
        myDiv.style.display="block";
       
        myDiv.innerHTML = MyCart.getCaddie() +"<button type='button' onclick='JavaScript:hiddenelement(\""+myId+"\")' > Continuer mes achats </button>"+ PaypalHTML() ;
        var NVATop = parseInt(document.documentElement.scrollTop) + (returnSize()[1] - myDiv.offsetHeight) / 2 - myPage.offsetTop;
        var NVALeft = parseInt(document.documentElement.scrollLeft) +(returnSize()[0] - myDiv.offsetWidth) / 2 - myPage.offsetLeft;
        
        myDiv.style.top = NVATop + 'px';
	    myDiv.style.left = NVALeft +'px';
   
	}

function windowCenterIE(myId) {

if ( null != myId  ) 
    {

        result = returnSize();
       
       var myDiv = document.getElementById(myId);
       
        myDiv.parentElement.removeChild(myDiv);
        
       var nouveauDIV = document.createElement("DIV");
      
        nouveauDIV.id = myId; 

        document.body.appendChild(nouveauDIV);       
        
        
        nouveauDIV.style.position = "absolute";
        nouveauDIV.style.display="block";

        nouveauDIV.innerHTML = MyCart.getCaddie() +"<br /> <button type='button' onclick='JavaScript:hiddenelement(\""+myId+"\")' > Continuer mes achats </button>"+ PaypalHTML() ;
       

        var NVATop = parseInt((parseInt(document.documentElement.scrollTop) + (returnSize()[1] - nouveauDIV.offsetHeight) / 2));
        var NVALeft = parseInt((parseInt(document.documentElement.scrollLeft) +(returnSize()[0] - nouveauDIV.offsetWidth) / 2));
        
        nouveauDIV.style.top = NVATop + ' px';
	    nouveauDIV.style.left = NVALeft +' px';
	   
	}
}
