//- cart.List FUNCTIONS


/*
 *  Reguli de denumire in cart (cart.List):
 *	EDITBOX :  quantity_$cartitemid (INPUT)
 *	INDIVIDUAL_PRICE : price_$cartitemid ("xxx.xx CHF") (TD)
 * 	TOTAL_PRICE: totalprice_$cartitemid ("xxx.xx CHF") (B)
 */


function utf8_encode( s ){  return unescape( encodeURIComponent( s ) );}

function utf8_decode( s ){  return decodeURIComponent( escape( s ) );}


function CLAShowStatusForm(cartid,addressid){
	$("status_link_"+cartid+"_"+addressid).hide();
	$("status_form_"+cartid+"_"+addressid).show();
	$("status_form_"+cartid+"_"+addressid).setStyle({display:'inline'});
}

function CLAHideStatusForm(cartid,addressid){
	$("status_form_"+cartid+"_"+addressid).hide();
	$("status_link_"+cartid+"_"+addressid).show();
}

/**
*	Enables or disables the "Passer a la caisse" link in cart.List
*	Enables or disables the sc_delivery combo box
*   Called on document load, then on each modification
*/
function CLCheckValidity(){
	var url = "index.php?object=cart&method=ValidateCartList";
	new Ajax.Request(url, {
		  method: 'post'
		  ,onSuccess: function(transport){

				var s = transport.responseText;
				var data = eval('('+transport.responseText+')');
				var total = data.total;
				var whereto = data.whereto;
				var valid = data.valid;
				// $('nextlink')
				//console.log("PERRORS="+participants_errors);
				if(participants_errors>0){
					//console.log('A');
					$('nextlink').href = '#';
					$('nextlink').update("Passer � la caisse");
					$('nextlink').stopObserving('click');
					$('nextlink').observe('click',function(event){alert('xPlease solve the participants/stock overflow error(s) first!');});
				}else{
					//console.log('B');
					if(valid>0){
						//console.log('C');
						if(whereto=='continue'){
							//console.log('D');
							//console.log("has shipped="+data.has_shipped);
							CLSetValidCheckoutURL(data.has_shipped<=0?1:0);
							$('nextlink').update("Passer � la caisse");
							$('nextlink').stopObserving('click');
						}
						if(whereto=='finish'){
							//console.log('E');
							$('nextlink').href = ROOT_WWW + 'index.php?object=cart&method=CheckoutOnZero';
							$('nextlink').update("Compl�ter sa commande");
							$('nextlink').stopObserving('click');
						}
						$('nextlink').show();
					}else{
						//console.log('F');
						$('nextlink').href = '#';
						$('nextlink').update("Passer � la caisse");
						$('nextlink').stopObserving('click');
						if(valid==-1){
							//console.log('G');
							$('nextlink').observe('click',function(event){alert('Vous ne pouvez pas valider une commande avec un solde n�gatif!');});
						}
						if(valid==-2){
							//console.log('H');
							$('nextlink').observe('click',function(event){alert('Votre panier est vide!');});
						}
					}
				}

				// - the delivery mode/type selector (simple delivery / multiple delivery
				if(data.has_shipped>0){
					//$('sm_type').show();
				}else{
					//$('sm_type').hide();
				}

		}
	});
}

function CLSetValidCheckoutURL(skip_to_payment){
	//var sm_type = $('sm_type').value; // 1=simple delivery , 2=complex delivery
	//console.log("skip to payment="+skip_to_payment);
	if(skip_to_payment==1){
		$('nextlink').href = ROOT_WWW + 'index.php?object=cart&method=Checkout';
	}else{
		$('nextlink').href = ROOT_WWW + 'index.php?object=cart&method=SelectDelivery';//CheckoutSimple
	}
	/*
	if(sm_type==1){
		$('nextlink').href = ROOT_WWW + 'index.php?object=cart&method=CheckoutSimple';//CheckoutSimple
	}else{
		$('nextlink').href = ROOT_WWW + 'index.php?object=cart&method=Checkout';//Checkout
	}
	*/

}

function CLSaveSMDelivery(){
	var sm_type = $('sm_type').value;
	var url = "index.php?object=cart&method=SaveSMDelivery&sm_type=" + sm_type;
	new Ajax.Request(url, {
		  method: 'post'
		  ,onSuccess: function(transport){
				var s = transport.responseText;
				//var data = eval('('+transport.responseText+')');
				CLCheckValidity();
		}
	});
}

