// JavaScript Document
//SHOPPING CART UPDATE PRODUCTS LIVE!
$(function() {
	$("#shopping_card tr .remove input").click(function() {
		var product_ref = $(this).val();
		$.ajax({
			type: "GET",
			url: "includes/bc/?do=shopping_cart",
			data: "quantity["+product_ref+"]=0",
			success: function() {
				$("#shopping_card tr .quantity input[name*='quantity["+product_ref+"]']").val("0");
				$("#shopping_card tr .remove input[value="+product_ref+"]").parent().parent().remove();
				calcPrice();
			},
			error: function() {
				window.location("includes/bc/?do=shopping_cart&quantity[" + product_ref + "]=0");
			}
		});
	});
	$("#shopping_card tr .quantity input").keyup(function() {
		var product_ref = $(this).attr("name").slice(9, -1);
		var quantity = $(this).val();
		var QuantityCheck = new LiveValidation($(this).attr("name"));
		QuantityCheck.add( Validate.Numericality, { onlyInteger: true } );
		QuantityCheck.add( Validate.Numericality, { minimum: 1, maximum: 999 } );
		LiveValidation.massValidate([ QuantityCheck ])
		if(LiveValidation.massValidate([ QuantityCheck ])){
			$.ajax({
				type: "GET",
				url: "includes/bc/?do=shopping_cart",
				data: "quantity["+product_ref+"]="+quantity,
				success: function() {
					calcPrice();
				},
				error: function() {
					window.location("includes/bc/?do=shopping_cart&quantity[" + product_ref + "]=" + quantity);
				}
			});
		}else{
			document.getElementById('usc').disabled = true;
			document.getElementById('cep').disabled = true;
			show_alert("Inserte una cantidad correcta");
		}
	});
});

function calcPrice() {
	var totalPrice = 0;
	var sub_totalPrice = 0;
	$("#shopping_card tr .quantity").parent().each(function() {
		var quantity = $(".quantity input", this).val();
		var unitPrice = $(".unit_price", this).text().slice(-7);
		var extendedPrice = Number(parseFloat(quantity))*Number(parseFloat(unitPrice));
		sub_totalPrice += extendedPrice;
		$(".extended_price", this).html(parseFloat(extendedPrice).toFixed(2) + " &euro;");
	});
	if(sub_totalPrice >= 60.00 || sub_totalPrice == 0.00){
		var gde = 0.00;
	}else if(sub_totalPrice != 0){
		var gde = 6.00;	
	}
	totalPrice = Number(parseFloat(sub_totalPrice))+Number(parseFloat(gde));
	$("#sc_total1 .c_subtotal").html(parseFloat(sub_totalPrice).toFixed(2));
	$("#sc_total2 .gde").html(parseFloat(gde).toFixed(2));
	$("#sc_total3 .total_price").html(parseFloat(totalPrice).toFixed(2));
	$('input[name="order_price"]').val(parseFloat(totalPrice).toFixed(2));
	//document.getElementById('order_price').value = parseFloat(totalPrice).toFixed(2);
	if(!isNaN(totalPrice)){
		document.getElementById('usc').disabled = false;
		document.getElementById('cep').disabled = false;
	}else{
		document.getElementById('usc').disabled = true;
		document.getElementById('cep').disabled = true;
	}
	if ( totalPrice == 0 ) {
		$("#shopping_cart_main").replaceWith("<br><br><p style=\"text-align = center;\">Su carta de compra no contiene Productos.</p></br></br>");
		//window.open("includes/bc/?do=delete_card", "_self");
		document.getElementById('usc').disabled = true;
		document.getElementById('cep').disabled = true;
	}
}
/* COMPRA */
/* ELIMINAR PEDIDO */
function delete_card(){
		window.open("includes/bc/?do=delete_card", "_self");
		//window.location("includes/bc/?do=delete_card");
}

var ShoppingCartStep = 0;

