// validacion de tarjeta de credito
function validaTarjetaCredito(ccNumb)
{
	var valid = "0123456789"  // Valid digits in a credit card number
	var len = ccNumb.length;  // The length of the submitted cc number
	var iCCN = parseInt(ccNumb);  // integer of ccNumb
	var sCCN = ccNumb.toString();  // string of ccNumb
	sCCN = sCCN.replace (/^\s+|\s+$/g,'');  // strip spaces
	var iTotal = 0;  // integer total set at zero
	var bNum = true;  // by default assume it is a number
	var bResult = false;  // by default assume it is NOT a valid cc
	var temp;  // temp variable for parsing string
	var calc;  // used for calculation of each digit

	// Determine if the ccNumb is in fact all numbers
	for (var j=0; j<len; j++) {
		temp = "" + sCCN.substring(j, j+1);
		if (valid.indexOf(temp) == "-1"){bNum = false;}
	}

	// if it is NOT a number, you can either alert to the fact, or just pass a failure
	if(!bNum){ bResult = false; }

	// Determine if it is the proper length 
	if((len == 0)&&(bResult)){  // nothing, field is blank AND passed above # check
		bResult = false;
	} else{  // ccNumb is a number and the proper length - let's see if it is a valid card number
		if(len >= 15){  // 15 or 16 for Amex or V/MC
  		for(var i=len;i>0;i--){  // LOOP throught the digits of the card
    		calc = parseInt(iCCN) % 10;  // right most digit
    		calc = parseInt(calc);  // assure it is an integer
    		iTotal += calc;  // running total of the card number as we loop - Do Nothing to first digit
    		i--;  // decrement the count - move to the next digit in the card
    		iCCN = iCCN / 10;                               // subtracts right most digit from ccNumb
    		calc = parseInt(iCCN) % 10 ;    // NEXT right most digit
    		calc = calc *2;                                 // multiply the digit by two
    		// Instead of some screwy method of converting 16 to a string and then parsing 1 and 6 and then adding them to make 7,
    		// I use a simple switch statement to change the value of calc2 to 7 if 16 is the multiple.
    		switch(calc){
      		case 10: calc = 1; break;       //5*2=10 & 1+0 = 1
      		case 12: calc = 3; break;       //6*2=12 & 1+2 = 3
      		case 14: calc = 5; break;       //7*2=14 & 1+4 = 5
      		case 16: calc = 7; break;       //8*2=16 & 1+6 = 7
      		case 18: calc = 9; break;       //9*2=18 & 1+8 = 9
      		default: calc = calc;           //4*2= 8 &   8 = 8  -same for all lower numbers
    		}                                               
  			iCCN = iCCN / 10;  // subtracts right most digit from ccNum
  			iTotal += calc;  // running total of the card number as we loop
			}  // END OF LOOP
			if ((iTotal%10)==0){  // check to see if the sum Mod 10 is zero
  			bResult = true;  // This IS (or could be) a valid credit card number.
			} else {
  			bResult = false;  // This could NOT be a valid credit card number
  		}
		}
	}
	return bResult;
}

function procesaPagoCesta(url)
{
	// primero validamos los datos de pago
	bResult=validaDatosPago();
	if (bResult)
	{
		$("boton_cesta").hide();
		$(document.body).startWaiting('bigBlackWaiting');
	
		var parametros=$("fmybasket").serialize();
		// nueva llamada Ajax para procesar el pago
		var myAjax=new Ajax.Request(url+"&"+parametros,
		{
			method:'get', 
			onSuccess: function(transport)
			{
				$(document.body).stopWaiting();
				var json=transport.responseText.evalJSON();
				if (json.result && json.result=="OK") 
				{
					try
					{
						location.href=json.url;
					}
					catch(err)
					{
						$(document.body).stopWaiting();
					}
				}
				else
				{
					// error
					if (json.error) 
					{
						$("boton_cesta").show();
						try
						{
							alert(json.error);
						}
						catch(err)
						{
							$(document.body).stopWaiting();
						}
					}
					if (json.url) location.href=json.url; 
					$(document.body).stopWaiting(); 
				}
			},
			onFailure: 	function ()	// ERROR CONTROL
			{
				$("boton_cesta").show();
				$(document.body).stopWaiting();
			}
		});
		return false;
	}
	else return false;
}