function CLAOnChange(cartid,addressid,newstatus){
	window.status = "Sending e-mail notification to customer...";
	//CLAHideStatusForm(cartid,addressid);
	var url = "index.php?object=cart&method=SetStatus&cartid="+cartid+"&addressid="+addressid+"&status="+newstatus;
	new Ajax.Request(url, {
		  method: 'post'
		  ,onSuccess: function(transport){
				var s = transport.responseText;
				var data = eval('('+transport.responseText+')');
				var new_status_name = "Status: " + data.status_name;
				window.location.reload();
		}
	});
}

var CLItem = Class.create({
	cartitemid:0
	,quantity:0
});
function getScreenQuantities(cartitemid){
	var ret = new Array();
	var temp = $$("input.cart_onequantity");
	for(var i=0;i<temp.length;i++){
		var tokens = temp[i].id.split('_');
		var oneitem = new CLItem();
		oneitem.cartitemid = tokens[1];
		oneitem.quantity = temp[i].value;
		ret.push(oneitem);
	}
	return ret;
}

function CLDeleteCartitem(cartitemid){
	if(confirm("Sure?")){
		$('quantity_'+cartitemid).value=0;
		CLSubmitForUpdate();
	}
}
function CLSubmitCartComment(quiet){
	var items = getScreenQuantities();
	if(quiet==1){}else{
		$('notification_onbeginsave').show();
		$('notification_onendsave').hide();
	}
	var url = "index.php?object=cart&method=SubmitForUpdateComment&comment="+$('comment').value;
	new Ajax.Request(url, {
		  method: 'post'
		  ,onSuccess: function(transport){
				var s = transport.responseText;
				var data = eval('('+transport.responseText+')');
				if(quiet==1){}else{
					$('notification_onbeginsave').hide();
					$('notification_onendsave').show();
					setTimeout('CLHideNotification()',1500);
				}
		} // onSuccess
	});
}
function CLSubmitForUpdate(){
	var items = getScreenQuantities();
	$('notification_onbeginsave').show();
	$('notification_onendsave').hide();
	var url = "index.php?object=cart&method=SubmitForUpdate&coderabat="+$('coderabat').value;
	for(var i=0;i<items.length;i++){
		url += "&quantity_" + items[i].cartitemid +"=" + items[i].quantity;
	}
	new Ajax.Request(url, {
		  method: 'post'
		  ,onSuccess: function(transport){
				var s = transport.responseText;
				var data = eval('('+transport.responseText+')');

				// handling discount
				var discount = data.discount_value;
				if(discount>0){
					$('discount').update("-"+number_format(discount,2,'.',',') + " CHF");
					$('discount').show();
				}else{
					$('discount').update("0 CHF");
					$('discount').hide();
				}

				// handling deleted
				for(var i=0;i<data.deleted.length;i++){
					//console.log("Deleting cartitem_"+data.deleted[i]);
					$("cartitem_"+data.deleted[i]).remove();
				}

				// recalculating total(s)
				var bigtotal = 0;
				participants_errors = 0;
				for(var i=0;i<data.remaining_ids.length;i++){
					var cartitemid = data.remaining_ids[i];
					var individual_total = data.remaining_price[i] * data.remaining_quantities[i];
					var available = data.availability[i];
					var cours_or_product = data.cours_or_product[i];

					bigtotal += individual_total;
					$('totalprice_'+cartitemid).update(number_format(individual_total,2,'.',',')+' CHF');

					if(available!=true){
						//console.log('warning ');
						participants_errors++;
						$('warning_'+data.remaining_ids[i]).show();
						if(cours_or_product==1){
							if(data.freeplaces[i]>0){
								$('warning_'+data.remaining_ids[i]).title="Seule(s) " + data.freeplaces[i] + " place(s) est(sont) encore libre(s).";
							}else{
								$('warning_'+data.remaining_ids[i]).title="Cours plus disponible.";
							}
						}else{
							if(data.freeplaces[i]>0){
								$('warning_'+data.remaining_ids[i]).title="Seule(s) " + data.freeplaces[i] + " items(s) est(sont) encore disponible(s).";
							}else{
								$('warning_'+data.remaining_ids[i]).title="Produit plus disponible.";
							}
						}
					}else{
						$('warning_'+data.remaining_ids[i]).hide();
					}
				}
				bigtotal -= discount;
				$('total').update(number_format(bigtotal,2,'.',',')+' CHF');

				if($('headerProductCounter'))
					$('headerProductCounter').update(data.cart_total_count);

				// notification
				$('notification_onbeginsave').hide();
				$('notification_onendsave').show();
				setTimeout('CLHideNotification()',1500);
				CLCheckValidity();
		} // onSuccess
	});
}

