

$(document).ready(function (){
    if (document.minicart != null) {
        //alert('Honk!');
        linkEventsCartForm();
       
    }  
    
    if(document.frmCart != null){
    	changeShipment ();	
    	//$("#shop_gastos").change(changeShipment);
    	$("#shop_gastos", document.frmCart).click (changeShipment);
    }	
    
     
    
});

function linkEventsCartForm() {
	
    $(".amount", document.minicart).change (changeAmount);
    $(".delete", document.minicart).click (deleteProduct);
    $("#start_shopping", document.minicart).click (submitCart);
   
}

function submitCart (ev) {
    //alert (source + " " + loggedin);
    if (loggedin){ 
    	
    	self.location = _base_path+url_cart;
    }
    else {
    	
        afterLogin = _base_path+url_cart;
        
        //hay que cambiarlo por el registro express
        //showLogin();
       showLoginExpress();
        
        
    }
    ev.stopPropagation();
    return false;
}

function deleteProduct (ev) {
	
	
    var src = ev.target;
    while ( (src != null) && (src.tagName != 'A') ) src = src.parentNode;
    var prod = '';
    if (src != null) {
    	
        src = src.id;
        
        var params = src.split('_');
        var ctype = '';
        
        if(params[0] == 'delsbproduct'){
			ctype = '1';
		}
		else if (params[0] == 'delsbproductgirlfriend'){
			ctype = '2';
		}
		prod = params[1];
		
	
        if (prod != '') modifyCart (prod, ctype, '0');
    }
    if (prod == '') alert ("id raro: " + src);
    ev.stopPropagation();
    return false;
}

function fakePurchase(cartid,store){
	if ((cartid=='')||(store=='')){
		alert ("Parameters missing for fake purchase.")
		return false;
	}else{
		$.ajax({
	       url: _base_path+"fakePurchase.php",
	       type: "POST",
	       dataType: "text",
	       data: {
	           cartID: cartid,
	           storeID: store
	           	           
	       },
	        error: function(req, err, obj) {
	            alert ("Error " + err + req.status);
	        },
	        success: function (txt) {
	            if (txt=='OK'){
	            	alert ("Fake purchase was successful. Press 'OK' to continue.");
	            	self.location = 'SP_Final.html?pszPurchorderNum='+cartid+'&result=0';
	            	return false;
	            }else{
	            	alert ("An error ocurred while processing the fake purchase. Please try again later.");
	            	return false;
	        	}
	        }
	        
	        
	        
	    });
	}
	return false;
}

function changeAmount (ev) {
    //alert (ev.target.id);
 //   onblur="location.href='{sbproduct.PRODUCT_BUY_URL}&customer_type=1&amount='+this.value;" 
 
 	//alert('cantidad');
    var src = ev.target.id;
    
	var params = src.split('_');
	
		
	if(params[0] == 'sbproduct'){
			ctype = '1';
	}
	else if (params[0] == 'sbproductgirlfriend'){
		ctype = '2';
	}
	
	prod = params[1];
		
        
	


    
    /*
   
    var prod = '';
    var ctype = '';
    if ( (src.length > 20) && (src.substring (0, 20) == 'sbproductgirlfriend_') ) {
        prod = src.substring (20);
        ctype = '2';
    } else if ( (src.length > 10) && (src.substring (0, 10) == 'sbproduct_') ) {
        prod = src.substring (10);
        ctype = '1';
    }
    
    alert(prod);
    
    
    */
    
    //alert(ev.target.value);
    if ((prod != '')&&(ev.target.value>=0)&&(ev.target.value<10000)){
		
    	modifyCart (prod, ctype, Math.floor(ev.target.value));
    }
    else if (!((ev.target.value>=0)&&(ev.target.value<10000))){
    	alert ("You must introduce a valid amount");
    	document.location.reload();
    	
    }
    
    else alert ("id raro: " + src);
}

