//	| ########################################################################## |
//	|-------------- powered by Djingle -------- 2006 --------------------------- |
//	| ########################################################################## |

//	---| class CART
//	---| author: Régis CAZANAVE (Djingle)
//	---| date: 2006-08-21
//	---| version: V1.0

function CART(mode)
{
	this.mode=mode;
	
	this.total_euros_in_cart=0;
	
	this.showCartTimer = null;
	
	//internal functions -------------------------------------
	this._CallRemoteFunctions = function(todo, args) {
		
		var the_response;
		var the_result;
		var the_error;
		var the_error_a=new Array;
		//build data array
		var data = new Array;
		if (args) data=args;
		
		data["todo"]=todo;
		data["cart_name"]="cart";
		
		if (debug_mode) alert("envoi à la page distante avec data="+_Array2String(data));

		//this._DispLoadingMsg();

		the_response=CallAJAX("POST", server_url+"vod/do_cart.php", data, false);

		if(the_response.readyState == 4)
		{
			the_result=the_response.responseText;
			if (debug_mode) alert("retour de cette page = "+the_result);
			the_error_a=the_result.split("|");

			return the_error_a;
		}
	};

	this._GetCartArray = function () {
	
		//this function buids an array from the cookie (use AJAX method)
		var tmp_cart_a=new Array();

		var tmp=this._CallRemoteFunctions("get_cart_js_array", "");
		if (tmp[0]=="ok")
		{
			var cart_js_array_str=tmp[1];//is an array string
			eval(cart_js_array_str);
			this.cart_array=cart_content;//is an array

			this.total_nb_in_cart=this.cart_array.length;
			this.total_euros_in_cart=0;
			var coupons_nb=0;
			
			for (i=0;i<this.total_nb_in_cart;i++)
			{
				//if discount on product, apply reduction
				if (this.cart_array[i]["product_type"]=="coupon")
				{
					var reduction;
					var discounted_price;
					
					//todo: améliorer car on prend ici le produit i+1 pour appliquer la reduc
					
					if (this.cart_array[(i-1)])
					{
						var reduction_str="discounted_price=" +this.cart_array[i]["discount_formula"].replace("P", this.cart_array[(i-1)]["product_price"])+";";
						
						eval(reduction_str);//sets discounted_price
						reduction=this.cart_array[(i-1)]["product_price"]-discounted_price;
					
						this.total_euros_in_cart=this.total_euros_in_cart-reduction;
						coupons_nb++;
					}
				}
				else
					this.total_euros_in_cart=this.total_euros_in_cart-(-this.cart_array[i]["product_price"]);
			}
			this.total_euros_in_cart=Math.round(this.total_euros_in_cart*100)/100;
			this.total_nb_in_cart=this.total_nb_in_cart-coupons_nb;
			return true;
		}
	};
	
	this.CheckCookieMode = function () {
	
		//this._DispLoadingMsg("Tests cookies en cours...");
		var tmp=getCookie( test_cookie_name );
		
		if (tmp==1) return true;
		else return false;
	};
	
	//action functions --------------------------------------------
	this.AddtoCart = function (p_id, purchase_formula, product_price) {
	
		var ajaxdata=new Array;
		
		if (!p_id) p_id="0";
		
		//alert(p_id);
		
		if (p_id.toString().indexOf("J_")!=-1)
		{
			//it s a jacket
			ajaxdata["product_type"]="jacket";
			ajaxdata["product_id"]=p_id.substring(2);
		}
		else 
		{
			ajaxdata["product_id"]=p_id;
			ajaxdata["product_type"]="main";
		}
		
		ajaxdata["purchase_formula"]=purchase_formula;
		ajaxdata["product_price"]=product_price;
		//ajaxdata["product_price_idstr"]=product_price_idstr;

		this._AddtoCart(ajaxdata);
	};
	
	this._AddtoCart = function (item_params) {
	
		var do_close_cart=0;
		if (this.mode=="anchor")
		{
			do_close_cart=1;
			this.SwitchToFullMode();
		}
		
		var tmp=this._CallRemoteFunctions("add_to_cart", item_params);
		if (tmp[0]=="ok")
		{
			if (debug_mode) alert("ajout au panier successfull, je vais faire "+tmp[1]);
			eval(tmp[1]+";");
			if (do_close_cart)
			{
				this.showCartTimer = setTimeout( "my_cart.SwitchToAnchorMode();clearTimeout(my_cart.showCartTimer);", 2200 );
			}
		}
		else
			alert("erreur ! "+tmp[1]);
	};
	
	this.EmptyCart = function () {
		return this._CallRemoteFunctions("empty_cart");
	};

	this.RemoveFromCart = function (p_ix) {
	
		var ajaxdata=new Array;
		ajaxdata["product_ix"]=p_ix;
		
		var tmp=this._CallRemoteFunctions("remove_from_cart", ajaxdata);
		if (tmp[0]=="ok")
		{
			if (debug_mode) alert("remove du panier successfull, je vais faire "+tmp[1]);
			eval(tmp[1]+";");
			//this._AnimateTrash();
		}
		else
			alert("erreur ! "+tmp[1]);
	};
	
	this.ChangeInCart = function (p_ix, what) {
		var new_value=eval("document.c_cart."+what+"_"+p_ix).value;
		
		var ajaxdata=new Array;
		ajaxdata["product_ix"]=p_ix;
		ajaxdata["what"]=what;
		ajaxdata["value"]=new_value;

		var tmp=this._CallRemoteFunctions("change_in_cart", ajaxdata);
		if (tmp[0]=="ok")
		{
			if (debug_mode) alert("modif ds le panier successfull, je vais faire "+tmp[1]);
			eval(tmp[1]+";");
		}
		else
			alert("erreur ! "+tmp[1]);
	};
	
	//interface functions -------------------------------------------
	this._AnimateTrash = function () {
		if (document.getElementById("trash")) 
			document.getElementById("trash").src=skin_base+"images/FR/cart/trash_a.gif";
	};
	
	this._DispLoadingMsg = function() {
	
		var to_return="<img src='"+skin_base+"loading.gif' align=absmiddle> Loading...";
		this.BuildCart(to_return);
	};
	
	this._CalculateCartNb = function () {
			
		if (this.total_nb_in_cart==0)
			var total_cart="<font class=none_style>Aucun produit dans votre panier</font>";
		else 
		{
			var total_cart="Mon panier contient<br><b>" +this.total_nb_in_cart+" article";
			if (this.total_nb_in_cart>1) 
				total_cart=total_cart+"s";
			if (this.total_nb_in_cart>0)
			{
				total_cart=total_cart+"</b>&nbsp;&nbsp;soit <font color=#D04C47><b>"+this.total_euros_in_cart+"&euro;</b></font>";
			}
		}
		return total_cart;
	};
	
	this._DisplayPurchaseFormula = function (p_ix) {
	
		var product_carac=this.cart_array[p_ix];
		
		var tr="<select name='purchase_formula_"+p_ix+"' class=selectfield onchange='my_cart.ChangeInCart("+p_ix+",\"purchase_formula\");'>";
		for (f=0;f<product_prices.length;f++)
		{
			tr=tr+"<option value='"+ product_prices[f]["price_formula"] +"'";
			if (product_carac["purchase_formula"]==product_prices[f]["price_formula"])
				tr=tr+" selected";
			
			tr=tr+">"+ product_prices[f]["label"] +"</option>";
		}
		tr=tr+"</select>";

		return tr;
	};
	
	this._DisplayProductVersion = function (p_ix) {
	
		//var product_carac=this.cart_array[p_ix];
		var tr="";
		return tr;
	};
	
	this._DisplayDistributionType = function (p_ix) {
		
		var product_carac=this.cart_array[p_ix];
		var tr="";
		if (product_carac["distribution_type"]=="_streaming")
			tr=tr+"disponibilité immédiate";
		else 	tr=tr+"disponibilité : 30 min.";

		tr=tr+"<br>";
		if (product_carac["distribution_type"]=="_djingle" || product_carac["distribution_type"]=="_remote")
			tr=tr+product_carac["device"];
	
		return tr;
	};
	
	this._GetProductProfile = function (p_id) {

		var the_response;
		var the_result;
		var the_error;
		var the_error_a=new Array;
		if (!p_id) p_id="0";
		
		//build data array
		var data = new Array;
		data["todo"]="get_js_product_profile";
		data["product_id"]=p_id;

		if (debug_mode) alert("envoi à la page distante avec data="+_Array2String(data));

		the_response=CallAJAX("POST", server_url+"catalog/do.php", data, false);
	
		if(the_response.readyState == 4)
		{
			the_result=the_response.responseText;
			//alert(the_result);
			the_error_a=the_result.split("|");
	
			if (the_error_a[0]=="ok")
			{
				var cart_js_array_str=the_error_a[1];//is an array string
				eval(cart_js_array_str);
	
				return product_array;//product JS array
			}
			else return false;
			
			//todo: améliorer
		}
	};
	
	this.ReturnItem = function(p_ix) {
			
		if (!p_ix) p_ix="0";
		
		var bgclass=((p_ix%2==0)?"bg_altern_line":"");

		var product_carac=this.cart_array[p_ix];

		var product_data=this._GetProductProfile(product_carac["product_id"]);

		var the_product="<table border=0 cellpadding=2 "+((p_ix%2==0)?" class='bg_altern_line'":"")+" cellspacing=0 width=100% onMouseover='ChangeClass("+p_ix+", \"bg_sel_line\", \"ProductTable\");' onMouseout='ChangeClass("+p_ix+", \""+bgclass+"\",\"ProductTable\");' id='ProductTable_"+p_ix+"'>";

		/*
		the_product=the_product+"<tr><td rowspan=2 width=5 valign=top><img src='"+server_url+"upload/product/"+product_carac["product_id"]+"/"+product_data["picto"]+"' border=0></td>";
		*/
		
		the_product=the_product+"<td colspan=3>";
		
		if (product_carac["product_type"]=="jacket")
			the_product=the_product+"<u>Jaquette</u> ";
			
		the_product=the_product+product_data["title"]+"</td></tr>";
      		
      		the_product=the_product+"<tr><td class='beige'><strong>";
      		
      		if (product_carac["product_type"]=="jacket")
      			the_product=the_product+"Acheter et Imprimer";
      		else the_product=the_product+"Acheter et Graver";
      		
      		//alert(product_data["title"]);
      		
      		the_product=the_product+"</strong></td><td>";
		
		//alert("hé avec "+this.cart_array[(p_ix-(-1))]["product_type"]);
		
		//check if the following is not a corresponding coupon
		if (this.cart_array[(p_ix-(-1))])
		{
			//alert("juju "+this.cart_array[(p_ix-(-1))]["product_type"]);
			if (this.cart_array[(p_ix-(-1))]["product_type"]=="coupon")
			{
				var discounted_price;
					
				var reduction_str="discounted_price=" +this.cart_array[(p_ix-(-1))]["discount_formula"].replace("P", product_carac["product_price"])+";";
					
				eval(reduction_str);//sets discounted_price
				var the_r_price=Math.round(discounted_price*100)/100;
				
				the_product=the_product+"<font class=item_price_disabled>"+(Math.round(product_carac["product_price"]*100)/100)+" &euro;</font><br><font class='red'><strong>"+the_r_price.toFixed(2)+" &euro;</strong></font>";

			}		
			else
			{
				var the_r_price=Math.round(product_carac["product_price"]*100)/100;
		
				the_product=the_product+"<font class='red'><strong>"+the_r_price.toFixed(2)+" &euro;</strong></font>";
			}
		}
		else
		{
			var the_r_price=Math.round(product_carac["product_price"]*100)/100;
		
			the_product=the_product+"<font class='red'><strong>"+the_r_price.toFixed(2)+" &euro;</strong></font>";
		}
		
		the_product=the_product+"</td><td><a href='javascript:my_cart.RemoveFromCart("+p_ix+")'><img src='"+skin_base+"icon_delete.gif' border=0/></a></td></tr>";
		
		the_product=the_product+"<tr><td colspan=3 class='trait'></td></tr></table>";
    
		/*
		//product version
		the_product=the_product+"<tr><td valign=top><table border=0 cellpadding=0 cellspacing=0 width=100%><tr><td valign=top width=20%>VERSION<br>"+ this._DisplayProductVersion(p_ix) + "</td>";
		
		//purchase formula
		the_product=the_product+"<td valign=top width=20%>COMMANDE<br><i>"+this._DisplayPurchaseFormula(p_ix)+"</i></td>";

		//distribution type
		the_product=the_product+"<td valign=top width=30%>" + this._DisplayDistributionType(p_ix) + "</td>";
		
		
		//product price
		//sets reduced price if there is a discount
		//todo: améliorer car on consisdère que le coupon est juste avant
		
		the_product=the_product+"<tr><td valign=top align=right>";
	
		the_product=the_product+"</td></tr></table></td></tr></table>";
		*/
		return the_product;
	};
	
	//useless for the moment: not in a layer
	this.WriteItem = function(p_ix) {
				
		if (!p_ix) p_ix="0";
		//var the_product_layer_dd=eval("dd.elements.CartProduct_"+p_ix);
		//var the_product_layer = new LAYER("CartProduct_"+a);

		//add this layer to Cart's children
		//dd.elements.CartDiv.addChild(the_product_layer_dd);
		//dd.elements.CartDiv.attachChild(the_product_layer_dd);
		//dd.elements.CartDiv.attachChild("CartProduct_"+p_ix); 

		CartDiv.WriteInto(this.ReturnItem(p_ix),1);
		//the_product_layer_dd.moveBy(10,(50+30*p_ix));
	};
	
	this.ReturnCart = function (specific_content) {
	
		if (this.mode=="anchor") 
		{
			this.ReturnCartAnchor(specific_content);
			return;
		}
		//else
		var to_return="<div class='CartDiv_top_full'>";
		
		if (!this.CheckCookieMode())
		{
			to_return=to_return+"<font class=warning>Vous devez activer vos cookies</font>";
		}
		else
		{
			if (specific_content)
			{
				to_return=to_return+specific_content;
			}
			else
			{
				this._GetCartArray();
				to_return=to_return + this._CalculateCartNb();
				
				to_return=to_return+"</div><div id='cartBarZoom'>";

				if (this.cart_array.length>0)
				{
					//build items
					to_return=to_return+"<form name='c_cart' method=POST><table width=100% cellpadding=0 cellspacing=0 border=0><tr><td><strong>R&eacute;capitulatif<br /><br /></strong></td></tr>";
					
					
					for (a=0;a<this.cart_array.length;a++)
					{
						//alert(a + " : " +this.cart_array[a]["product_type"]);
						if (this.cart_array[a]["product_type"]!="coupon")
							to_return=to_return+"<tr><td>"+this.ReturnItem(a)+"</td></tr>";
					}

					if (this.cart_array.length>0)
					{
						to_return+="<tr><td align=center><a href='"+server_url+"vod/";
						
						var test=getCookie( "test_config" );
								
						if (test=="Ok") 
							to_return+="validate.php";
						else
							to_return+="test_config.php?from=cart";
		
						to_return+="'><img src='"+skin_base+"images/FR/cart/bt_cartFinish.gif' border=0></a></td></tr>";
					}
					to_return=to_return+"</table></form>";
				}
				else to_return=to_return+"Panier vide.";
				
				/*
				to_return=to_return+"<td valign=top><br><br><center><img src='"+skin_base+"images/FR/cart/trash.gif' border=0 id='trash'></center></td></tr></table>";
				*/
			}
		}
		to_return=to_return+"</div><div class='CartDiv_bottom_full'><a href='javascript:my_cart.SwitchToAnchorMode()'><img src='"+skin_base+"transp.gif' width=200 height=20 border=0></a></div>";

		return to_return;
	};
	
	this.ReturnCartAnchor = function (specific_content) {
	
		var to_return="<div class='CartDiv_top_anchor'>";

		if (!this.CheckCookieMode())
		{
			to_return=to_return+"<font class=warning>Vous devez activer vos cookies</font>";
		}
		else
		{
			if (specific_content) to_return=to_return+specific_content;
			else 
			{
				
				this._GetCartArray();
				to_return=to_return + this._CalculateCartNb();
			}
		}
		to_return=to_return + "</div><div class='CartDiv_bottom_anchor'><a href='javascript:my_cart.SwitchToFullMode()'><img src='"+skin_base+"transp.gif' width=150 height=20 border=0></a></div>";
		
		return to_return;
	};

	this.SwitchToFullMode = function () {
	
		clearTimeout(my_cart.showCartTimer);
		this.mode="full";
		//hide
		//CartDiv.Hide();

		//resize
		CartDiv.ResizeAndMove(211, 150, CartDiv.initial_X, -1);

		//set content
		this.BuildCart();
		//CartDiv.WriteInto(this.ReturnCart());

		//show
		//dd.elements.CartDiv.maximizeZ();
		//dd.elements.CartDiv.setDraggable(false);
		//CartDiv.Show();
		
	};

	this.SwitchToAnchorMode = function () {
	
		this.mode="anchor";
		//hide
		//CartDiv.Hide();

		//resize
		CartDiv.ResizeAndMove(211, 20, CartDiv.initial_X, -1);
		
		//set content
		this.BuildCart();
		CartDiv.WriteInto(this.ReturnCartAnchor());

		//show
		//dd.elements.CartDiv.setZ(dd.elements.CartDiv.defz);
		//dd.elements.CartDiv.setDraggable(true);
		//CartDiv.Show();
	};
	
	this.BuildCart = function (specific_content) {
	
		//cart creation
		if (this.mode=="anchor")
		{
			CartDiv.WriteInto(this.ReturnCartAnchor(specific_content));
		}
		else
		{
			CartDiv.WriteInto(this.ReturnCart(specific_content));
		}
	};
	
	//construction ------------------------------------------
}