function ShoppingCartModule(){
	
	var ShoppingCartShippingStatus 	= document.getElementById('shopping_cartShipping').style.visibility;
	var ShoppingCartPaymentStatus 	= document.getElementById('shopping_cartPayment').style.visibility;
	
	if( ShoppingCartShippingStatus == "hidden" &&  ShoppingCartPaymentStatus == "hidden"){ ShoppingCartStep = 0; }
	
	var ShoppingCartError = 0;
	var $alert;
	if(ShoppingCartStep == 0 && $("#sc_total3 .total_price").html() != '0.00'){
		ShoppingCartDisableOptions();
		ShoppingCartShipping();
		ShoppingCartPayment();
		ShoppingCartStep = 1;
		
		if($('#ShippingCreateAccount').size() > 0){
			$('#CreateAccount').remove();
			$("input[name=\"BillingStatus\"]").attr('checked') ? $("#BillingLegal").show() : $("#BillingLegal").hide();
			$('#my_account_select input[name="crearuc"]').click(function(){
				section_select('shopping_cart', 0);
				show_alert('Termine de tramitar su pedido para crear la cuenta de usuario.');
			});
			var UserFirstName = new LiveValidation('FirstName');
				UserFirstName.add(Validate.Presence);
				UserFirstName.add(Validate.Exclusion, {within:['Insertar Nombre']});
			
			var UserLastName = new LiveValidation('LastName');
				UserLastName.add(Validate.Presence);
				UserLastName.add(Validate.Exclusion, { within: ['Insertar Apellidos'] });
			
			var UserDNINIF = new LiveValidation('DNI/NIF');
				UserDNINIF.add(Validate.Presence);
				UserDNINIF.add(Validate.Exclusion, { within: ['Insertar DNI/NIF'] });
		
			$("input[name=\"BillingStatus\"]").attr('checked') ? UserDNINIF.enable() : UserDNINIF.disable();
			
			$("input[name=\"BillingStatus\"]").click(function(){
				$(this).attr('checked') ? UserDNINIF.enable() : UserDNINIF.disable();
			});
			
			$('#ShippingCreateAccount input[name="EMail"]').keyup(function(){
				var UserEmail = new LiveValidation('EMail');
				UserEmail.add(Validate.Presence);
				UserEmail.add(Validate.Exclusion, {within:['Insertar E-Mail']});
				UserEmail.add(Validate.Email);
				if(LiveValidation.massValidate([ UserEmail ])){
					var xml_result;
					var url = 'includes/bc/';
					url += '?do=checkMail';
					url += '&rc_user_email='+$(this).val();
					url += '&sid='+Math.random();
					xml_result = new makeAJAX();
					xml_result.open('GET', url, true);
					xml_result.onreadystatechange = 
					function(){
						if(xml_result.readyState == 4){
							if(xml_result.status == 200){
								if(xml_result.responseText == 'OK'){
									show_alert('Ya existe un usuario con esta cuenta de E-Mail');
									$('#ShippingCreateAccount input[name="EMail"]').val('Insertar E-Mail');
								}
							}else{
								alert("no existe url");	
							}
						}
					 }
					 xml_result.send(null);	
				}
			});
			
			var UserTelephone = new LiveValidation('Telephone');
			UserTelephone.add(Validate.Numericality, {onlyInteger: true});
			
			var UserMobilephone = new LiveValidation('Mobilephone');
			UserMobilephone.add(Validate.Numericality, {onlyInteger: true});
			
			var UserFax = new LiveValidation('Fax');
			UserFax.add(Validate.Numericality, {onlyInteger: true});
			
			var Acou = new LiveValidation('acou');
			Acou.add(Validate.Acceptance);
			
			var AddressBookStreet = new LiveValidation('Street');
			AddressBookStreet.add(Validate.Exclusion, {within:['Insertar Calle']});
			AddressBookStreet.add(Validate.Presence);
			
			var AddressBookCP = new LiveValidation('PostCode');
			AddressBookCP.add(Validate.Presence);
			AddressBookCP.add(Validate.Numericality, { onlyInteger: true });
			AddressBookCP.add(Validate.Numericality, { minimum: 1000, maximum: 54999 });
			AddressBookCP.add(Validate.Exclusion, { within:['00000'] });
			
			var password = new LiveValidation('Password');
			password.add(Validate.Presence);
			password.add(Validate.Exclusion, {within:['password']});
			
			var password2 = new LiveValidation('Password2');
			password2.add(Validate.Presence);
			password2.add(Validate.Confirmation, { match: 'password'});
			password2.add(Validate.Exclusion, {within:['password']});
		}
		
	}else if(ShoppingCartStep == 1){
		CCCPaymentStatus 									= document.getElementById('CCC').checked;
		CCPaymentStatus										= document.getElementById('CC').checked;
		if($('#ShippingCreateAccount').size() > 0){
			
			var UserFirstName = new LiveValidation('FirstName');
			UserFirstName.add(Validate.Presence);
			UserFirstName.add(Validate.Exclusion, {within:['Insertar Nombre']});
			
			var UserLastName = new LiveValidation('LastName');
			UserLastName.add(Validate.Presence);
			UserLastName.add(Validate.Exclusion, { within: ['Insertar Apellidos'] });
			
			var UserEmail = new LiveValidation('EMail');
			UserEmail.add(Validate.Presence);
			UserEmail.add(Validate.Exclusion, {within:['Insertar E-Mail']});
			UserEmail.add(Validate.Email);
			
			var UserDNINIF = new LiveValidation('DNI/NIF');
			UserDNINIF.add(Validate.Presence);
			UserDNINIF.add(Validate.Exclusion, { within: ['Insertar DNI/NIF'] });
		
			$("input[name=\"BillingStatus\"]").click(function(){
				$(this).attr('checked') ? UserDNINIF.enable() : UserDNINIF.disable();
			});
			
			var UserTelephone = new LiveValidation('Telephone');
			UserTelephone.add(Validate.Numericality, {onlyInteger: true});
			
			var UserMobilephone = new LiveValidation('Mobilephone');
			UserMobilephone.add(Validate.Numericality, {onlyInteger: true});
			
			var UserFax = new LiveValidation('Fax');
			UserFax.add(Validate.Numericality, {onlyInteger: true});
			
			var Acou = new LiveValidation('acou');
			Acou.add(Validate.Acceptance);
			
			var AddressBookStreet = new LiveValidation('Street');
			AddressBookStreet.add(Validate.Exclusion, {within:['Insertar Calle']});
			AddressBookStreet.add(Validate.Presence);
			
			var AddressBookCP = new LiveValidation('PostCode');
			AddressBookCP.add(Validate.Presence);
			AddressBookCP.add(Validate.Numericality, { onlyInteger: true });
			AddressBookCP.add(Validate.Numericality, { minimum: 1000, maximum: 54999 });
			AddressBookCP.add(Validate.Exclusion, { within:['00000'] });
			
			var password = new LiveValidation('Password');
			password.add(Validate.Presence);
			password.add(Validate.Exclusion, {within:['password']});
			
			var password2 = new LiveValidation('Password2');
			password2.add(Validate.Presence);
			password2.add(Validate.Confirmation, { match: 'password'});
			password2.add(Validate.Exclusion, {within:['password']});
			
			var p = $('#ShippingCreateAccount select[name="ProvinciaId"]').val();
			var m = $('#ShippingCreateAccount select[name="MunicipioId"]').val();
			
			var SignUpOk = LiveValidation.massValidate([ UserFirstName, UserLastName, UserDNINIF, UserEmail, Acou, AddressBookStreet, AddressBookCP, password, password2 ]);
			
			if(!SignUpOk || !p || !m){
				ShoppingCartError 								= 1;	//Añadimos Error para parar script
				var $alert 										= 'Revise los campos obligatorios';
			}else{
				if(!CCPaymentStatus && !CCCPaymentStatus){
					ShoppingCartError 								= 1;	//Añadimos Error para parar script
					var $alert 										= 'Seleccione una Forma de Pago';
				}else{
					ShoppingCartError 								= 0;	//Limpiamos error
				}
			}
		}else{
			if(!CCPaymentStatus && !CCCPaymentStatus){
					ShoppingCartError 								= 1;	//Añadimos Error para parar script
					var $alert 										= 'Seleccione una Forma de Pago';
				}else{
					ShoppingCartError 								= 0;	//Limpiamos error
				}
		}
		/*if(CCPaymentStatus){
			var PAN = new Array();
			for(var x = 1; x <= 4; x++){
				PAN[x] = new LiveValidation('PAN'+x);
				PAN[x].add(Validate.Presence);
				PAN[x].add(Validate.Numericality, { onlyInteger: true });
				PAN[x].add(Validate.Numericality, { minimum: 0000, maximum: 9999 });
				PAN[x].add(Validate.Length, { is: 4 } );
				//PAN[x].add(Validate.Exclusion, { within:['0000'] });
			}
			var CCok = LiveValidation.massValidate([ PAN[1], PAN[2], PAN[3], PAN[4] ]);
			ShoppingCartError 								= CCok ? 0 : 1;
			$alert 											= CCok ? '' : 'Hay un error en la numeración de tarjeta.<br>';
			
			var CCMonth 									= document.getElementById('MONTH').value;
			var CCYear  									= document.getElementById('YEAR').value;
			
			var TempDate 									= new Date();
			var TempYear 									= TempDate.getYear();
			var TempMonth 									= TempDate.getMonth();
			
			if((CCYear == TempYear) && (TempMonth > CCMonth)){
				ShoppingCartError 							= 1;
				$alert 										+= 'La tarjeta está caducada.<br>';
			}
			
		}else{
			var PAN = 0;	
		}*/
		if(ShoppingCartError){
			show_alert($alert);
		}else{
			document.getElementById('OrderForm').submit();
		}
	}
}