function modifyCart (prod, ctype, amount, pricegift,pound) {
	
	 
	  
	  
    //alert (prid + " " + ctype + " " + amount);
    var shoppingcartdiv = document.getElementById ('shoppingcartdiv');
    //var height = shoppingcartdiv.style.pixelHeight;
    shoppingcartdiv.innerHTML = document.getElementById("cartloading").innerHTML;
    //shoppingcartdiv.style.pixelHeight = height;
   // var price = giftprice;
   /*if (document.form_carro.pricegift.value != -1000)
   {
   		var pricegift = document.form_carro.pricegift.value;
   		if ((pricegift < 10 )&& (amount!=0)){
   			alert("The minimum value for a Gift Card minimum is �10");
   			pricegift = -1;
   		}
   }*/
   if (pound==undefined) {
   	 var pound = '';
   }
   if (pricegift==undefined) {
   	 var pricegift = '';
   }
   else if ((pricegift < 10 )&& (amount!=0)){
   			alert("The minimum value for a Gift Card is "+pound+"10");
   			pricegift = -1;
   	}
  	//alert('Price : ' + pricegift);
    $.ajax({
       url: _base_path+"modifyMiniCart.html",
       type: "POST",
       dataType: "html",
       data: {
           prod: prod,
           customer_type: ctype,
           amount: amount,
           pricegift: pricegift,
         //  giftprice : giftprice,
           request_uri: source
       },
        error: function(req, err, obj) {
            alert ("Error " + err + req.status);
        },
        success: function (html) {
            $("#shoppingcartdiv").html (html);
            linkEventsCartForm();
        }
    });
    
}

//Cambia en el fron-end el valor de los gastos de env�o
function changeShipment () {		 
	
	
	//alert("ENTRO");
	//Calculamos el total de los gastos de env�o	
	
	var shipvalue =   $("input[@name='shiptype']:checked").val();	
	var shipvalue_gf =  $("input[@name='shiptype_gf']:checked").val();	
	var price_tot =  $("input[@name='price_tot']").val();	
	var pound =  $("input[@name='pound']").val();	
	
	
	var id1;
	var title1;
	var description1;
	var price1;
	var id2;
	var title2;
	var description2;
	var price2;
	var ss = 0;
	
	if (shipvalue!=null || shipvalue_gf!=null){
	$.ajax({
       url: _base_path+"GetShipmentExpenses.php",
       type: "POST",
       dataType: "xml",
       data: {
           ship1: shipvalue,
           ship2: shipvalue_gf,
           price_tot: price_tot
           
       },
        error: function(req, err, obj) {
            alert ("Error " + err + req.status);
        },
        success: function (xml) {
            $(xml).find("ship1").each(function() {
				id1 = $("id",this).text();
				title1 = $("title",this).text();
				description1 = $("description",this).text();
				price1  = $("price",this).text();
				
				
			});
			$(xml).find("ship2").each(function() {
				id2 = $("id",this).text();
				title2 = $("title",this).text();
				description2 = $("description",this).text();
				price2  = $("price",this).text();
				
				
			});
			
			var total = $(xml).find("total").text();
			var total_formatted = $(xml).find("total_form").text();
			var total_withshipment = $(xml).find("total_withshipment").text();
			var total_withshipment_formatted = $(xml).find("total_withshipment_formatted").text();
			var shipping = $(xml).find("shipping").text();
			var shipping_formatted = $(xml).find("shipping_formatted").text();
		  // alert ("TOTAL="+total);
			//alert ("VALE="+total_formatted);
			//Actualizamos el total de los gastos de envío
			 $("#send_consts").text (pound+shipping_formatted);
			 $("#shop_line_precio").text (pound+shipping_formatted);
			 
				 
			//Obtenemos el total sin el euro del final
			var total_without_send = $("#sbprice").text()
			
			total_without_send = total_without_send.substring(0,total_without_send.length -1 );
			
			//Sumamos al total los gatos de envío
		    $("#shop_total_cuenta").text (pound+" "+ total_withshipment_formatted);
		    $("#shop_final_right").text (pound+" "+total_withshipment_formatted);
				 
				 
			
			
			//alert("SHIP1="+shipvalue);
			//alert("SHIP2="+shipvalue_gf);
			
			$("#ship1").val (shipvalue);
			$("#ship2").val (shipvalue_gf);
			//document.forms['frmCart'].elements['ship1'].value = shipvalue;
			//document.forms['frmCart'].elements['ship2'].value = shipvalue_gf;
			
			
				
			


		    
        }
        
        
        
    });
	}else{
		
		//Sumamos al total los gatos de envío
		 $("#shop_total_cuenta").text (pound+" "+ price_tot);
		 $("#shop_final_right").text (pound+" "+price_tot);
		
	}
	
	 	
}