function CLHideNotification(){
	$('notification_onendsave').hide();
}

function number_format (number, decimals, dec_point, thousands_sep) {

    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

//- AJAX cart FUNCTIONS

function cartActivateTab(id){

	var curent = 1;

		handleEtape(id);




		if(id==2){
			cartLoadProductsIframe();
		}

		if(id==3){
			$('nav_next_container').hide();
			cartLoadPaymentIframe();
		}else{
			$('nav_next_container').show();
		}




		// this while was right bellow handleEtape()
		while($('steptab'+curent)){
			if(curent==id ){
				$('steptab'+curent).addClassName('cart_tab_selected');
				$('steppanel'+curent).show();
			}else{
				$('steptab'+curent).removeClassName('cart_tab_selected');
				$('steppanel'+curent).hide();
			}
			curent++;
		}

}

function handleEtape(id){
	var curent = 1;
	$('etape_numero').update(id);
	while($('steptab'+curent)){
		if(curent<id ){
			$('steptab'+curent).hide();
		}else{
			$('steptab'+curent).show();
		}
		curent++;
	}
}

function cartUpdateTabsStatus(obj){
	var temp = $(obj).id.split('_');
	delivery_method = temp[1];
	//console.log("DLVR="+delivery_method);
	// cart_count1 = products , cart_count2 = gifts
	if(cart_count2>0)
		$('steptab2').setStyle("color:#fff;");
	else
		$('steptab2').setStyle("color:#b64d7f;");

	//console.log(cart_has_shipped);
	if(cart_has_shipped>0)
		$('steptab3').setStyle("color:#fff;");
	else
		$('steptab3').setStyle("color:#b64d7f;");
}

function cartValidateTabTransition(newtabid,direction){
	var ret=false;
	//alert(cart_has_shipped);
	//console.log("NewTabID="+newtabid+' userid='+user_auth_id+' direction='+ direction+ ' cc1='+cart_count1+' , cc2='+cart_count2);
	var errmsg = '';
	switch(newtabid){
		case 1: // Authentication
			ret = true;
		break;
		case 2: // Products
			if(cart_has_shipped<=0 && direction != 'undefined'){
				var newtab = direction<0?1:3;
				cartCertainTab(newtab,direction);
				return false;
			}
		/*
			if((cart_count1<=0 && direction != 'undefined') || (delivery_method>0 && direction != 'undefined')){
				var newtab = direction<0?2:4;
				//console.log('skipping the products tab...'+newtab);
				cartCertainTab(newtab,direction);
				return false;
			}
		*/
			ret = true;
		break;

		case 3: // Payment
			ret = true;
		break;
	}
	if(errmsg!='')
		alert(errmsg);
	return ret;
}

function cartCertainTab(tabid,direction){
	var nt = tabid;
	if(cartValidateTabTransition(nt,direction)){
		if($('steptab'+nt)){
			current_tab = nt;
			cartActivateTab(current_tab);
		}
	}
}
function cartNextTab(){
	var nt = current_tab + 1;
	if(cartValidateTabTransition(nt,1)){
		if($('steptab'+nt)){
			current_tab = nt;
			cartActivateTab(current_tab);
		}
	}
}

function cartPrevTab(){
	var nt = current_tab - 1;
	if(nt>1){
		if(cartValidateTabTransition(nt,-1)){
			if($('steptab'+nt)){
				current_tab = nt;
				cartActivateTab(current_tab);
			}
		}
	}else{
		//alert('da');
		window.top.location = ROOT_WWW + "/index.php?object=cart&method=SelectDelivery";
	}

}

function cartShowAddAddressForm(newaddress_form,creating,theid){
	//console.log(creating);
	if(creating==1){
		if($('title_form'))
			$('title_form').update('Ajouter une adresse de livraison');
		if($('rec_addressid'))
			$('rec_addressid').value=0;
	}else{
		if($('title_form'))
			$('title_form').update('Modifier une adresse de livraison');
		if($('rec_addressid'))
			$('rec_addressid').value=theid;
		loadAddressIntoAddressFormForShippingIframeSimple(theid);
	}
	//console.log(theid);
	if($('toggler_'+newaddress_form))
		$('toggler_'+newaddress_form).hide();
	if($('div_'+newaddress_form))
		$('div_'+newaddress_form).show();
}

function loadAddressIntoAddressFormForShippingIframeSimple(addressid){
	var url = 'index.php?object=cart&method=GetAddress&addressid='+addressid;
	new Ajax.Request(url, {
		method: 'post',
		onSuccess: loadAddressIntoAddressFormForShippingIframeSimpleExecute
	});
}
function loadAddressIntoAddressFormForShippingIframeSimpleExecute(transport){
	var response = eval('('+transport.responseText+')');
	$('rec_address1').value = response.address1;
	$('rec_address2').value = response.address2;
	$('rec_zip').value = response.zip;
	$('rec_city').value = response.city;
}

function cartCancelAddAddress(newaddress_form){
	if($(newaddress_form))
		$(newaddress_form).reset();
	if($('div_'+newaddress_form))
		$('div_'+newaddress_form).hide();
	if($('toggler_'+newaddress_form))
		$('toggler_'+newaddress_form).show();
}

function cartSubmitAddAddress(newaddress_form){
	var city = $(newaddress_form).elements['rec_city'] ? $(newaddress_form).elements['rec_city'].value : '';
	var zip = $(newaddress_form).elements['rec_zip'] ? $(newaddress_form).elements['rec_zip'].value : '';
	var address1 = $(newaddress_form).elements['rec_address1'] ? $(newaddress_form).elements['rec_address1'].value : '';
	var address2 = $(newaddress_form).elements['rec_address2'] ? $(newaddress_form).elements['rec_address2'].value : '';
	if($(newaddress_form).elements['rec_addressid'])
		var addressid = $(newaddress_form).elements['rec_addressid'].value;
	if($(newaddress_form).elements['rec_boxname'])
		var boxname = $(newaddress_form).elements['rec_boxname'].value;
	manager.createNewBox(city,zip,address1,address2,addressid,boxname);
}

function cartUpdateBoxForm(){
	if($('rec_addressid')){
		var addressid = $('rec_addressid').value;
		if(addressid>0 || addressid==''){
			$('support_rec_city').hide();
			$('support_rec_address1').hide();
			$('support_rec_address2').hide();
			$('support_rec_zip').hide();
		}else{
			$('support_rec_city').show();
			$('support_rec_address1').show();
			$('support_rec_address2').show();
			$('support_rec_zip').show();
		}
	}
}

function cartTabs_addresses(){
	$('pickups').hide();
	$('addresses').show();
	$('div_newaddress_form').hide();
	$('toggler_newaddress_form').show();
}

function cartTabs_pickups(){
	$('addresses').hide();
	$('pickups').show();
	$('div_newaddress_form').hide();
	$('toggler_newaddress_form').hide();
}


function cartLoadGiftsIframe(){
	//$('loading').show();
	if($('iframe1')){
		$('iframe1').src = "index.php?object=cart&method=ShippingIframe&whattoshow=gifts";
		$('iframe1').observe('Load',function(){

		//console.log('gata');
		//$('loading').hide();
		});
	}
}

function cartLoadProductsIframe(){

	//$('loading').show();
	if($('iframe2')){
		$('iframe2').src = "index.php?object=cart&method=ShippingIframe&whattoshow=products";
		//alert('prods-gata:' + $('iframe2').src);
		$('iframe2').observe('Load',function(){

		//console.log('gata');
		//$('loading').hide();
		});
	}
}


function cartLoadPaymentIframe(){

	//$('loading').show();

	$('iframe3').src = "about:blank";
	setTimeout('$("iframe3").src = "index.php?object=cart&method=PayIframe";',100);

}

function cartadminTOGGLE(cartid){
	$('orderdetails_'+cartid).toggle();
	if($('orderdetails_'+cartid).visible()){
		$('orderheader_'+cartid).setStyle('background:#ccc;');
	}else{
		$('orderheader_'+cartid).setStyle('background:#fff;');
	}
}

function Pay_togglecomments(){
	if($('addcomment_checkbox').checked){
		$('addcomment_support').show();
	}else{
		$('addcomment_support').hide();

		// we delete the comment when the user unchecks the checkbox
		$('comment').value= '';
		CLSubmitCartComment(1);
	}

}