function ShoppingCartDisableOptions(){
	var scm = document.getElementById('shopping_cart_main');
	var scm_e = scm.getElementsByTagName("input");
	for(var i =0 ; i<scm_e.length; i++){
		if(scm_e.item(i).type == "checkbox"){
			scm_e.item(i).disabled = true;
		}else{
			scm_e.item(i).readOnly = true;	
		}	
	}
}

function ShoppingCartShipping(){
	divStatus('shopping_cartShipping',1);
}

function ShoppingCartPayment(){
	divStatus('shopping_cartPayment',1);
}

function ShoppingCartOrderComment(){
	divStatus('ShoppingCartOrderComment',1);
}
/* SHOPPING CART PaymentMethod */

function changeMethod(a){
	var a; //Entrada de método
//CC 	-> shopping_cartPaymentCC
//CCC 	-> shopping_cartPaymentCCC	
	if(a == "CC"){
		divStatus('shopping_cartPaymentCC',1);
		divStatus('shopping_cartPaymentCCC',0);
		document.getElementById('CCC').checked = false;
	}else if(a == "CCC"){
		divStatus('shopping_cartPaymentCC',0);
		divStatus('shopping_cartPaymentCCC',1);	
		document.getElementById('CC').checked = false;
	}
}

function product_add(product_ref){
	var product_ref;
	var url = 'includes/bc/';
	url += '?do=shopping_cart';
	url += '&product_ref='+product_ref;
	url += '&quantity=1&xml=1';
	url += '&sid='+Math.random();
	xml_result = new makeAJAX();
    xml_result.open('GET', url, true);
	xml_result.onreadystatechange = 
	function(){
	   	if(xml_result.readyState == 4){
			if(xml_result.status == 200){
				show_msg(xml_result.responseXML);
			}else{
				alert("no existe url");	
			}
		}
	}
	xml_result.send(null);
}