function modificaAtributosCesta(url, id_producto_viejo, id_producto_nuevo)
{
	$(document.body).startWaiting('bigBlackWaiting');

	// nueva llamada Ajax para modificar la cantidad
	var myAjax=new Ajax.Request(url+"&action=modifyAttribute&product_from="+id_producto_viejo+"&product_to="+id_producto_nuevo,
	{
		method:'get', 
		onSuccess: function(transport)
		{
			var json=transport.responseText.evalJSON();
			if (json.result=="OK") 
			{
				try
				{	
					ponDatosCestaFlotante(json.basket);
					ponDatosCesta(json.url, json.basket);
					$(document.body).stopWaiting();
				}
				catch(err)
				{
					$(document.body).stopWaiting();
				}
			}
			else 
			{
				// error
				if (json.error) 
				{
					try
					{
						alert(json.error);
					}
					catch(err)
					{
						$(document.body).stopWaiting();
					}
				}
				if (json.url!=undefined) location.href=json.url;
				$(document.body).stopWaiting();
			}
		},
		onFailure: 	function ()	// ERROR CONTROL
		{
			$(document.body).stopWaiting();
		}
		
	});
}

function modificaCantidadCesta(url, id_producto, id_cantidad)
{
	$(document.body).startWaiting('bigBlackWaiting');

	// nueva llamada Ajax para modificar la cantidad
	var myAjax=new Ajax.Request(url+"&action=modifyQuantity&product="+id_producto+'&quantity='+id_cantidad,
	{
		method:'get', 
		onSuccess: function(transport)
		{
			var json=transport.responseText.evalJSON();
			if (json.result=="OK") 
			{
				try
				{	
					ponDatosCestaFlotante(json.basket);
					ponDatosCesta(json.url, json.basket);
					$(document.body).stopWaiting();
				}
				catch(err)
				{
					$(document.body).stopWaiting();
				}
			}
			else 
			{
				// error
				if (json.error) 
				{
					try
					{
						alert(json.error);
					}
					catch(err)
					{
						$(document.body).stopWaiting();
					}
				}
				if (json.url!=undefined) location.href=json.url;
				$(document.body).stopWaiting();
			}
		},
		onFailure: 	function ()	// ERROR CONTROL
		{
			$(document.body).stopWaiting();
		}
		
	});
}

function modificaDireccionCesta(url, id_direccion)
{
	$(document.body).startWaiting('bigBlackWaiting');

	// nueva llamada Ajax para modificar la cantidad
	var myAjax=new Ajax.Request(url+'&action=modifyAddress&address='+id_direccion,
	{
		method:'get', 
		onSuccess: function(transport)
		{
			var json=transport.responseText.evalJSON();
			if (json.result=="OK") 
			{
				try
				{	
					ponDatosCestaFlotante(json.basket);
					ponDatosCesta(json.url, json.basket);
					$(document.body).stopWaiting();
				}
				catch(err)
				{
					$(document.body).stopWaiting();
				}
			}
			else 
			{
				// error
				if (json.error) 
				{
					try
					{
						alert(json.error);
					}
					catch(err)
					{
						$(document.body).stopWaiting();
					}
				}
				if (json.url!=undefined) location.href=json.url;
				$(document.body).stopWaiting();
			}
		},
		onFailure: 	function ()	// ERROR CONTROL
		{
			$(document.body).stopWaiting();
		}
		
	});

}

function eliminaProductoCesta(url, id_producto)
{
	$(document.body).startWaiting('bigBlackWaiting');

	// nueva llamada Ajax para modificar la cantidad
	var myAjax=new Ajax.Request(url+'&action=deleteProduct&product='+id_producto,
	{
		method:'get', 
		onSuccess: function(transport)
		{
			var json=transport.responseText.evalJSON();
			if (json.result=="OK") 
			{
				try
				{	
					ponDatosCestaFlotante(json.basket);
					ponDatosCesta(json.url, json.basket);
					$(document.body).stopWaiting();
				}
				catch(err)
				{
					$(document.body).stopWaiting();
				}
			}
			else 
			{
				// error
				if (json.error) 
				{
					try
					{
						alert(json.error);
					}
					catch(err)
					{
						$(document.body).stopWaiting();
					}
				}
				if (json.url!=undefined) location.href=json.url;
				$(document.body).stopWaiting();
			}
		},
		onFailure: 	function ()	// ERROR CONTROL
		{
			$(document.body).stopWaiting();
		}
		
	});
}

function eliminaProductoCapaCesta(url, id_producto, i)
{
	var cart_box = 	'cart_box';
	var cart_div = 	'ordline_';
	
	$(cart_box).startWaiting('blackWaiting');
	
	// quitar de antemano el item de la cesta
	//$(cart_div+i).hide();
	try {
		MH.viewcart();
	}
	catch(e){}

	// nueva llamada Ajax para modificar la cantidad
	var myAjax=new Ajax.Request(url+'&action=deleteProduct&product='+id_producto,
	{
		method:'get', 
		onSuccess: function(transport)
		{
			var json=transport.responseText.evalJSON();
			if (json.result=="OK") 
			{
				try
				{	
					location.href = document.location;
					//ponDatosCestaFlotante(json.basket);
					//$(document.body).stopWaiting();
				}
				catch(err)
				{
					$(document.body).stopWaiting();
				}
			}
			else 
			{
				// error
				if (json.error) 
				{
					try
					{
						alert(json.error);
					}
					catch(err)
					{
						$(document.body).stopWaiting();
					}
				}
				if (json.url!=undefined) location.href=json.url;
				$(document.body).stopWaiting();
			}
		},
		onFailure: 	function ()	// ERROR CONTROL
		{
			$(cart_box).stopWaiting();
		}
		
	});
}

function ponDatosCesta(url, datos)
{
	// vamos poniendo todos los campos javascript
	$("campaign_name").innerHTML=datos.campaign_name;
	$("precio_original").innerHTML=datos.precio_tienda;
	$("precio_privalia").innerHTML=datos.precio_privalia;
	$("subtotal").innerHTML=datos.subtotal;
	$("ahorro").innerHTML=datos.ahorro;
	$("total").innerHTML=datos.order.order_amount;

	// filas de la cesta
	tabBody=$("filas_cesta");

	if ( tabBody.hasChildNodes() )
	{
		while ( tabBody.childNodes.length >= 1 )
		{
			tabBody.removeChild( tabBody.firstChild );       
		} 
	}
	
	var ultimo=datos.lines.length-1;
	for (i=0;i<datos.lines.length;i++)
	{
		fila_cesta=datos.lines[i];
		
		var row=document.createElement("tr");
		Element.extend(row);
		if (i==ultimo) row.addClassName('blank');

		var cell1=document.createElement("td");	
		Element.extend(cell1);
		cell1.addClassName("thumbnail");
		cell1.innerHTML="<a href='#' onClick=\"zoomImageCart("+fila_cesta.ordline_FK_campaign_PK+", '"+fila_cesta.id+"')\" >"+
			"<span class='ico-zoom'></span>"+
			"<img src='"+fila_cesta.img+"' alt='zoom producto' border='0' /></a>";
			
		var cell2=document.createElement("td");
		Element.extend(cell2);
		cell2.addClassName("size10");
		cell2.innerHTML=fila_cesta.ordline_description;
		
		var cell3=document.createElement("td");
		Element.extend(cell3);
		cell3.addClassName("size");
		string_node3="<select name='talla/"+fila_cesta.ordline_PK+"' onChange='modificaAtributosCesta(\""+url+"\", "+fila_cesta.ordline_PK+", this.options[this.selectedIndex].value)'>";			

		for (j=0;j<fila_cesta["sizes"].length;j++)
		{
			size_cesta=fila_cesta["sizes"][j];
			
			string_node3+="<option value='"+size_cesta.key+"' ";
			if (!size_cesta.available) string_node3+=" disabled='disabled' ";
			if (fila_cesta.selectedSize==size_cesta.key) string_node3+=" selected ";
			string_node3+=">"+size_cesta.label;
			string_node3+="</option>";
		}
		string_node3+="</select>";
		cell3.innerHTML=string_node3;
		
		var cell4=document.createElement("td");
		Element.extend(cell4);
		string_node4="<select name='cantidad/"+fila_cesta.ordline_PK+"' onChange='modificaCantidadCesta(\""+url+"\", "+fila_cesta.ordline_PK+", this.options[this.selectedIndex].value)'>";
			
		for (var quantity_cesta in fila_cesta.quantities)
		{
			string_node4+="<option value='"+quantity_cesta+"' ";
			if (quantity_cesta==fila_cesta.ordline_quantityOrdered) string_node4+=" selected ";
			string_node4+=">"+quantity_cesta+"</option>";
		}
		string_node4+="</select>";
		string_node4+="&nbsp;<span class='inline importe'>R$&nbsp;"+fila_cesta.ordline_price+"</span>";
		cell4.innerHTML=string_node4;
		
		var cell5=document.createElement("td");
		Element.extend(cell5);
		cell5.addClassName("aligncenter");
		cell5.innerHTML="<div class='padleft5'><a class='ico-only-delete' href='javascript:;' onClick='eliminaProductoCesta(\""+url+"\", "+fila_cesta.ordline_PK+")' title='Borrar producto'>"+
			"Borrar</a></div>";
		
		var cell6=document.createElement("td");
		Element.extend(cell6);
		cell6.addClassName("importe");
		cell6.innerHTML="<strong>R$&nbsp;"+fila_cesta.ordline_total+"</strong>";

		row.appendChild(cell1);
		row.appendChild(cell2);
		row.appendChild(cell3);
		row.appendChild(cell4);
		row.appendChild(cell5);
		row.appendChild(cell6);
		
		tabBody.appendChild(row);
	}

	// costes de la cesta
	tabBody1=$("costes_cesta");
	if ( tabBody1.hasChildNodes() )
	{
		while ( tabBody1.childNodes.length >= 1 )
		{
			tabBody1.removeChild( tabBody1.firstChild );       
		} 
	}

	for (j=0;j<datos.costs.length;j++)
	{
		coste_cesta=datos.costs[j];
		var row=document.createElement("tr");
		Element.extend(row);
		row.addClassName("blank");
		
		var cell1=document.createElement("td");
		Element.extend(cell1);
		cell1.innerHTML=coste_cesta.ordcost_description;

		var cell2=document.createElement("td");
		Element.extend(cell2);
		cell2.addClassName("importe alignright");
		cell2.innerHTML="R$&nbsp;"+coste_cesta.ordcost_total;
		
		row.appendChild(cell1);
		row.appendChild(cell2);

		tabBody1.appendChild(row);
	}
	
	// parcelas
	var quote;
	var sActive;
	var sParcelas;
	var sp;
	var amount = datos.order.order_amount.replace(',', '');
	var htmlcode = '';
	
	$("parcelados").update('');

	for (j=1;j<=6;j++) {
		eval("sp = datos.parcela"+j+";");
		
		if(sp!=null && amount >= sp){
			quote = Math.ceil((amount * 100) / j) / 100;
			quote = quote.toFixed(2);
	
			if(j==1)	{
				sActive = "active";
				sParcelas = "parcela";
				sChecked = "checked";
			}else{
				sActive = "";
				sParcelas = "parcelas";
				sChecked = "";
			}
			
			if(j==4)
			{
				htmlcode +="<div class='clear'></div><div class='line-dotted padtop10'></div><div class='clear padtop10'></div>";
			}
			
			htmlcode += "<div id='x"+j+"' class='parcel " + sActive + "'><input type='radio' " + sChecked + " onclick=\"activarParcela('x"+j+"')\" value='"+j+"' name='numero_pagos' id='numero_pagos"+j+"'/><label for='numero_pagos"+j+"'>"+j+" " + sParcelas + " de <br/><span>R$ "+addCommas(quote)+"</span></label></div>";
			
		}
	}

	$("parcelados").update(htmlcode + '<div class="clear"></div>');
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function validaDatosPago()
{
	if ($("accepted").value==0) 
	{	
		alert(s_alert_notermsaccepted);	
		return false;
	} 

	var numero=$("pan").value;
	if (numero.length==0) 
	{
		alert(s_alert_nocreditcard);	
		return false;
	} 

	if (!validaTarjetaCredito(numero))
	{
		alert(s_alert_creditcarderror);
		return false;
	}
	
	// fecha de caducidad
	if ($('mes').selectedIndex<=0 || $('any').selectedIndex<=0)
	{
		alert(s_alert_noexpiredate);		
		return false;
	}
	
	var miFecha=new Date();
	var miMes=miFecha.getMonth()+1;
	var miAny=miFecha.getFullYear();

	var suMes=$('mes').value;
	var suAny=$('any').value;

	if (suAny==miAny)
	{
		// el mes introducido debe ser igual o superior al actual
		if (suMes<miMes)
		{
			alert(s_alert_expiredateerror);			
			return false;
		}
	}

	// cvv2
	if ($('cvv2').value.length!=3 && $('cvv2').value.length!=4) 
	{
		alert(s_alert_seccodeerror);
		return false;
	} 

	// nombre
	if ($('nombre').value.length==0)
	{
		alert(s_alert_nocardowner);		
		return false;
	}
	
	// tipo de tarjeta
	if ($('tipo_tarjeta').selectedIndex<=0)
	{
		alert(s_alert_nocardtype);		
		return false;
	}

	//f5 continua deshabilitada pero ahora lanza mensaje
	document.onkeydown = function(e){
		if(e){
			document.onkeypress = function(){return true;}
		}			
		var evt = e?e:event;
		if(evt.keyCode==116){
			if(e){
				document.onkeypress = function(){
											document.getElementById('proceso_pago').style.visibility='hidden';
											document.getElementById('cancel_pago').style.visibility='visible';
											return false;
										}
			} else {
				evt.keyCode = 0;
				evt.returnValue = false;
			}
		}
		if(evt.keyCode == 27){
			if(e){
				document.onkeypress = function(){
											document.getElementById('proceso_pago').style.visibility='hidden';
											document.getElementById('cancel_pago').style.visibility='visible';
											return false;
										}
			} else {
				evt.keyCode = 0;
				evt.returnValue = false;
			}	
		}
	}
	
	//Ocultamos el boton de envio de formulario mientras se envian los datos a Braspag 
//	document.getElementById('final').style.visibility='hidden';
	//Mostramos un mensaje de espera mientras esperamos la respuesta de Braspag
//	document.getElementById('proceso_pago').style.visibility='visible';
	//Funcion evita reenvio del formulario
/*	if (!statSend) {
		statSend = true;
		document.getElementById('final').onmouseover=function(){};
		document.getElementById('final').onmouseout=function(){};
		return true;
	} else {	
		//alert("Formulario ya enviado");
		return false;
	}
*/
	return true;
}

function cargaDatosCesta(urlAjax)
{
	$(document.body).startWaiting("bigBlackWaiting");

	var myAjax=new Ajax.Request(urlAjax,	
	{
		method:'get', 
		onSuccess: function(transport)
		{
			var json=transport.responseText.evalJSON();
			if (json.result=="OK") 
			{
				try
				{	
					ponDatosCesta(json.url, json.basket);
					$(document.body).stopWaiting();
				}
				catch(err)
				{
					$(document.body).stopWaiting();
				}
			}
			else 
			{
				// error
				if (json.error) 
				{
					try
					{
						alert(json.error);
					}
					catch(err)
					{
						$(document.body).stopWaiting();
					}
				}
				if (json.url!=undefined) location.href=json.url;
				$(document.body).stopWaiting();
			}
		},
		onFailure: 	function ()	// ERROR CONTROL
		{
			$(document.body).stopWaiting();
		}
	});
}

function registraMemberChatSession(url)
{
	$(document.body).startWaiting('bigBlackWaiting');

	// nueva llamada Ajax para registrar el acceso de un socio al Chat
	var myAjax=new Ajax.Request(url+"&action=registerMemberChatSession",
	{
		method:'get', 
		onSuccess: function(transport)
		{
			var json=transport.responseText.evalJSON();
			if (json.result=="OK") 
			{
				try
				{	
					$(document.body).stopWaiting();
				}
				catch(err)
				{
					$(document.body).stopWaiting();
				}
			}
			else 
			{
				// error
				if (json.error) 
				{
					try
					{
						alert(json.error);
					}
					catch(err)
					{
						$(document.body).stopWaiting();
					}
				}
				if (json.url!=undefined) location.href=json.url;
				$(document.body).stopWaiting();
			}
		},
		onFailure: 	function ()	// ERROR CONTROL
		{
			$(document.body).stopWaiting();
		}
		
	});
}
