
/* pagos2.js */
// Funcion para obtener el contacto seleccionado
function asignaContactId(){
	//si DRIVE esta habilitado
	if($('domicHab').type=='radio') {
		if ($('domicHab').checked){
			$('campoContactInfo').value = $('domicHab').value;
		}else if ($('recogHiper').checked){
			$('campoContactInfo').value = $('recogHiper').value;
		}
	}
	if($('domicHab').type=='hidden') {
		$('campoContactInfo').value = $('domicHab').value;
	}
}

//primero limpia todas las franjas, para que no quede ninguna seleccionada
// y luego marca la franja seleccionada
var sigue="false";
function activarFranjas(id, precio, col, fil, tab){
	sigue="true";
	for(tabla=1;tabla<=tab;tabla++){
	    for (i=1; i<=fil; i++){
		    for (j=1; j<=col; j++){
		        var capa = $("celda_" + tabla + "_" + i + "_" + j);
		       // alert(("celda_" + tabla + "_" + i + "_" + j));
		        if(capa!=null){
		        	capa.style.backgroundColor="#FFFFFF";
		        }
	        }
		}
	}
    var capa = $(id);
    capa.style.backgroundColor="#DCDCDC";

    $('pagos').value = precio;
}

//Comprueba que tiene marcada alguna franja horaria
var msgFranja='';
var msgAusencia='';

function irAPaso2(){
	if(!$("vecino").checked){
		if(sigue=="true"){
	    	asignaContactId();
			$("siguiente").click();
		}else{
			alert(msgFranja);
		}
	}else{
		if($("ausencia").value==''){
			alert(msgAusencia);
		}else{
			if(sigue=="true"){
		    	asignaContactId();
		    	$('entregaVecino').value = $('ausencia').value;
				$("siguiente").click();
			}else{
				alert(msgFranja);
			}
		}
	}
}
//asigna el codigo postal del radio button seleccionado, para calcular los datos en base a este codigo postal
//asignamos la tienda para pasarla por la request a los diferentes action y droplet de la pagina
function asignarCodigoPostal(form,shipTo, nuevoTiendaId,nuevoCodPostal, path)
{
	$('newCodigoPostal').value =nuevoCodPostal;
	$('ship').value =shipTo;
	$('tienda').value =nuevoTiendaId;
	$('tiendaId').value =nuevoTiendaId;
	$('urlRedirect').value =path;
	//$('tramoSiguiente').value=0;
	$('tramoSigAnt').value = ""; //al cambiar de direccion, ponemos tramoSigAnt a "" pq no hemos pinchado ni en Anterior ni Siguiente
	form.submit();
}

function checkCambiaDireccion(msgConfirm){
	if(confirm(msgConfirm)){
		//Al presionar en aceptar
		return true;
	}
	//cambiados rb1 por tipoEntregaOtroDomicilio
	//y rb2 por recogHiper
	var radio1=$('domicHab');
    var radio2=$('recogHiper');
	if (radio1.checked)
	{
		radio2.checked='checked';
	}
	else
	{
		radio1.checked='checked';
	}
	//Al presionar en cancelar
	return false;
}



//comprueba si ha habido cambio de tienda cuando se ha cambiado de codigo postal
//si elije que si que cambia de tienda, ejecutamos el cambio de tienda y el cambio de radio button
function cambioTienda(form,path,cambioTienda,shipTo, nuevoTiendaId, nuevoCodPostal, indisponibles,msg1,msg2,msgQuestion)
{
	var radio1=$('domicHab');
    var radio2=$('recogHiper');
	var articulos='';
	var msgConfirm;
	if (indisponibles!='')
	{
		//preparamos la lista de los nombres
		var productsNames = indisponibles.split(",");
		var numProducts = productsNames.length;
		//var listaNames=new Array(numProducts);

		for (i=0;i<productsNames.length;i++)
		{
			var prod = productsNames[i];
			if (i==0)
			{
				var name= prod.split("[");
				prod = name[1];
			}
			if (i==numProducts-1)
			{
				var name= prod.split("]");
				prod = name[0];
			}
			articulos= articulos + '\n' + prod;
		}
		msgConfirm =msg1+msg2+articulos+'\n'+msgQuestion;
	}
	else
	{
		msgConfirm =msg1+' '+msgQuestion;
	}
	if (cambioTienda=='true')
	{
		//devuelve un valor a la funcion returnConfirmado
		if(checkCambiaDireccion(msgConfirm))
		{
			//actualizamos el shipTo
			asignarCodigoPostal(form,shipTo, nuevoTiendaId, nuevoCodPostal, path);
		}
	}
	else
	{
		//actualizamos el shipTo
		asignarCodigoPostal(form,shipTo, nuevoTiendaId, nuevoCodPostal, '');
		if(radio1.checked)
		{
			radio2.checked='checked';
		}
		else
		{
			radio1.checked='checked';
		}
	}
}


//cambia la fecha de inicio de las franjas horarias
function tramoSiguiente(tienda)
{
	$('tienda').value = tienda;
	$('tiendaId').value = tienda;
	$('tramoSigAnt').value = 1;
	var paginaActual = parseInt($('paginaActual').value);
	if(isNaN(paginaActual))
	{
		paginaActual = 1;
	}
	else
	{
		paginaActual = paginaActual + 1;
	}
	$('paginaActual').value = paginaActual;
	$('paso1').submit();
}
//cambia la fecha de inicio de las franjas horarias
function tramoAnterior(tienda)
{
	$('tienda').value = tienda;
	$('tiendaId').value = tienda;
	$('tramoSigAnt').value = 0;
	var paginaActual = parseInt($('paginaActual').value);
	if(isNaN(paginaActual))
	{
		paginaActual = 0;
	}
	else
	{
		paginaActual = paginaActual - 1;
	}
	$('paginaActual').value = paginaActual;
	$('paso1').submit();
}

function asingFranja(pId, pDate, pInihour, pEndhour, pDelivery, pStatus,pfechaSel)
{
	$('timeSlotId').value = pId;
	$('timeSlotIniHour').value = pInihour;
	$('timeSlotEndHour').value = pEndhour;
	$('timeSlotDeliveryAmount').value = pDelivery;
	$('timeSlotDate').value = pDate;
	$('timeSlotStatus').value = pStatus;
	$('timeSlotId2').value = pId;
	$('fechaSel').value = pfechaSel;
	//EVOLUTIVO I $('enlaceSiguiente').style.display = 'block';
}

///////PROCESO DE PAGO 02
//funcion q comprueba si ha sido desmarcada la opcion de aceptar las condiciones de pago
function aceptoCondiciones(msgAccept){
	if(!$('aceptoCondPago').checked){
		alert(msgAccept);
	}else{
		$('botonPago').click();
	}
}


/*
	Función que actualiza el estado de uso de una promocion
*/
function usePromotion(promoId){
	if ($(promoId).checked){
		new Ajax.Request("/alimentacion/EnablePromotion.aspx",
			{
				parameters: {"promoId": promoId, "enable": "yes"},
				method: 'GET'
			}
		);
	}else{
		new Ajax.Request("/alimentacion/EnablePromotion.aspx",
			{
				parameters: {"promoId": promoId, "enable": "no"},
				method: 'GET'
			}
		);
	}
}

function usaPromocionEmple(orderId){
	if ($('descEmpl').checked){
		new Ajax.Request("/alimentacion/EnablePromocionEmpleado.aspx",
			{
				parameters: {"orderId":orderId,"enable": "yes"},
				method: 'GET'
			}
		);
	}else{
		new Ajax.Request("/alimentacion/EnablePromocionEmpleado.aspx",
			{
				parameters: {"orderId":orderId,"enable": "no"},
				method: 'GET'
			}
		);
	}
}


/*
  Engloba el funcionamiento de la activacion y asignacion de franja horaria,
  y el paso automatico al siguiente paso de pago */
function nuevaSeleccionFranjas(idCelda, precio, col, fil, tab, idTimeSlot, date, inihour, endhour, delivery, status, fechaSel, msgFranja, msgAusencia) {
	/*var nuevaDireccionId='';
	nuevaDireccionId=$('driverSelect').options[$('driverSelect').selectedIndex].value;
	if( nuevaDireccionId == null || nuevaDireccionId==""){
		alert($("mensajeErrorTipoEntrega").getValue());
		return;
	}*/
	//activar franjas
	activarFranjas(idCelda, precio, col, fil, tab);
	//asignar franja
	asingFranja(idTimeSlot, date, inihour, endhour, delivery, status, fechaSel);

	irAPaso2();

	asignaContactId();
}

var messageNoServicio;
var messageErrorConsulta;
var msgConfirmCambioDireccion1;
var msgConfirmCambioDireccion2;
var msgConfirmCambioDireccion3;
function cambiarDireccion(formulario, campo, path) {

	var campoSeleccionadoId=campo.id;
	var nuevaDireccionId='';
	var tipoEntrega='';
	if(campoSeleccionadoId=='domicHab') {
		tipoEntrega=campo.value;
		nuevaDireccionId=$('shipToDireccionSelect').options[$('shipToDireccionSelect').selectedIndex].value;
	} else if(campoSeleccionadoId=='recogHiper') {
		tipoEntrega=campo.value;
		nuevaDireccionId=$('driverSelect').options[$('driverSelect').selectedIndex].value;
		if( nuevaDireccionId == null || nuevaDireccionId==""){
			alert($("mensajeErrorTipoEntrega").getValue());
			$('divFranjas').hide();
			if($("tituloFranjas")!=null) {
				$("tituloFranjas").hide();
			}
			$('divErrorSeleccioneHiper').show();
			return;
		}
	} else if(campoSeleccionadoId=='shipToDireccionSelect') {
		$('domicHab').checked=true;
		tipoEntrega=$('domicHab').value;
		nuevaDireccionId=campo.options[campo.selectedIndex].value;

	} else if(campoSeleccionadoId=='driverSelect') {
		$('recogHiper').checked=true;
		tipoEntrega=$('recogHiper').value;
		nuevaDireccionId=campo.options[campo.selectedIndex].value;
	}

	if(tipoEntrega!='') {
		var idPedido=$('orderId').value;
		var params = "tipoEntrega="+tipoEntrega+"&nuevaDireccion="+nuevaDireccionId+"&orderId="+idPedido+"&originContextPath="+path;
		msgError="NO existe el recurso solicitado";
		new Ajax.Request('/alimentacion/CheckDisponibilidad.aspx',{
			method : 'post',
			postBody : params,
			onSuccess : respuestaCheckDisponibilidad,
			on404:function(transport){
		     alert(msgError);
			  }
		});
	}

}

function respuestaCheckDisponibilidad(transport) {
	var datos = eval('('+transport.responseText+')');
	var seguir=false;

	if(datos.errorMessageType!=null) {
		if(datos.errorMessageType=='NO_SERVICIO') {
			alert(messageNoServicio);
		}
		if(datos.errorMessageType=='ERROR_CONSULTA') {
			alert(messageErrorConsulta);
		}
	} else {
		 if(datos.differentTienda == 'true'){
			if(datos.indisponiblesNames!=null) {
				var articulos='';
				var productsNames=datos.indisponiblesNames;
				for (i=0;i<productsNames.length;i++) {
					var prod = productsNames[i];
					articulos= articulos + '\n\t* ' + prod;
				}


				seguir=confirm(msgConfirmCambioDireccion1+msgConfirmCambioDireccion2+articulos+'\n'+msgConfirmCambioDireccion3);
			} else {
				seguir=confirm(msgConfirmCambioDireccion1+' '+msgConfirmCambioDireccion3);
			}
		}else{
		 	seguir = true;
		}
	}
	if(seguir) {
		if(datos.tipoEntrega=='DRIVE') {
			$('recogHiper').checked=true;
		} else {
			$('domicHab').checked=true;
		}
		//ocultar las franjas durante el cambio de tienda
		if( $('divFranjas') != null && $('tituloFranjas') != null ){
			$('divFranjas').hide();
			$('tituloFranjas').hide();
		}
		nuevoAsignarCodigoPostal($('paso1'),datos.tipoEntrega, datos.selectedTiendaId, datos.selectedPostalCode, datos.originContextPath);
	} else {
		$('paso1').reset();
		$('divFranjas').show();
		if($("tituloFranjas")!=null) {
			$("tituloFranjas").show();
		}
		$('divErrorSeleccioneHiper').hide();
	}
}

//asigna el codigo postal del radio button seleccionado, para calcular los datos en base a este codigo postal
//asignamos la tienda para pasarla por la request a los diferentes action y droplet de la pagina
function nuevoAsignarCodigoPostal(formulario,tipoEntrega, nuevoTiendaId,nuevoCodPostal, path) {
	$('newCodigoPostal').value =nuevoCodPostal;
	$('userpostalcode').value =nuevoCodPostal;
	$('tienda').value =nuevoTiendaId;
	$('tiendaId').value =nuevoTiendaId;
	$('urlRedirect').value =path;
	$('tramoSigAnt').value = ""; //al cambiar de direccion, ponemos tramoSigAnt a "" pq no hemos pinchado ni en Anterior ni Siguiente
	formulario.submit();
}


// Funciones previas al proceso de pago 2
function preSubmit2(form)
{
	//Valida rb aceptar Ofertas
	if (validaRbRecibirOfertas(form)==false){
		return false;
	}

	if (validaRbCederEmail(form)==false){
		return false;
	}
	return true;
}

/* normalizacion.js */

var address;
var candidato = false;

// Funciones que marcan si el elemento seleccionado es candidato o normalizado
function seleccionCandidato()
{
	candidato = true;
}
function seleccionNormalizado()
{
	candidato = false;
}

// En el caso de que el elmento seleccionado sea un candidato se obtiene la informacion faltante.
function obtenerInfoCandidato(addressId)
{
	if (candidato)
	{
		if (address == "billingAddress")
		{
			params = { "address": "billingAddress",
				   "billingAddress.routeType": $('routeType').value,
	 			   "billingAddress.address1" : $('address1').value,
	 			   "billingAddress.address2" : $('address2').value,
	 			   "billingAddress.city" : $('city').value,
	 			   "billingAddress.postalCode" : $('postalCode').value,
	 			   "billingAddress.province" : $('province').value
	 			 };
		}
		else
		{
			params = { "address" : "shippingAddress",
				   "shippingAddress.routeType": $('TipoVia').value,
	 			   "shippingAddress.address1" : $('NombreVia').value,
	 			   "shippingAddress.address2" : $('numero').value,
	 			   "shippingAddress.city" : $('localidad').value,
	 			   "shippingAddress.postalCode" : $('codPostal').value,
	 			   "shippingAddress.province" : $('provincia').value
	 			 };
		}

		new Ajax.Request("NormalizarDireccion.aspx",{
				parameters: params,
				onSuccess: mostrarRespuesta,
				onFailure: mostrarRespuesta
			});
	}else{
		if(address == "billingAddress"){
			// var text = $('routeType').value+" "+$('address1').value+" "+$('address2').value+","+$('city').value+"."+$('postalCode').value+","+$('province').value;
			var text = buildTextBillingAddress();
			addOptionSelectDirecciones(text,address,"billingAddressId");
		}else if (address == "shippingAddress"){
			//var text = $('TipoVia').value+" "+$('NombreVia').value+" "+$('numero').value+","+$('localidad').value+"."+$('codPostal').value+","+$('provincia').value;
			var text = buildTextShippingAddress();
			addOptionSelectDirecciones(text,address,"secondaryAddressId");
		}
	}
}

function validateAddress(addressId, msgErrorTlfn, msgOblFields)
{
	if(validarCamposObligatoriosDir(addressId,msgErrorTlfn,msgOblFields))
	{
		if (addressId == "billingAddress")
		{
			if( $('fromModificarCuenta') ) {
				params = { "address": "billingAddress",
					   "billingAddress.routeType": $('routeType').value,
		 			   "billingAddress.address1" : $('address1').value,
		 			   "billingAddress.address2" : $('address2').value,
		 			   "billingAddress.city" : $('city').value,
		 			   "billingAddress.postalCode" : $('postalCode').value,
		 			   "billingAddress.province" : $('province').value,
		 			   "from" : $('fromModificarCuenta').value
		 			 };
		 	} else {
		 		params = { "address": "billingAddress",
					   "billingAddress.routeType": $('routeType').value,
		 			   "billingAddress.address1" : $('address1').value,
		 			   "billingAddress.address2" : $('address2').value,
		 			   "billingAddress.city" : $('city').value,
		 			   "billingAddress.postalCode" : $('postalCode').value,
		 			   "billingAddress.province" : $('province').value
		 			 };
		 	}
	 		address = "billingAddress";
		}
		else
		{
			if( $('fromModificarCuenta') ) {
				params = { "address" : "shippingAddress",
					   "shippingAddress.routeType": $('TipoVia').value,
		 			   "shippingAddress.address1" : $('NombreVia').value,
		 			   "shippingAddress.address2" : $('numero').value,
		 			   "shippingAddress.city" : $('localidad').value,
		 			   "shippingAddress.postalCode" : $('codPostal').value,
		 			   "shippingAddress.province" : $('provincia').value,
		 			   "from" : $('fromModificarCuenta').value
		 			 };
		 	}else{
		 		params = { "address" : "shippingAddress",
					   "shippingAddress.routeType": $('TipoVia').value,
		 			   "shippingAddress.address1" : $('NombreVia').value,
		 			   "shippingAddress.address2" : $('numero').value,
		 			   "shippingAddress.city" : $('localidad').value,
		 			   "shippingAddress.postalCode" : $('codPostal').value,
		 			   "shippingAddress.province" : $('provincia').value
		 			 };
		 	}
	 		address = "shippingAddress";
		}

		new Ajax.Request("NormalizarDireccion.aspx",{
				parameters: params,
				onSuccess: mostrarRespuesta,
				onFailure: mostrarRespuesta
			});
	}
}

function mostrarRespuesta(transport)
{
	if (transport.responseText != null)
	{
		if (transport.responseText.indexOf("<!-- Home -->") > 0){
			document.location="/alimentacion/HomeAlimentacion.aspx";
		}
		else{
			if($('optionBlank')){
				$('optionBlank').remove();
			}
			if(address == "billingAddress")
			{
				var sugerencias = $('direccionesAlternativas');
				sugerencias.update(transport.responseText);
				sugerencias.style.display='block';
				if(transport.responseText.indexOf("selectDireccionesAlternativas") == -1 &&
				   transport.responseText.indexOf("novalidation") == -1 ) {
					// var text = $('routeType').value+" "+$('address1').value+" "+$('address2').value+","+$('city').value+"."+$('postalCode').value+","+$('province').value;
					var text =	buildTextBillingAddress();
					addOptionSelectDirecciones(text,address,"billingAddressId");
				}
			}
			else if (address == "shippingAddress")
			{
				var sugerencias_dos = $('direccionesAlternativas_dos');
				sugerencias_dos.update(transport.responseText);
				sugerencias_dos.style.display='block';
				if(transport.responseText.indexOf("selectDireccionesAlternativas") == -1 &&
				   transport.responseText.indexOf("novalidation") == -1 ) {
					//var text = $('TipoVia').value+" "+$('NombreVia').value+" "+$('numero').value+","+$('localidad').value+"."+$('codPostal').value+","+$('provincia').value;
					var text = buildTextShippingAddress();
					addOptionSelectDirecciones(text,address,"secondaryAddressId");
				}
			}

		}
	}
}


function activaBoton(){
	$('botonNormalizar').disabled = false;
}

function ocultaSugerencias()
{
	//A Borrar:
	//selectDireccionesAlternativas o
	//imgCheto o
	//novalidation
	if ($('selectDireccionesAlternativas') != null)
	{
		$('selectDireccionesAlternativas').remove();
	}
	else if($('imgCheto') != null)
	{
		$('imgCheto').remove();
	}
	else if($('novalidation') != null)
	{
		$('novalidation').remove();
	}

	if(address == "billingAddress")
	{
		$('direccionesAlternativas').style.display='none';
	}
	else if (address == "shippingAddress")
	{
		$('direccionesAlternativas_dos').style.display='none';
	}
}

// Funcion que dependiendo del candidato seleccionado actualiza la direccion
function seleccionarCandidato(tipoVia, denomOficialVia, numVia, codPost, denomOficialPob, indiceFiab, coordX, coordY,seccionCensal)
{

	if (address == "billingAddress")
	{
		if (tipoVia != null && tipoVia != "") {
	       	$('routeType').value = tipoVia;
       	}
		if (denomOficialVia != null && denomOficialVia != "") {
			$('address1').value = denomOficialVia;
		}
		if (numVia != null && numVia != "") {
			$('address2').value = numVia;
		}
		if (codPost != null && codPost != "") {
			$('postalCode').value = codPost;
		}
		if (denomOficialPob != null && denomOficialPob != "") {
			$('city').value = denomOficialPob;
		}
		$('normalized').value = indiceFiab;
		$('coordX').value = coordX;
		$('coordY').value = coordY;
		$('seccionCensal').value = seccionCensal;
	}
	else
	{
		if (tipoVia != ""){
			$('TipoVia').value = tipoVia;
		}
		if (denomOficialVia != null && denomOficialVia != "") {
			$('NombreVia').value = denomOficialVia;
		}
		if (numVia != null && numVia != "") {
			$('numero').value = numVia;
		}
		if (codPost != null && codPost != "") {
			$('codPostal').value = codPost;
		}
		if (denomOficialPob != null && denomOficialPob != "") {
			$('localidad').value = denomOficialPob;
		}
		$('normalizedSec').value = indiceFiab;
		$('coordXsec').value = coordX;
		$('coordYsec').value = coordY;
		$('seccionCensalSec').value = seccionCensal;
	}
}

// Funcion que dependiendo del candidato (de 3 campos) seleccionado actualiza la direccion
function seleccionarResto(codPost, litPoblacion, resto, indiceFiab, coordX, coordY,seccionCensal )
{
	if (address == "billingAddress")
	{
		$('postalCode').value = codPost;
		$('city').value = litPoblacion;
		$('address1').value = resto;
		$('normalized').value = indiceFiab;
		$('coordX').value = coordX;
		$('coordY').value = coordY;
		$('seccionCensal').value = seccionCensal;
	}
	else if (address == "shippingAddress")
	{
		$('codPostal').value = codPost;
		$('localidad').value = litPoblacion;
		$('NombreVia').value = resto;
		$('normalizedSec').value = indiceFiab;
		$('coordXsec').value = coordX;
		$('coordYsec').value = coordY;
		$('seccionCensalSec').value = seccionCensal;
	}
}

// Actualiza los indices de fiabilidad y coordenadas cuando la direccion no esta validada
function noValidada(indiceFiab, coordX, coordY,seccionCensal)
{
	if (address == "billingAddress")
	{
		$('normalized').value = indiceFiab;
		$('coordX').value = coordX;
		$('coordY').value = coordY;
		$('seccionCensal').value = seccionCensal;
	}
	else if (address == "shippingAddress")
	{
		$('normalizedSec').value = indiceFiab;
		$('coordXsec').value = coordX;
		$('coordYsec').value = coordY;
		$('seccionCensalSec').value = seccionCensal;
	}
}

function normalizaDireccion(routeType, address1,address2, city, province, postalCode, indiceFiab, coordX, coordY,seccionCensal)
{

	//Para que no salga el marco rojo.
	$('direccionesAlternativas').removeClassName('divDireccionesAlternativas');
	if(address == "billingAddress")
	{
		if(routeType != "")
		{
			$('routeType').value = routeType;
		}
		else
		{
			$('routeType').value = "CALLE";
		}

		$('address1').value = address1;
		if($('address2').value != "")
		{
			$('address2').value = address2;
		}
		$('city').value = city;
		if(province != "")
		{
			$('province').value = province;
		}
		$('postalCode').value = postalCode;
		$('normalized').value = indiceFiab;
		$('coordX').value = coordX;
		$('coordY').value = coordY;
		$('seccionCensal').value = seccionCensal;
	}
	else if (address == "shippingAddress")
	{
		if(routeType != "")
		{
			$('TipoVia').value = routeType;
		}
		else
		{
			$('TipoVia').value = "CALLE";
		}
		$('NombreVia').value = address1;
		if($('numero').value != "")
		{
			$('numero').value = address2;
		}
		$('localidad').value = city;
		if(province != "")
		{
			$('provincia').value = province;
		}
		$('codPostal').value = postalCode;
		$('normalizedSec').value = indiceFiab;
		$('coordXsec').value = coordX;
		$('coordYsec').value = coordY;
		$('seccionCensalSec').value = seccionCensal;
	}
	$('direccionesAlternativas').addClassName('divDireccionesAlternativas');
}

function deshabilitar(address)
{
	if(address == "billingAddress")
	{
		$('routeType').disabled = true;
		$('address1').disabled = true;
		$('address2').disabled = true;
		$('urbanization').disabled = true;
		$('block').disabled = true;
		$('stairs').disabled = true;
		$('floor').disabled = true;
		$('door').disabled = true;
		$('city').disabled = true;
		$('province').disabled = true;
		$('postalCode').disabled = true;
		$('phoneNumber').disabled = true;
		$('phoneNumber2').disabled = true;
		$('infoForTransporter').disabled = true;
		var btnValidar1 = $('btnValidar1');
		btnValidar1.disabled = true;
		btnValidar1.className ="botonAzulDes";
	}
	else
	{
		$('TipoVia').disabled = true;
		$('NombreVia').disabled = true;
		$('numero').disabled = true;
		$('urbanizacion').disabled = true;
		$('bloque').disabled = true;
		$('escalera').disabled = true;
		$('piso').disabled = true;
		$('puerta').disabled = true;
		$('localidad').disabled = true;
		$('provincia').disabled = true;
		$('codPostal').disabled = true;
		$('telefono').disabled = true;
		$('telefono2').disabled = true;
		$('infoParaRepartidor').disabled = true;
		var btnValidar2 = $('btnValidar2');
		btnValidar2.disabled = true;
		btnValidar2.className ="botonAzulDes";
	}
}

function habilitar()
{
	if(address == "billingAddress")
	{
		$('routeType').disabled = false;
		$('address1').disabled = false;
		$('address2').disabled = false;
		$('urbanization').disabled = false;
		$('block').disabled = false;
		$('stairs').disabled = false;
		$('floor').disabled = false;
		$('door').disabled = false;
		$('city').disabled = false;
		$('province').disabled = false;
		$('postalCode').disabled = false;
		$('phoneNumber').disabled = false;
		$('phoneNumber2').disabled = false;
		$('infoForTransporter').disabled = false;
	}
	else if (address == "shippingAddress")
	{
		$('TipoVia').disabled = false;
		$('NombreVia').disabled = false;
		$('numero').disabled = false;
		$('urbanizacion').disabled = false;
		$('bloque').disabled = false;
		$('escalera').disabled = false;
		$('piso').disabled = false;
		$('puerta').disabled = false;
		$('localidad').disabled = false;
		$('provincia').disabled = false;
		$('codPostal').disabled = false;
		$('telefono').disabled = false;
		$('telefono2').disabled = false;
		$('infoParaRepartidor').disabled = false;
	}
	$('checkSecondAddress').disabled = false;
}

// funcion que comprueba antes de normalizar la dir que todos los campos obligatorios se han introducido
function validarCamposObligatoriosDir(addressId,msgErrorTlfn,msgOblFields)
{
	address = addressId;
	if (addressId == "billingAddress")
	{
		if($('routeType').value != "" &&
			$('address1').value != "" &&
			$('address2').value != "" &&
			$('city').value != "" &&
			$('province').value != "" &&
			$('postalCode').value != "")
		{
 			if(!esCodigoPostal($('postalCode').value))
 			{
 				alert(msgOblFields);
 				habilitar();
				habilitarValidacion("billingAddress");
 				return false;
 			}
 			if(!esTelefono($('phoneNumber').value))
 			{
 				alert(msgErrorTlfn);
 				habilitar();
				habilitarValidacion("billingAddress");
 				return false;
 			}
	 		if(document.getElementById('phoneNumber2').value != "")
	 		{
	 			if(!esTelefono($('phoneNumber2').value))
	 			{
	 				alert(msgErrorTlfn);
	 				habilitar();
					habilitarValidacion("billingAddress");
	 				return false;
	 			}
	 		}
	 		return true;
		}
		else
		{
			alert(msgOblFields);
			address = addressId;
			habilitar();
			habilitarValidacion("billingAddress");
			return false;
		}
	}

	if (addressId == "shippingAddress")
	{
		if($('TipoVia').value != "" &&
			$('NombreVia').value != "" &&
			$('numero').value != "" &&
			$('localidad').value != "" &&
			$('provincia').value != "" &&
			$('codPostal').value != "")
		{
 			if(!esCodigoPostal($('codPostal').value))
 			{
 				alert(msgOblFields);
 				habilitar();
				habilitarValidacion("shippingAddress");
 				return false;
 			}
	 		if(!esTelefono(document.getElementById('telefono').value))
	 		{
	 			alert(msgErrorTlfn);
				habilitar();
				habilitarValidacion("shippingAddress");
	 			return false;
	 		}
		 	if(document.getElementById('telefono2').value != "")
		 	{
		 		if(!esTelefono(document.getElementById('telefono2').value))
		 		{
		 			alert(msgErrorTlfn);
					habilitar();
					habilitarValidacion("shippingAddress");
		 			return false;
		 		}
		 	}
	 		return true;
		}
		else
		{
			alert(msgOblFields);
			address = addressId;
			habilitar();
			habilitarValidacion("shippingAddress");
			return false;
		}
	}
}

function compruebaServicio()
{
	if (address == "billingAddress")
	{
		var postalCode = $('postalCode').value;
		params = {"postalCode" : postalCode };
	}
	else
	{
		var postalCode = $('codPostal').value;
		params = {"postalCode" : postalCode };
	}

	new Ajax.Updater('popup','/alimentacion/ComprobarServicio.aspx',
			{
				parameters : params
			}
		)
}


function habilitaBotonValidacion()
{
	if (address == "billingAddress")
	{
		$('checkSecondAddress').disabled = true;
		var btnValidar1 = $('btnValidar1');
		btnValidar1.disabled = false;

		btnValidar1.className = "botonAzul";
	}
	else
	{
		var btnValidar2 = $('btnValidar2');
		btnValidar2.disabled = false;

		btnValidar2.className = "botonAzul";
	}
}

function addOptionSelectDirecciones(text,value,id){
	if($(id)){
		$(id).text = text;
	}else{
		var selectDirecciones = $('shipToDireccionSelect');
		var optn = document.createElement("OPTION");
	    optn.text = text;
	    optn.value = value;
	    optn.id = id;
	    selectDirecciones.options.add(optn);
	}
}



function buildTextBillingAddress(){
	var text = "";
	if($('routeType').value != ""){text = text + $('routeType').value+" ";}
	if($('address1').value != ""){text = text + $('address1').value+" ";}
	if($('address2').value != ""){text = text + $('address2').value+", ";}
	if($('floor').value != "" ){text = text + $('floor').value+" ";}
	if($('door').value != ""){text = text + $('door').value+". ";}
	if($('urbanization').value != ""){text = text + $('urbanization').value+". ";}
	if($('city').value != ""){text = text + $('city').value+", ";}
	if($('postalCode').value != ""){text = text + $('postalCode').value;}
	// alert(text);
	return text;
}

function buildTextShippingAddress(){
    var text = "";
    if($('TipoVia').value != "" ){text = text + $('TipoVia').value +" ";}
    if($('NombreVia').value != ""){text = text + $('NombreVia').value+" ";}
    if($('numero').value != ""){text = text + $('numero').value+", ";}
    if($('piso').value != "" ){ text = text + $('piso').value+" ";}
    if($('puerta').value != ""){ text = text + $('puerta').value+". ";}
    if($('urbanizacion').value != ""){text = text + $('urbanizacion').value+". ";}
	if($('localidad').value != ""){text = text + $('localidad').value+", ";}
	if($('codPostal').value != ""){text = text + $('codPostal').value;}
	// alert(text);
	return text;
}

/*registro.js*/

// Variable que marca si la todas las direcciones han sido validadas
var validacionDirOk = true;

//Se actualiza la variable de validacion de direcciones a NO validada
function dirNoValidada()
{
	validacionDirOk = false;
}

//Se actualiza la variable de validacion de direcciones
function dirValidada()
{
	validacionDirOk = true;
}

//Se valida la opcion de segunda direccion para habilitar los botones apropiados
function validarSecondAddress(option)
{
	if (!option.checked)
	{
		dirValidada();
	}
}

//Se inicializa la variable de validacion dependiendo de si existe direccion previa o no
function inicializacionRegistro()
{
	if ($('routeType').value != null && $('routeType').value != "")
	{
		dirValidada();
	}
	else
	{
		dirNoValidada();
	}
}

/*Se deshabilita la fila fiscal y pedido en caso de seleccionar la check de particular*/
function deshabilitarEmpresa()
{
    $('filaFiscal1').style.display = 'none';
    $('filaFiscal2').style.display = 'none';
    $('divFPedido').style.display = 'none';
    if($('errorTextoFiscal')!=null)
    {
    	$('errorTextoFiscal').style.display = 'none';
    }
}

/*Se habilita la fila fiscal y pedido en caso de seleccionar la check de empresa*/
function habilitarEmpresa()
{
    $('filaFiscal1').style.display = 'block';
    $('filaFiscal2').style.display = 'block';
    $('divFPedido').style.display = 'block';
    if($('errorTextoFiscal')!=null)
    {
    	$('errorTextoFiscal').style.display = 'block';
    }
}

//Solo se muestra la fila de amigo si esta seleccionado dicho valor en el combo
function mostrarAmigo()
{
    var indice = $('selectAmigo').selectedIndex
    var selec = $('selectAmigo');
    var texto = selec.options[indice].value;
    if(texto == 'Amigo')
    {
       $('filaAmigo1').style.display = 'block';
       $('filaAmigo2').style.display = 'block';
       if($('friendEmailError')!=null)
       {
       		$('friendEmailError').style.display = 'block';
       }
    }
    if(texto != 'Amigo')
    {
       $('filaAmigo1').style.display = 'none';
       $('filaAmigo2').style.display = 'none';
       if($('friendEmailError')!=null)
       {
       		$('friendEmailError').style.display = 'none';
       }
    }
}

//Se cambiar el titulo de direccion en funcion de si esta o no marcada la check de segunda direccion
function cambiarTituloDireccion(msg1,msg2)
{
    var check = $('checkSecondAddress');
    var texto = $('textoDireccion');
    if(check.checked == true)
    {
		texto.update(msg1);
    }
    else
    {
		texto.update(msg2);
    }
}

function habilitarDeshabDirecc()
{
	var check = $('checkSecondAddress');
	var titulo = $('tituloDireccionEntrega');
	var linea = $('lineaSeparadorDireccionEntrega');
	if(check.checked == true)
    {
        titulo.style.display = 'block';
        linea.style.display = 'block';
    }
    else
    {
        titulo.style.display = 'none';
        linea.style.display = 'none';
    }
}

// Al hacer click en el boton Aceptar se comprueba que las direcciones han sido validadas
function checkDirValid(msgNotValidated)
{
	if(validacionDirOk == false)
	{
		alert(msgNotValidated);
	}
}

// Funciones previas al submit de registro
function preSubmit(form)
{
	// Si no se han validado todas las direcciones, no se realiza el submit
	if(validacionDirOk == false)
	{
		return false;
	}

	//Valida rb aceptar Ofertas
	if (validaRbRecibirOfertas(form)==false){
		return false;
	}

	if (validaRbCederEmail(form)==false){
		return false;
	}

	// formamos el numero de ClubCarrefour
	$('clubCard').value = $('clubCard1').value + $('clubCard2').value;

	// formamos la fecha de nacimiento y la validamos para formularioParticular
	var fecha;
	if(($("dd").value == "") || ($("mm").value == "") || ($("aaaa").value == ""))
	{
		$("dateOfBirth").value='';
	}
	else
	{
   		fecha = $("dd").value + '/' + $("mm").value + '/' + $("aaaa").value;
   		var fechaTrue = esFecha(fecha);
   		if(fechaTrue)
   		{
			$("dateOfBirth").value = fecha;
		}
		else
		{
			$("dateOfBirth").value='';
		}
	}
	return true;
}

function habilitarValidacion(addressId)
{
	if (addressId == "billingAddress")
	{
		$('checkSecondAddress').disabled = true;
		var btnValidar1 = $('btnValidar1');
		btnValidar1.disabled = false;
		btnValidar1.className="botonAzul";
	}
	else if (addressId == "shippingAddress")
	{
		var btnValidar2 = $('btnValidar2');
		btnValidar2.disabled = false;
		btnValidar2.className="botonAzul";
	}
	// Las direcciones no esta validadas
	dirNoValidada();
}

//Sugerencias para Tipos de VIA
var aTiposVia = ['PASEO', 'PASSEIG', 'PSEIG', 'AVENIDA', 'AVINGUDA', 'AVDA', 'CALLE', 'CARRER', 'CALLEJON', 'CARRERO', 'CAMINO', 'CAMI', 'CMNO', 'PASAJE', 'PJE', 'PASSATGE', 'PTGE', 'CHALET', 'XALET', 'PLAZA', 'RESIDENCIAL', 'RESIDENCIAL', 'RESID', 'GLORIETA', 'GLTA', 'CARRETERA', 'CRA', 'SENDA', 'BOULEVARD', 'CUESTA', 'PARQUE', 'PQUE', 'POLIGONO', 'POLIG', 'RAMBLA', 'RBLA', 'RONDA', 'TRAVESIA', 'TRAVESSIA', 'TRAV', 'URBANIZACION', 'URB', 'VIA', 'ZONA','PARK','AVENUE','STREET','WAY','CRESCENT','ST.','ROAD'];

function TipoViaSugerencias()
{
    this.tiposVia = aTiposVia;
}

function Arranca() {
	var oTextbox = new SugerenciasControl($("routeType"), new TipoViaSugerencias());
	var oTextbox2 = new SugerenciasControl($("TipoVia"), new TipoViaSugerencias());

	var clubCard = $("clubCard").value;
	if (clubCard != "")
	{
		$("clubCard1").value = clubCard.slice(0,9);
		$("clubCard2").value = clubCard.slice(9,14);
	}

	var fecha = $("dateOfBirth").value;
	if(fecha.value != "")
	{
		var arrayFecha = fecha.split('/');
		if(arrayFecha.length == 3){
			$("dd").value = arrayFecha[0];
			$("mm").value = arrayFecha[1];
			$("aaaa").value = arrayFecha[2];
		}
	}
	if($("rb2").checked)
	{
		habilitarEmpresa();
	}
	else
	{
		deshabilitarEmpresa();
	}
}

function simularEnter(evento){
	if (evento.keyCode == 13)
	{
		return false;
	}
}

//  ----------------------------------------------------------------------------------
//   function esFecha(fech)
//  	devuelve TRUE si la fecha que se le pasa es valida o FALSE en caso contrario
//  ----------------------------------------------------------------------------------
function esFecha(fech)
{
	var i=0;
	var z=0;
	var dia="";

	var separador1 = fech.indexOf('/');
	var resto = fech.substring(separador1+1,fech.length);
	var separador2 = resto.indexOf('/');

	if ((separador1<=0) || (separador2<=0))
	{
		return false;
	}

	while (fech.charAt(i) != '/')
	{
		dia=dia+fech.charAt(i);
		i=i+1;
	}

	var mes="";
	i=i+1;

	while (fech.charAt(i) != '/')
	{
		mes=mes+fech.charAt(i);
		i=i+1;
	}

	var anio="";
	i=i+1;

	while (fech.charAt(i) != '')
	{
		anio=anio+fech.charAt(i);
		i=i+1;
	}

	var bisiesto=false;
	if (esNumero(dia) && esNumero(mes) && esNumero(anio))
	{
		if(anio%4==0) bisiesto=true;
		if (mes>0 && mes<13)
		{
			if (dia>0 && dia<32)
			{
				if ((mes==4 || mes==6 || mes==9 || mes==11) && dia==31)
				{
					return false;
				}
				if (mes==2)
				{
					if (bisiesto && dia>29)
					{
						return false;
					}
					if (!bisiesto && dia>28)
					{
						return false;
					}
				}
			}
			else
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
	return true;
}

//  ----------------------------------------------------------------------------------
//   function esNumero(cad)
//  	devuelve TRUE si la cadena que se le pasa como parametro es un numero
//  ----------------------------------------------------------------------------------
function esNumero(cad)
{
	var ok=true;
	if (cad.length>0)
	{
		for (i=1;i<=cad.length;i++)
			if (((cad.substring(i-1,i)>"9") || (cad.substring(i-1,i)<"0")) && (cad.substring(i-1,i)!="."))
			{
				ok=false;
				break;
			}
	}
	else
		ok=false;

	if (ok)
		return true;
	else
		return false;
}

//  ----------------------------------------------------------------------------------
//   function esTelefono(cad)
//  	devuelve TRUE si la cadena que se le pasa como parametro es un numero de telefono
//  ----------------------------------------------------------------------------------
function esTelefono(cad)
{
   var ValidChars = " 0123456789.-";
   var esTelefono=true;
   var Char;
   if(cad.length != 9)
   {
   	  return false;
   }
   for (i = 0; i < cad.length && esTelefono == true; i++)
   {
	  Char = cad.charAt(i);
	  if (ValidChars.indexOf(Char) == -1)
		  esTelefono = false;
   }
   return esTelefono;
}

//  ----------------------------------------------------------------------------------
//   function esCodigoPostal(cad)
//  	devuelve TRUE si la cadena que se le pasa como parametro es un numero un Codigo Postal
//  ----------------------------------------------------------------------------------
function esCodigoPostal(cad)
{
   var ValidChars = "0123456789";
   var esCodigoPostal=true;
   var Char;
   if(cad.length != 5)
   {
   	  return false;
   }
   for (i = 0; i < cad.length && esCodigoPostal == true; i++)
   {
	  Char = cad.charAt(i);
	  if (ValidChars.indexOf(Char) == -1)
		  esCodigoPostal = false;
   }
   return esCodigoPostal;
}


//	----------------------------------------------------------------------------------
//   function checkCambiaPreferencias(oldValue,msgConfirm)
//		Muestra un mensaje de confirmacion al usuario preguntandole si esta seguro
//		de que quiere cambiar sus preferencias de sustitucion.
//
//		Solo se muestra si el valor de las preferencias cambian.
//
//	----------------------------------------------------------------------------------
function checkCambiaPreferencias(oldValue,msgConfirm)
{
	//valor seleccionado en el dropdown menu
	var newValue=$('sustitucion').value;
	//Si son distintos el valor antiguo y el cambiado, se muestra el mensaje de confirmacion.
	if (newValue != oldValue)
	{
		if(confirm(msgConfirm))
		{
			//Al presionar en aceptar
			return true;
		}
		//Al presionar en cancelar
		return false;
	}
	//Si son distintos, se devuelve true directamente
	return true;
}

function submitFromLinkRegistro(){
  var form = $('logonGuestForm');
  $('logoutSuccessURLGuest').setValue('/alimentacion/RedireccionGuestLinkRegistro.aspx')
  form.submit();
}

function fillSelectDirecciones(item){
	if(!item.checked){
	  	if( $("secondaryAddressId") ) {
			$("secondaryAddressId").remove();
		}
	}
}

/* sustPrefs.js */

function cambiaPreferencias(prodId){
	var typeId = $("select_".concat(prodId)).value;
	params = {"productId" : prodId, "typeId" : typeId };
	new Ajax.Request("ChangeSustitutionCriteria.aspx",
			{
				parameters: params,
				method: 'GET'
			}
		);
}


/* busqueda.js */

//fichero para los javascript de la zona de busquedas

//funcion que se ejecuta al realizar algun cambio de subcatalogo en el combo de busqueda
function changeCombo(url){
	subcatalogo = $('scatalog').value;
	params={"scatalog" : subcatalogo};
	new Ajax.Request(url,
	{
		parameters:params,
		method:'get'
	}
	);

}

//se ejecuta cuando presionas una tecla en el text, comprueba si es intro
//llama a compruebaTecla cuando se pulsa la tecla intro
function compruebaTecla(oEvent,url,palabra,subcatalogo){
	var iKeyCode;
	if(document.all){
		iKeyCode = oEvent.keyCode;
	}else{
		iKeyCode = oEvent.which;
	}
	if (iKeyCode == 13){
		mostrarResultados(url,palabra,subcatalogo);
	}
}
function cargandoBusqueda(mensaje)
{

	p=$('center');
	p.className="divSubhome";
	p.innerHTML = "<div>"
	+"<br/><br/><br/>"
	+"<table style='text-align:center'><tr><th>"
	+"<img src='/alimentacion/201111031215/media/es/web/imagenes/reloj_arena.gif'/></th></tr>" ;

	p.innerHTML += "<tr><th align='center'><span class='producto' style='align:center;float:center;font-weight:bold;font-size:11px;'>"
	+mensaje
	+"</span><b></b></th></tr></table> </div>" ;
}
function loadingYMostrarResultados(url,palabra,subcatalogo,mensaje){
	cargandoBusqueda(mensaje);
	mostrarResultados(url,palabra,subcatalogo);
}
//se ejecuta al realizar la busqueda desde el boton BUSCAR
function mostrarResultados(url,palabra,subcatalogo){
	var buscar = $(palabra).value;
	var scatalog = $(subcatalogo).value;

	//Guardamos el historico de navegación --BOTON VOLVER
	params = { "url" : url+"?buscar="+buscar+"&scatalog="+scatalog};
	new Ajax.Request("GuardarNavegacion.aspx",
	{
		parameters: params,
		asynchronous: false
	}
	);

	params={"buscar" : buscar, "scatalog" : scatalog};
	new Ajax.Request(url,
		{
			parameters:params,
			onSuccess:function(transport){mostrarResultadosSuccess(transport);}
		}
	);
}

function mostrarResultadosSuccess(transport){

	if (transport.responseText.indexOf("<!-- Home -->") > 0)
	{
		document.location="/alimentacion/HomeAlimentacion.aspx";
	}
	else
	{
		$('center').update(transport.responseText);
		$('center').className='';
	}
}

//funcion que se ejecuta al hacer click en Ver Mas Resultados..
function verMasResultados(url,buscar,nodo,scatalog,moreResults){
	if(nodo==''){
		nodo='null';
	}
	params={"buscar":buscar,"scatalog":scatalog,"nodo":nodo,"moreResults":moreResults};
	new Ajax.Request(url,
		{
			parameters:params,
			onSuccess: function(transport){mostrarResultadosSuccess(transport);}
		}
	);
}

//funcion que hace desaparecer el enlace de verMasResultados
function enlaceVerMasResultados(){
	$('verMas').style.display = 'none';
}

////funcion que refresca mediante Ajax cuando se hace click en el enlace de un nodo
function acotarBusqueda(url, buscar, nodo, scatalog, moreResults){
	//alert('Acotando busqueda para ' + nodo);
	//alert(' -' + buscar+' -'+nodo+' -'+scatalog+' - '+moreResults);
	params={"buscar" : buscar, "scatalog" : scatalog, "nodo" : nodo, "moreResults" : moreResults};
	new Ajax.Request(url,
		{
			parameters:params,
			onSuccess: function(transport){mostrarResultadosSuccess(transport);}
		}
	);
}

//function que realiza el refresco tras haber realizado una ordenacion
function ordenarResultadoBusqueda(url,buscar, moreResults, nodo,scatalog, sortProperties){
	if(nodo==''){
		nodo='null';
	}
	params={"buscar" : buscar, "moreResults" : moreResults, "nodo" : nodo, "scatalog" : scatalog, "sortProperties" : sortProperties};
	new Ajax.Request(url,
		{
			parameters:params,
			onSuccess: function(transport){mostrarResultadosSuccess(transport);}
		}
	);
}

//funcion que refresca mediante Ajax cuando se hace click en el enlace anterior
function paginacionBusqueda(url, pagina, nodo, scatalog, moreResults, buscar){
	if(nodo==''){
		nodo='null';
	}
	params={"pagina":pagina,"nodo":nodo,"scatalog":scatalog,"moreResults":moreResults,"buscar":buscar};
	new Ajax.Request(url,
		{
			parameters:params,
			onSuccess: function(transport){mostrarResultadosSuccess(transport);}
		}
	);
}

//funcion que refresca mediante Ajax cuando se modifica la visualizacion del listado mediante un combo
function changeVisualizationBusqueda(itemId, buscar, scatalog, nodo, moreResults) {
	var selectedOption = $('selectImagen').value;
	if(nodo==''){
		nodo='null';
	}
	params = {
				"visualizationOption" : selectedOption,
				"itemId" : itemId,
				"nodo" : nodo,
				"scatalog" : scatalog,
				"moreResults":  moreResults,
				"buscar" : buscar
			};
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			onSuccess: function(transport){showResults(transport);}
		}
	);
}

function showResults(transport){
	if (transport.responseText.indexOf("<!-- Home -->") > 0)
	{
		document.location="/alimentacion/HomeAlimentacion.aspx";
	}
	else
	{
		$('center').update(transport.responseText);
	}
}

function orderBySelectBusqueda(itemId, buscar, scatalog, nodo, moreResults){
	var orderByProp = $('sel_orden').value;
	if(nodo==''){
		nodo='null';
	}
	params = {
				"sortProperties" : orderByProp,
	 			"itemId" : itemId,
			  	"buscar" : buscar,
			  	"scatalog" : scatalog,
			  	"nodo" : nodo,
			  	"moreResults" : moreResults
			  };
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			onSuccess: function(transport){showResults(transport);}
		}
	);
}

/* compra.js */



//---------------------BUSCAR
function buscar_over()
  {
	document.buscar.src = "/alimentacion/201111031215/media/es/web/boton/buscarR.gif";
  }
function buscar_out()
  {
  	document.buscar.src = "/alimentacion/201111031215/media/es/web/boton/buscar.gif";
  }


//--------------------  DETALLE COMPRA
function detalleCompra_over()
  {
	document.detalleCompra.src = "/alimentacion/201111031215/media/es/web/boton/bt_detalleCompraRoll.gif";
  }
function detalleCompra_out()
  {
  	document.detalleCompra.src = "/alimentacion/201111031215/media/es/web/boton/bt_detalleCompra.gif";
  }


//--------------------  DESCUENTOS ACUMULADOS
function descuentosAcumulados_over()
  {
	document.descuentosAcumulados.src = "/alimentacion/201111031215/media/es/web/boton/bt_descuentosAcumuladosRoll.gif";
  }
function descuentosAcumulados_out()
  {
  	document.descuentosAcumulados.src = "/alimentacion/201111031215/media/es/web/boton/bt_descuentosAcumulados.gif";
  }


//-----------------------  GUARDAR COMPRA COMO LISTA
function guardarComoLista_over()
  {
	document.guardarComoLista.src = "/alimentacion/201111031215/media/es/web/boton/bt_guardarComoListaRoll.gif";
  }
function guardarComoLista_out()
  {
  	document.guardarComoLista.src = "/alimentacion/201111031215/media/es/web/boton/bt_guardarComoLista.gif";
  }


//--------------------------  PROXIMA ENTREGA DISPONIBLE
function proximaEntrega_over()
  {
	document.proximaEntrega.src = "/alimentacion/201111031215/media/es/web/boton/bt_proximaEntregaRoll.gif";
  }
function proximaEntrega_out()
  {
  	document.proximaEntrega.src = "/alimentacion/201111031215/media/es/web/boton/bt_proximaEntrega.gif";
  }


//--------------------------- PAGAR
function pagar_over()
  {
	document.pagar.src = "/alimentacion/201111031215/media/es/web/boton/bt_pagarRoll.gif";
  }
function pagar_out()
  {
  	document.pagar.src = "/alimentacion/201111031215/media/es/web/boton/bt_pagar.gif";
  }


//---------------------------  LISTAS PERSONALES
function listasPersonales_over()
  {
	document.listasPersonales.src = "/alimentacion/201111031215/media/es/web/boton/bt_listasPersonalesRoll.gif";
  }
function listasPersonales_out()
  {
  	document.listasPersonales.src = "/alimentacion/201111031215/media/es/web/boton/bt_listasPersonales.gif";
  }


//--------------------------- PEDIDOS ANRTERIORES
function pedidosAnteriores_over()
  {
	document.pedidosAnteriores.src = "/alimentacion/201111031215/media/es/web/boton/bt_pedidosAnterioresRoll.gif";
  }
function pedidosAnteriores_out()
  {
  	document.pedidosAnteriores.src = "/alimentacion/201111031215/media/es/web/boton/bt_pedidosAnteriores.gif";
  }

/* drive.js */

function habilitarNoSoyCliente(){
 document.getElementById('literalYaSoyCliente').style.display='none';
 document.getElementById('enlaceNoSoyCliente').style.display='none';
 document.getElementById('cajaYaSoyCliente').style.display='none';

 document.getElementById('literalNoSoyCliente').style.display='block';
 document.getElementById('enlaceYaSoyCliente').style.display='block';
 document.getElementById('cajaNoSoyCliente').style.display='block';

}

function habilitarYaSoyCliente(){

 document.getElementById('literalNoSoyCliente').style.display='none';
 document.getElementById('enlaceYaSoyCliente').style.display='none';
 document.getElementById('cajaNoSoyCliente').style.display='none';

 document.getElementById('literalYaSoyCliente').style.display='block';
 document.getElementById('enlaceNoSoyCliente').style.display='block';
 document.getElementById('cajaYaSoyCliente').style.display='block';

}

function limpiarTipoEntrega(){
	var form = $('logonFormSoyCliente');
	if( eval('form.tipoEntrega[0] != null ') ) {
		form.tipoEntrega[0].checked = false;
		form.tipoEntrega[1].checked = false;
		form.tipoEntrega[2].checked = false;
	}
}

/* funciones.js */

function loadPreRegistro(origen, numUnid, msgAviso)
{
	if (origen=="cabecera")
	{
		cargaPreRegistroCenter("");
	}
	else{
		if (validaUnidadesCarrito(numUnid, msgAviso))
		{
			var urlOrigen= document.location.toString();
			if (urlOrigen!='')
			{
				var registro = urlOrigen.indexOf("Registro.aspx");
				if (registro < 0)
				{
					//no viene del registro, recargar solo centro
					cargaPreRegistroCenter(origen);
				}
				else
				{
					document.location="/alimentacion/SubHome.aspx?redirige=preRegistro";
				}
			}
		}
	}
}

function cargaPreRegistroCenter (origen)
{
	params = {"origen" : origen};
	doLoadPreRegistro(params);
}

//Funcion generica para realizar una llamada ajax pasandole parametros
function doLoadPreRegistro(params)
{
	$('center').className="divCentral";
	var opts = {
		parameters: params,
		onSuccess: function(transport){showResponseLogout(transport,"center");}
	}
	new Ajax.Request("/alimentacion/PreRegistro.aspx",opts);
}


function showResponseLogout(transport,id_contenedor)
{
	$(id_contenedor).update(transport.responseText);
}

function hacerClickLogin (idBoton)
{
	$(idBoton).click();
	return true;
}

//funcion Ajax que hace el submit del formulario
function doLoginAjax(formulario, botonId,origen)
{
	var txtContrasena = document.getElementById('txtContrasena');
	txtContrasena.value = toHexa(txtContrasena.value);
	var url ="/alimentacion/PreRegistro.aspx";
	//Actualizara detalle de mi compra.
	var opts = {
		parameters: {"origen" : origen},
		postBody : preparePostData(formulario.id, botonId),
		onSuccess: function(transport) { successAjaxLoginHandler(transport, origen); }
	}
	new Ajax.Request(url,opts);
}

function toHexa(cadena){
	cad='';
	for (var i=0; i<cadena.length; i++)
	{
		var caracter = cadena.charCodeAt(i);
		hexa = toHex(caracter);
		cad=cad+hexa;
	}
	return cad;
}

function toHex(dec)
{
	var hexChars="0123456789ABCDEF"
	if (dec > 255)
	{
		return null;
	}
	var i = dec % 16
	var j = (dec-i) / 16
	return  hexChars.charAt(j) + hexChars.charAt(i)
}

//actualiza el centro en el caso que haya algun error
//si no hay error, redirecciona o a la Subhome o a paso 1 de pago, si el origen es pagar
function successAjaxLoginHandler(transport, origen) {
	if (transport.responseText.indexOf("<!-- Home -->") != -1)
	{
		document.location="/alimentacion/HomeAlimentacion.aspx";
	}
	else
	{
		if (transport.responseText.indexOf("<!-- Subhome -->") != -1)
		{
			if (transport.responseText.indexOf("comprueba_redireccion('miCompraCambioTienda')") != -1)
			{
				//hay que mandarlo a detalle de mi compra
				document.location="/alimentacion/SubHome.aspx?redirige=miCompraCambioTienda";
			}
			else
			{
				document.location="/alimentacion/SubHome.aspx";
			}
		} else if (transport.responseText.indexOf("<!-- Preregistro -->") != -1) {
			if(origen=='pagar') {
				if(transport.responseText.indexOf("<!-- Hay errores -->") != -1) {
					$('center').update(transport.responseText);
				} else {
					document.location="/alimentacion/ProcesoPago01.aspx?origen="+origen;
				}
			} else {
				$('center').update(transport.responseText);
			}
		}
	}
}


//Hace el submit del formulario
function preparePostData(formId, submitButton)
{
    var form = document.getElementById(formId);
    var result = "xmlrequest=true";
    for (var i = 0; i < form.elements.length; i++)
    {
        var el = form.elements[i];
        if (el.tagName.toLowerCase() == "select")
        {
            for (var j = 0; j < el.options.length; j++)
            {
                var op = el.options[j];
                if (op.selected)
                    result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(op.value);
            }
        }
        else if (el.tagName.toLowerCase() == "textarea")
        {
            result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(el.value);
        }
        else if (el.tagName.toLowerCase() == "input")
        {
            if (el.type.toLowerCase() == "checkbox" || el.type.toLowerCase() == "radio")
            {
                if (el.checked)
                    result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(el.value);
            }
            else if (el.type.toLowerCase() == "submit")
            {
               if (el == submitButton)
               {
					// is "el" the submit button that fired the form submit?
                    result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(el.value);
               }
            }
            else if (el.type.toLowerCase() != "button")
            {
                result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(el.value);
            }
        }
    }
    if(submitButton != '')
    {
    	var button = document.getElementById(submitButton);
    	result += "&" + encodeURIComponent(button.name) + "=" + encodeURIComponent(button.value);

    }
    return result;
}


//Funcion utilizada para redireccionar segun origen
function compruebaOrigen()
{
	var link = document.getElementById('linkPreregistro');
	var linkAnterior = document.location.href;
	var existeOrigen = linkAnterior.indexOf("origen");
	if (existeOrigen < 0)
	{
		link.href = link.href + "?origen=/alimentacion/SubHome.aspx";
	}
	else
	{
		var action = linkAnterior.split("origen=");
		var origen = action[1];
		var ultimoParametro = origen.indexOf("#");
		if (ultimoParametro >= 0)
		{
			var origenReal = origen.split("#");
			origen = origenReal[0];
		}
		link.href = link.href + "?origen=" + origen;
	}
}

function cerrarVentana()
{
	window.close();
}

// boton que vuelve desde una ficha de producto --BOTON VOLVER
function navegacionVolver(url){

	//Guardamos el historico de navegación AHORA BORRAMOS EL ENLACE ANTERIOR --BOTON VOLVER
	params = { "url" : url , "volver" : "yes" };
	new Ajax.Request("GuardarNavegacion.aspx",
	{
		parameters: params,
		asynchronous: false
	}
	);


	if(url!=''){
		var itemId = gup(url,"itemId");
		var id_contenedor= "center";

		if(url.indexOf("Terminal")>0)
		{
			//NodoTerminal
			params = { "itemId" : itemId, "visualizationOption" : -1};
			new Ajax.Request("NodoTerminalAjax.aspx",
				{
					parameters: params,
					onSuccess: function(transport){showProducts(transport,id_contenedor,params,itemId);}
				}
			);
		}
		else if(url.indexOf("AutomaticoPromociones")>0)
		{
			//NodoAutomaticoPromociones
			params = { "itemId" : itemId, "visualizationOption" : -1, "nap" : 1};
			new Ajax.Request("NodoAutomaticoPromocionesAjax.aspx",
				{
					parameters: params,
					onSuccess: function(transport){showProducts(transport,id_contenedor,params,itemId);}
				}
			);

		}
		else if(url.indexOf("3Columnas")>0)
		{
			//3Columnas
			requestNodoCentral("NodoNavegCentral3ColumnasAjax.aspx",itemId,id_contenedor);
		}
		else if(url.indexOf("Imagen")>0)
		{
			//Imagen
			requestNodoCentral("NodoNavegCentralImagenAjax.aspx",itemId,id_contenedor);
		}
		else if(url.indexOf("CentralColumna")>0)
		{
			//CentralColumna
			requestNodoCentral("NodoNavegCentralColumnaAjax.aspx",itemId,id_contenedor);
		}
		else if(url.indexOf("3Niveles")>0)
		{
			//3Niveles
			requestNodoCentral("NodoNavegCentral3NivelesAjax.aspx",itemId,id_contenedor);
		}
		else if(url.indexOf("Estatico")>0)
		{
			//NodoEstatico
			requestNodoCentral("NodoEstaticoAjax.aspx",itemId,id_contenedor);
			$(id_contenedor).className="left";
		}
		else
		{
			//Todos los demas
			new Ajax.Request(url,
				{
					onSuccess: function(transport){
						$('center').className = "";
						$("center").update(transport.responseText);
					}
				}
			);
		}
	}else{ //si viene nulo es que nos viene de un acceso dinamico
		document.location="/alimentacion/SubHome.aspx";
	}

}

function doChangePtoVenta(){
	new Ajax.Request('/alimentacion/SubHome.aspx',{
		method : 'post',
		postBody : Form.serialize($('form')),
		onSuccess : function(transport){
			if( transport.responseText.indexOf('errors') >0 ){
			 	document.write(transport.responseText);
			}else{
			    //window.opener.document.location="/alimentacion/PaginaBienvenida.aspx";
			    window.close();
			    window.dialogArguments.location.replace("/alimentacion/PaginaBienvenida.aspx");
			}
		}
	});
}

function doLoginPreHomeAjax(){
	msg1="doLoginPreHomeAjax";
	alert(msg1);
	msg2="onSuccess";
	msg3="abrirPopup";
	new Ajax.Request('/alimentacion/HomeAlimentacion.aspx',{
		method : 'post',
		postBody : Form.serialize($('logonForm')),
		onSuccess : function(transport){
			alert(msg2);
			document.write(transport.responseText);
			//al fin y al cabo esto es una recarga
			//buscar la forma de hacer logout/login en el manejador
			if(transport.responseText.indexOf('errores') > 0 ){
			}else{
				alert(msg3);
			}
		}
	});
}

function doLinkModificarRegistroPopupDirecciones(){
	//window.dialogArguments.location.replace("/alimentacion/MiCuenta.aspx");
	if($("couponCode") != null && $("couponCode").getValue() != ""){
		// alert($("couponCode").getValue());
		window.close();
		window.dialogArguments.location.replace("/alimentacion/PaginaBienvenidaFromMisDatos.aspx");
	}else{
		window.close();
		window.dialogArguments.location.replace("/alimentacion/MiCuenta.aspx?from=seleccionPuntoEntrega");
	}
}

function inicializarNavegacion(){
	params = { "url" : "/alimentacion/SubHome.aspx"};
	new Ajax.Request("GuardarNavegacion.aspx",
	{
		parameters: params,
		asynchronous: false
	}
	);
}

function mostrarLoading(mensaje)
{
	if(mensaje == null || mensaje == ''){
		mensaje = $('textoEsperaGenerico').value;
	}
	p=$('center');
	p2=$('centerHidden');
	txt=$('mensajeEspera');
	if (txt != null) {
		txt.innerHTML = '';
		txt.innerHTML = mensaje;
	}
	p2.style.display = '';
	p.style.display = 'none';
}

function ocultarLoading()
{
	p=$('center');
	p2=$('centerHidden');
	p2.style.display = 'none';
	p.style.display = '';
}

/* include_listProducts.js */

function doConsulta(formulario, boton, url, id)
{

	var opts = {
		method:'post',
		parameters: preparePostDat(formulario.id),
		onSuccess: function(transport){ handleDoConsulta(transport, formulario, id); },
		onFailure: handleError
	}
	new Ajax.Request(url,opts);
	desplegarCarrito();

	/* ESTOS CAMBIOS SOLO SE DEBEN HACER SI LACOMPRA HA IDO BIEN:
		se pasan al gestor de respuesta
	if( $('cantidadActual_'+id) != null && $(id) != null ){
		$('cantidadActual_'+id).value = $(id).value;
	}
	if( $('prel_cantidadActual_'+id) != null && $("cant_" + id) != null ){
		$('prel_cantidadActual_'+id).value = $("cant_" + id).value;
	}
	*/
}

//Actualiza solamente la parte derecha del carrito
function handleDoConsulta (transport, formulario, id) {
	if (transport.responseText.indexOf("<!-- Home -->") > 0) {
		document.location="/alimentacion/HomeAlimentacion.aspx";
	} else {

		//actualizamos con ajax el bloque_carrito
		$('recargaCarrito').update(transport.responseText);
		//Comprobamos si existe algun mensaje de Error para mostrar el popup
		if ($('mensajeError')!=null)
		{
			var texto = $('mensajeError').value;
			if ($('confirmMsg') != null && $('confirmMsg').value == 1){
				if (confirm(texto)){
					loadPreRegistro('',1,'');
				}
			}else{
				alert(texto);
			}
		} else {
			//no hay errores
			if( $('cantidadActual_'+id) != null && $(id) != null ){
				$('cantidadActual_'+id).value = $(id).value;
			}
			if( $('prel_cantidadActual_'+id) != null && $("cant_" + id) != null ){
				$('prel_cantidadActual_'+id).value = $("cant_" + id).value;
			}
		}
		$('preload_carrito').style.display='none';
		//recargar botones derecha
		var opts2 = {
			onSuccess: function(transport){showResponse(transport,"recargaBotonesDerecha");}
		}
		new Ajax.Request("/alimentacion/BotonesBloqueCarrito.aspx", opts2);
	}
}

//actualiza el contenido del order si hacemos alguna modificacion
function updateMyPurchase(formulario, botonId, url, id)
{
	//Actualizara detalle de mi compra.
	var opts = {
		method:'post',
		postBody : preparePostData(formulario.id, botonId),
		onSuccess: updateContentMyPurchase
	}
	new Ajax.Request(url,opts);

	if( $('cantidadActual_'+id) != null && $(id) != null ){
		$('cantidadActual_'+id).value = $(id).value;
	}

	if( $('prel_cantidadActual_'+id) != null && $(id) != null ){
		$('prel_cantidadActual_'+id).value = $(id).value;
	}
}

//actualiza la parte del carrito y la del center
var updateContentMyPurchase = function(transport)
{

	if (transport.responseText.indexOf("<!-- Home -->") > 0)
	{
		document.location="/alimentacion/HomeAlimentacion.aspx";
	}
	else
	{
		//actualizamos con ajax el bloque_carrito
		$('recargaCarrito').update(transport.responseText);
		//Comprobamos si existe algun mensaje de Error para mostrar el popup
		if ($('mensajeError')!=null && $('mensajeError')!='')
		{
			var texto = $('mensajeError').value;
			alert(texto);
		}
		else
		{
			new Ajax.Updater('center','/alimentacion/ContenidoDetalleMiCompra.aspx');
		}
		$('preload_carrito').style.display='none';
		//recargar botones derecha
		var opts2 = {
			onSuccess: function(transport){showResponse(transport,"recargaBotonesDerecha");}
		}
		new Ajax.Request("/alimentacion/BotonesBloqueCarrito.aspx", opts2);
	}
}

function loadPurchaseDetails(params)
{
	//Guardamos el historico de navegación --BOTON VOLVER
	params = { "url" : '/alimentacion/ContenidoDetalleMiCompra.aspx'};
	new Ajax.Request("GuardarNavegacion.aspx",
	{
		parameters: params,
		asynchronous: false
	}
	);


	$('divPublicidad').innerHTML="";
	new Ajax.Request('/alimentacion/ContenidoDetalleMiCompra.aspx',
		{
			parameters: params,
			onSuccess : function(transport){showResponseCenter(transport);}
		}
	);
}

function loadPurchaseDetailsAccDisc(accDiscRef)
{
	//Guardamos el historico de navegación --BOTON VOLVER
	params = {"url" : '/alimentacion/ContenidoDetalleMiCompra.aspx'};
	new Ajax.Request("GuardarNavegacion.aspx",
	{
		parameters: params,
		asynchronous: false
	}
	);

	params = {"accDiscLabel" : accDiscRef, "url" : '/alimentacion/ContenidoDetalleMiCompra.aspx'};
	$('divPublicidad').innerHTML="";
	new Ajax.Request('/alimentacion/ContenidoDetalleMiCompra.aspx',
		{
			parameters: params,
			onSuccess : function(transport){showResponseCenter(transport);}
		}
	);
}


function loadHyperlink(hid)
{
	params={"id" : hid};
	new Ajax.Request('/alimentacion/FichaHipervinculo.aspx',
		{
			parameters  : params,
			onSuccess   : function(transport){showResponseCenter(transport);}
		}
	);
}

function loadFichaDinamica(fdid, promoid){
	params={"id" : fdid, "promoId" : promoid};
	new Ajax.Request('/alimentacion/FichaPromociones.aspx',
		{
			parameters	: params,
			onSuccess	: function(transport){showResponseCenter(transport);}
		}
	);
}

//actualiza unicamente contenido central
function showResponseCenter(transport)
{

	if (transport.responseText.indexOf("<!-- Home -->") > 0)
	{
		document.location="/alimentacion/HomeAlimentacion.aspx";
	}
	else
	{
		$('center').className = "";
		$("center").update(transport.responseText);
	}
}


// Icono a mostra durante la carga Ajax
var mostrarImgLoading = function()
{
	p=$('preload_carrito');
	p.style.display='inline';
	imagen = new Image();
	imagen.src="images/indicator_arrows.gif";
	p.appendChild(imagen);
	p.innerHTML += "  Cargando Datos ..." ;
}

// Resultado de error en operacion Ajax
var handleError = function(t)
{
	//alert(t.responseText);
	$('preload_carrito').innerHTML = "";
	$('preload_carrito').style.display="none";
	msg="Vuelva a intentarlo en unos minutos o dir\u00edjase \na nuestro Departamento de Atenci\u00f3n al Cliente.";
	alert(msg);
}

// Prepara la consulta Ajax
function preparePostDat(formId)
{
    var form = document.getElementById(formId);

    var num = form.elements.length;
    var result = "xmlrequest=true&";

    result += Form.serialize(formId) ;

    return result;
}


function confirmarVaciarCarrito(formId,confirmationMessage)
{
	if (confirm(confirmationMessage))
	{
		$('emptyCartButton').click();
	}
}

//-------- Metodo que habilita o deshabilita el carrito
function bloquearEnlace(linkId,state,linkedin){

	var linked=document.getElementById(linkId);
	if(state){
		linked.href="javascript:void(0);";
		}
	else{
		var r= "javascript:$('"+linkedin +"').click();";
		linked.href=r;
		}

}

// -------- Venta Mostrador

function addCarritoFichaProdCorte(idBoton){
	if(document.getElementById('cortes') != null) {
		if(document.getElementById('cortes').selectedIndex > 0) {
			document.getElementById('corteIdAddCarrito').value = document.getElementById('cortes').value;
			$(idBoton).click();
		} else {
			alert('Es necesario seleccionar un tipo de corte.\nGracias.');
		}
	} else {
		$(idBoton).click();
	}
}

function bloquearEnlaceCorte(linkId,state,linkedin){
	var linked=$(linkId);
	if(state){
		linked.href="javascript:void(0);";
	} else {
		if($('cortes') != null) {
			var r= "javascript:addCarritoFichaProdCorte('"+linkedin +"');";
			linked.href=r;
		} else {
			var r= "javascript:$('"+linkedin +"').click();";
			linked.href=r;
		}
	}
}

function addProdListasPersonalesCorte(idprod, skuId){
	var cantidad;
	if($(idprod) != null){
		cantidad = $(idprod).value;
	}else if($(skuId) != null){
		cantidad = $(skuId).value;
	}else{
		cantidad = '0';
	}

	$('quantity-'+idprod).value = cantidad;
	var boton = 'botonAnadir-'+ idprod;
	var corteIdAdd = 'corteIdAddLP_' + idprod;

	if($('cortes') != null){
		if($('cortes').selectedIndex > 0) {
			$(corteIdAdd).value = $('cortes').value;
			$(boton).click();
		} else {
			alert('Es necesario seleccionar un tipo de corte.\nGracias.');
			return false;
		}
	} else {
		$(boton).click();
	}
}

/* listasDesplegables.js */

function listasPersonales()
{
    var desplegableListas = $("listasPersonalesDesplegables");
    var divListaCompra = $("divListaCompra");
    var desplegablePedidos = $("pedidosAnterioresDesplegable");
    var enlacesDesplegados = $("enlacesDesplegados");
    var enlacesPlegados = $("enlacesPlegados");

    //modificado para dar una inicializacion que falla en explorer
    var alturaListaCompra = "10";
    if (divListaCompra.style.height != "")
    {
    	var alturaListaCompraConUnidades = divListaCompra.style.height;
    	alturaListaCompra = alturaListaCompraConUnidades.substring(0, (alturaListaCompraConUnidades.length)-2);
    }

    if (desplegableListas.style.display == 'block')
    {
        divListaCompra.style.height = (eval(alturaListaCompra,10) + eval(7.5,10)) + "em";
        enlacesDesplegados.style.display = 'block';
        enlacesPlegados.style.display = 'none';
        desplegableListas.style.display = 'none';
        desplegablePedidos.style.display = 'none';
    }
    else
    {
        if (desplegablePedidos.style.display != 'block')
        {
            divListaCompra.style.height = (eval(alturaListaCompra,10) - eval(7.5,10)) + "em";
        }
        enlacesDesplegados.style.display = 'none';
        enlacesPlegados.style.display = 'block';
        desplegableListas.style.display = 'block';
        desplegablePedidos.style.display = 'none';

    }
}

function pedidosAnteriores()
{
    var desplegableListas = $("listasPersonalesDesplegables");
    var divListaCompra = $("divListaCompra");
    var desplegablePedidos = $("pedidosAnterioresDesplegable");
    var enlacesDesplegados = $("enlacesDesplegados");
    var enlacesPlegados = $("enlacesPlegados");

    //modificado para dar una inicializacion que falla en explorer
    var alturaListaCompra = "10";
    if (divListaCompra.style.height != "")
    {
    	var alturaListaCompraConUnidades = divListaCompra.style.height;
    	alturaListaCompra = alturaListaCompraConUnidades.substring(0, (alturaListaCompraConUnidades.length)-2);
    }

    //debugger;
    if (desplegablePedidos.style.display == 'block')
    {
        divListaCompra.style.height = (eval(alturaListaCompra,10) + eval(7.5,10)) + "em";
        enlacesDesplegados.style.display = 'block';
        enlacesPlegados.style.display = 'none';
        desplegablePedidos.style.display = 'none';
        desplegableListas.style.display = 'none';


    }
    else
    {
        if (desplegableListas.style.display != 'block')
        {
            divListaCompra.style.height = (eval(alturaListaCompra,10) - eval(7.5,10)) + "em";
        }
        enlacesDesplegados.style.display = 'none';
        enlacesPlegados.style.display = 'block';
        desplegablePedidos.style.display = 'block';
        desplegableListas.style.display = 'none';

    }
}

function desplegarCarrito()
{
    var desplegableListas = document.getElementById("listasPersonalesDesplegables");
    var divListaCompra = document.getElementById("divListaCompra");
    var desplegablePedidos = document.getElementById("pedidosAnterioresDesplegable");
    var enlacesDesplegados = document.getElementById("enlacesDesplegados");
    var enlacesPlegados = document.getElementById("enlacesPlegados");

    //debugger;
    var alturaListaCompraConUnidades = divListaCompra.style.height;

    var alturaListaCompra = alturaListaCompraConUnidades.substring(0, (alturaListaCompraConUnidades.length)-2);
    alturaListaCompra = alturaListaCompra;

        divListaCompra.style.height = (eval(alturaListaCompra,10) + eval(7.5,10)) + "em";
        enlacesDesplegados.style.display = 'block';
        enlacesPlegados.style.display = 'none'
        desplegablePedidos.style.display = 'none';
        desplegableListas.style.display = 'none';

}

/* listasPersonales.js */

//Asigna el boton eliminar como el pulsado para la funcion updatePurchaseList
function eliminaLista(idBoton, texto)
{
	var id = "elimina_".concat(idBoton);
	var result = confirm(texto);
	if(result)
	{
		$("botonPresionado").value = id;
		$(id).click();
	}
}

//Asigna el boton actualizar como el pulsado para la funcion updatePurchaseList
function actualizaLista(idBoton)
{
	var id = "actualiza_".concat(idBoton);
	$('botonPresionado').value = id;
	$(id).click();
}

//Actualiza o elimina una lista personal
function updatePurchaseLists(formulario, url)
{
	botonId = $('botonPresionado').value;
	doConsultaPurchaseList(formulario, botonId, url);
}

function actualizarCantidadItemLista(campo, idGiftItem, index, antiguoValor, msg1, pagina)
{
	if (campo.value == '' || isNaN(campo.value))
	{
		// Aviso y se asigna valor por defecto
		alert(msg1);
		campo.value = antiguoValor;
	}
	else
	{
		var elemento2 = $(idGiftItem);
		elemento2.value = campo.value;
		$('tl_'.concat(campo.id)).value = campo.value;
		var formulario = $('f-'.concat(campo.id));
		var url = "/alimentacion/MostrarLista.aspx?indLista=".concat(index)+"&pagina="+pagina;
		doConsultaPurchaseList(formulario, "botonLista", url);
	}
}

//Funcionalidad de aumentar la cantidad de un elemento de la lista personal
function aumentarLista(id, idGiftItem, index,total, pagina)
{
	if(pagina==null){
		pagina=1;
	}
	var elemento = $(id);
	elemento.value = parseInt(elemento.value) + 1;
	var elemento2 = $(idGiftItem);
	elemento2.value = elemento.value;
	$('tl_'.concat(id)).value = elemento.value;
	var formulario = $('f-'.concat(id));
	var url = "/alimentacion/MostrarLista.aspx?indLista=".concat(index)+"&pagina="+pagina+"&total="+total;
	doConsultaPurchaseList(formulario, "botonLista", url);
}

//Funcionalidad de disminuir la cantidad de un elemento de la lista personal sin llegar a 0
function disminuirLista(id, idGiftItem, index, total, pagina)
{
	if(pagina==null){
		pagina=1;
	}
	var elemento = $(id);
	var valor = elemento.value - 1;
	if(valor > -1)
	{
		elemento.value = valor;
		var elemento2 = $(idGiftItem);
		elemento2.value = valor;
		$('tl_'.concat(id)).value = valor;
		var formulario = $('f-'.concat(id));
		var url = "/alimentacion/MostrarLista.aspx?indLista=".concat(index)+"&pagina="+pagina+"&total="+total;
		doConsultaPurchaseList(formulario, 'botonLista', url);
	}
}

//Funcion generica que muestra un alert con un texto
function mostrarMensaje(texto)
{
	alert(texto);
}

//Ordenacion de los productos de la lista personal
function ordenacionListaPersonal(sort, indLista)
{
	params = {"indLista" : indLista, "sortProperties" : sort};
	ajaxUpdater(params);
}

//Ordenacion de los productos de la lista personal con imagenes grandes
function ordenacionListaPersonalImagenes(indLista)
{
	var orderByProp = $('sel_orden').value;
	params = {"sortProperties" : orderByProp, "indLista" : indLista};
	var id_contenedor = "center";
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			method: 'POST',
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
//	var orden = $('sel_orden').value;
//	params = {"indLista" : indLista, "order" : orden};
//	ajaxUpdater(params);
}

//Funcion generica para realizar una llamada ajax pasandole parametros
function ajaxUpdater(params)
{
	var opts = {
		parameters: params,
		onSuccess: function(transport){showResponse(transport,"center");}
	}
	new Ajax.Request("/alimentacion/MostrarLista.aspx",opts);
}

//
//Funciones para incluir un producto a una lista personal.
//
function addItemPurchaseLists(form, botonId)
{
	var opts = {
		postBody: preparePostData(form.id, botonId),
		onInteractive:mostrarCargaAnadirProducto,
		onSuccess: handleDoConsultaListaPersonal
	}
	new Ajax.Request('/alimentacion/InsertarProductoEnLista.aspx',opts);
}

var handleDoConsultaListaPersonal = function(transport)
{
	showResponse(transport, 'preloadErrorListaPersonal');
	//Comprobamos si existe algun mensaje de Error para mostrar el popup
	if($('mensajeErrorEmergente')){
		mostrarMensajeEmergente();
	}else{
		//Muestra un mensaje cuando inluimos un item a la lista personal
		//mostrarMensaje($("textoInterAddItem").value);
	}
	recargaBloqueListas();
}


function doConsultaAllPurchaseList(form, botonId, url, mensajeError)
{
	mostrarLoading();

	var textico = preparePostData(form.id, botonId);
	var opts = {
		postBody : textico,
		onSuccess: updateContentAllPurchaseLists,
		onError: function (){ocultarLoading();alert(mensajeError);},
		on404: function (){ocultarLoading();alert(mensajeError);},
		onFailure: function (){ocultarLoading();alert(mensajeError);}
	}

	new Ajax.Request(url, opts);
}

function updateContentAllPurchaseLists(transport)
{
	showResponse(transport, 'center');
	if($("erroresComprandoLista") != null)
	{
		var listado = $("erroresComprandoLista").value;

		var productsError = listado.split(",");
		var texto = '';
		for (i=0;i<productsError.length;i++)
		{
			var txto = productsError[i];
			if (i==0)
			{
				var name= txto.split("[");
				txto = name[1];
			}
			if (i==productsError.length-1)
			{
				var name= txto.split("]");
				txto = name[0];
			}
			texto= texto + '\n' + txto;
		}
		alert(texto);
	}
	else
	{
		mostrarMensaje($("textoInterComprarLista").value);
	}

	recargaCarrito();
	recargaBotonesDerecha();
	recargaBloqueListas();
	ocultarLoading();
}

function doConsultaPurchaseList(form, botonId, url)
{
	var textico = preparePostData(form.id, botonId);
	var opts = {
		postBody : textico,
		encoding: 'ISO-8859-15',
		onSuccess: updateContentPurchaseLists
	}
	new Ajax.Request(url, opts);
}

function updateContentPurchaseLists(transport)
{
	if(transport.responseText != "")
	{
		showResponse(transport, 'center');
		mostrarMensajeEmergente();
	}
	else
	{
		mostrar_gestionar_listas();
	}
	recargaBloqueListas();
}

function mostrarCargaAnadirProducto()
{
	mostrarCarga("Incluyendo producto en la lista.", false);
}

function mostrarCargaComprarLista()
{
	mostrarCarga("Gracias por esperar mientras se incluyen a su pedido los productos de la lista.", false);
}

function mostrarCargaListaComprada()
{
	mostrarCarga("Los productos de la lista se han incluido al pedido correctamente.", true);
}

function mostrarCarga(texto, espera)
{
	$('fondoCargando').style.display='block';
	imagen = new Image();
	imagen.src="images/indicator_arrows.gif";
	p.appendChild(imagen);
	$('cargando').innerHTML +=texto;
	if(espera)
	{
		boton = new Button();
		boton.value="Aceptar";
		boton.onclick= function(){ocultaCarga();};
		p.appendChild(boton);
	}
}

function ocultaCarga()
{
	$('fondoCargando').style.display='none';
}

function mostrarMensajePopup(parametro)
{
	if(parametro != null)
	{
		if(parametro == true)
		{
			mostrarMensajeEmergente();
		}
		else
		{
			window.opener.recargaBloqueListas();
			muestraListaCreada();
		}
	}
}

function muestraGuardandoLista()
{
	$('nombreLista').style.display = 'none';
	$('listaCreada').style.display = 'none';
	$('guardandoLista').style.display = 'block';
}

function muestraListaCreada()
{
	$('nombreLista').style.display = 'none';
	$('guardandoLista').style.display = 'none';
	$('listaCreada').style.display = 'block';

}

function mostrarMensajeEmergente()
{
	if($('mensajeErrorEmergente') != null){
		var texto = $('mensajeErrorEmergente').value;
		mostrarMensaje(texto);
	}
}

//Abre un popUp para crear una nueva lista con el carrito de la compra actual
function crearNuevaLista(enlace)
{
	var result = abrirPopUp(enlace.href,enlace.title,'toolbar=no,location=no,menubar=no,resizable=no,width=400,height=200','250','250');
}

function recargaCarrito()
{
	var opts = {
		onSuccess: function(transport){showResponse(transport,"recargaCarrito");}
	}
	new Ajax.Request("/alimentacion/BloqueCarrito.aspx", opts);
}
function recargaBotonesDerecha()
{
	var opts2 = {
			onSuccess: function(transport){showResponse(transport,"recargaBotonesDerecha");}
		}
		new Ajax.Request("/alimentacion/BotonesBloqueCarrito.aspx", opts2);
}

//recarga el bloque derecha
function recargaBloqueListas()
{
	var opts = {
		onSuccess: function(transport){showResponse(transport,"recargaBloqueLista");}
	}
	new Ajax.Request("/alimentacion/BloqueListas.aspx", opts);

	var opts2 = {
		onSuccess: function(transport){showResponse(transport,"recargaBotonesDerecha");}
	}
	new Ajax.Request("/alimentacion/BotonesBloqueCarrito.aspx", opts2);
	if($("center").innerHTML.indexOf("<!-- gestionarListas -->") != -1){
		mostrar_gestionar_listas();
	}
}

//Carga la jsp de gestionar listas personales desde mi_cuenta
function mostrar_gestionar_listas_mi_cuenta()
{
	document.location ='/alimentacion/SubHome.aspx?redirige=gestionarListas';
}

//Carga la jsp de gestionar listas personales
function mostrar_gestionar_listas(keyHipervinculo)
{
	var opts = {
		onSuccess: function(transport){showResponse(transport,"divPublicidad");}
	}
	url = "/alimentacion/HipervinculoEstatico.aspx?key=" + keyHipervinculo;
	new Ajax.Request(url, opts);
	$('center').className="";
	opts = {
		onSuccess: function(transport){showResponse(transport,"center");}
	}
	new Ajax.Request("/alimentacion/GestionarListas.aspx", opts);
}

//Carga la jsp de una lista personal del usuario
function mostrar_lista_personal(index, keyHipervinculo,mensaje)
{
	mostrarLoading(mensaje);
	//Guardamos el historico de navegación --BOTON VOLVER
	params = { "url" : "/alimentacion/MostrarLista.aspx?indLista=" + index};
	new Ajax.Request("GuardarNavegacion.aspx",
	{
		parameters: params,
		asynchronous: false
	}
	);

	opts = {
		onSuccess: function(transport){ocultarLoading();showResponse(transport,"divPublicidad");}
	}
	url = "/alimentacion/IframeHipervinculoEstatico.aspx?key=" + keyHipervinculo;
	new Ajax.Request(url, opts);
	$('center').className="";
	opts = {
		onSuccess: function(transport){showResponse(transport,"center");}
	}
	url = "/alimentacion/MostrarLista.aspx?indLista=" + index;
	new Ajax.Request(url, opts);
}

//
//Funciones que generan el tooltip con las listas personales
//
function cargaLista(productId, elemento, skuId, corteSeleccion)
{
	var cantidad;
	if($(productId) != null){
		cantidad = $(productId).value;
	}else if($(skuId) != null){
		cantidad = $(skuId).value;
	}else{
		cantidad = '0';
	}

	var params;
	if(corteSeleccion != null){
		params = {"productId" : productId, "cantidad" : cantidad, "skuId" : skuId, "corteSeleccionado" : corteSeleccion};
	}else{
		params = {"productId" : productId, "cantidad" : cantidad, "skuId" : skuId};
	}

	var opts = {
		parameters : params,
		onSuccess: onCargaLista,
		asynchronous: false
	}
	new Ajax.Request("/alimentacion/RecalculaPopupListas.aspx", opts);
}

var onCargaLista = function(transport)
{

	if (transport.responseText.indexOf("<!-- Home -->") > 0)
	{
		document.location="/alimentacion/HomeAlimentacion.aspx";
	}
	else
	{

		dw_Tooltip.content_vars = {
			hover: {
				hoverable: true,
				content: transport.responseText
			}
		}
	}
}

function comprarTodo ()
{
	$('botonCompraTodo').click();
}

function crearNuevaLista()
{
	$('crearLista').click();
}

function addProdListaPersonal(id){
	if($('cortes') != null){
		if($('cortes').value != '0') {
			$('corteIdAddLP-'+id).value = $('cortes').value;
			$('botonAnadir-'+id).click();
		} else {
			alert('Es necesario seleccionar un tipo de corte.\nGracias.');
			return false;
		}
	}else {
		$('botonAnadir-'+id).click();
	}
}

/* menuAyuda.js */


function doListaSubOpciones(id,url,msgError)
{
	var params =  "idHelpOption=" + id ;
	var opts = {
		method:'get',
		parameters:params,
		onComplete: showResponseListaSubMenu,
		onError: function (){alert(msgError);},
		on404: function (){alert(msgError);},
		onFailure: function (){alert(msgError);}
	}
	new Ajax.Request(url,opts);
}

function doMostrarTextoCentral(id,url,msgError)
{
	var ident =  "idHelpSubOption=" + id;
	var opts = {
		method:'get',
		parameters : ident,
		onComplete : showResponseTexto,
		onError: function (){alert(msgError);},
		on404: function (){alert(msgError);},
		onFailure: function (){alert(msgError);}
	}
	new Ajax.Request(url,opts);
}

 function showResponseListaSubMenu(transport)
{
	if (transport.responseText.indexOf("<!-- Home -->") > 0)
	{
		document.location="/alimentacion/HomeAlimentacion.aspx";
	}
	else
	{
		$('divListaAyuda').update(transport.responseText);
		cargaTextoCentral();
	}
}

 function showResponseTexto(transport)
{
	if (transport.responseText.indexOf("<!-- Home -->") > 0)
	{
		document.location="/alimentacion/HomeAlimentacion.aspx";
	}
	else
	{
		$('divTextoCentral').update(transport.responseText);
	}
}

function cargaMenuAyuda()
{
	var idObjeto='linkOpcion_0';
	var link = document.getElementById(idObjeto);
	lanzarEvento (link,'click');
}

function cargaTextoCentral()
{
	var idObjeto='linkSubOpcion_0';
	var link = document.getElementById(idObjeto);
	lanzarEvento (link,'click');
}

function lanzarEvento(obj,evt){

    var fireOnThis = obj;
    if( document.createEvent )
    {
      var evObj = document.createEvent('MouseEvents');
      evObj.initEvent( evt, true, false );
      fireOnThis.dispatchEvent(evObj);
    }
    else if( document.createEventObject )
    {
      fireOnThis.fireEvent('on'+evt);
    }
}

/* menuPpal.js */

function showCompraOnLine() {
  Element.show('cajaCompraOnline');
  $('online').addClassName('active');
}
function hideCompraOnLine() {
  Element.hide('cajaCompraOnline');
  $('online').removeClassName('active');
}
function showTiendas() {
  Element.show('cajaTiendasCarrefour');
  $('tiendas').addClassName('active');
 var iframeTiendas = document.getElementById("menuiframeTiendas");
 if (iframeTiendas != null)
 {
    iframeTiendas.style.display = 'block'
 }
}
function hideTiendas() {
  Element.hide('cajaTiendasCarrefour');
  $('tiendas').removeClassName('active');
 var iframeTiendas = document.getElementById("menuiframeTiendas");
 if (iframeTiendas != null)
 {
     iframeTiendas.style.display = 'none'
 }
}
function showGrupo() {
  Element.show('cajaGrupoCarrefour');
  $('grupo').addClassName('active');
}
function hideGrupo() {
  Element.hide('cajaGrupoCarrefour');
  $('grupo').removeClassName('active');
}
function abreimg(image,medidas) { //abre imagenes de Recursos en Grupo Carrefour
	img = image;
	medida = medidas;
	window.open(img,'','top=0,left=0,scrollbars=yes,'+medidas+',resizable=yes');
}

/* menuPrincipal.js */


//---> Se obtiene el estado de una pestaâ??a del menu (en este caso CompraOnLine)
function getStyle()
   {
      var temp = document.getElementById("CompraOnLine").style.visibility;
      return temp;
   }


//---> Se cambia el estado de una pestaâ??a del menu (en este caso CompraOnLine)
function switchCompraOnLine()
  {
      var current = getStyle();
      if( current == "visible" )
       {
         document.getElementById("CompraOnLine").style.visibility = "hidden";
       }
       else
       {
         document.getElementById("CompraOnLine").style.visibility = "visible";
       }
  }


//
//---> Se muestra el menu correspondiente a CompraOnLine
function showCompraOnLine2()
  {
	document.btCompra.src = "/alimentacion/201111031215/media/es/web/boton/bt_CompraOnLine2.gif";
      	document.getElementById("CompraOnLine").style.visibility = "visible";
  }
//---> Se oculta el menu correspondiente a CompraOnLine
function hideCompraOnLine2()
  {
  	document.btCompra.src = "/alimentacion/201111031215/media/es/web/boton/bt_CompraOnLine1.gif";
	document.getElementById("CompraOnLine").style.visibility = "hidden";
  }
function hideCompraOnLineSIN()
  {
	document.getElementById("CompraOnLine").style.visibility = "hidden";
  }



//
//---> Se muestra el menu correspondiente a TiendasCarrefour
function showTiendasCarrefour()
  {
  	document.btTiendas.src = "/alimentacion/201111031215/media/es/web/boton/bt_TiendasCarrefour2.gif";
      	document.getElementById("TiendasCarrefour").style.visibility = "visible";
  }
 //---> Se oculta el menu correspondiente a TiendasCarrefour
function hideTiendasCarrefour()
  {
  		document.btTiendas.src = "/alimentacion/201111031215/media/es/web/boton/bt_TiendasCarrefour1.gif";
		document.getElementById("TiendasCarrefour").style.visibility = "hidden";
  }
function hideTiendasCarrefourSIN()
  {
		document.getElementById("TiendasCarrefour").style.visibility = "hidden";
  }



//
//---> Se muestra el menu correspondiente a GrupoCarrefour
function showGrupoCarrefour()
  {
  	document.btGrupo.src = "/alimentacion/201111031215/media/es/web/boton/bt_GrupoCarrefour2.gif";
      	document.getElementById("GrupoCarrefour").style.visibility = "visible";
  }
 //---> Se oculta el menu correspondiente a GrupoCarrefour
function hideGrupoCarrefour()
  {
  	document.btGrupo.src = "/alimentacion/201111031215/media/es/web/boton/bt_GrupoCarrefour1.gif";
	document.getElementById("GrupoCarrefour").style.visibility = "hidden";
  }
function hideGrupoCarrefourSIN()
  {
	document.getElementById("GrupoCarrefour").style.visibility = "hidden";
  }

/* nodo_terminal.js */


// Funcion para manejar la visualizacion (sin imagenes, iconos, imagenes) de un nodo terminal
function visualizacionNodoTerminal(nombreTablaListado, nombreTablaListadoImagenes, ordenConImg, nombreIconos, opcionMenu)
{
	var tablaListado = document.getElementById(nombreTablaListado);
	var tablaListadoImagenes = document.getElementById(nombreTablaListadoImagenes);
	var ordenCon = document.getElementById(ordenConImg);
	if (opcionMenu == '2')
	{
		// Visualizacion con imagenes medianas
		tablaListado.style.display='none';
		tablaListadoImagenes.style.display='block';
		ordenCon.style.display='block';
	}
	else
	{
		tablaListado.style.display='block';
		tablaListadoImagenes.style.display='none';
		ordenCon.style.display='none';
		var coleccionIconos = document.getElementsByName(nombreIconos);
		if (opcionMenu == '0')
		{
			// Visualizacion sin imagenes
			for (i=0;i<coleccionIconos.length;i++)
			{
				coleccionIconos[i].style.display='none';
			}
		}
		if (opcionMenu == '1')
		{
			// Visualizacion con iconos
			for (i=0;i<coleccionIconos.length;i++)
			{
				coleccionIconos[i].style.display='block';
			}
		}
	}
}

/* ocultar.js */

var currentPreviewBox;
var IE = document.all?true:false;
var ieVer=/*@cc_on function(){ switch(@_jscript_version){ case 1.0:return 3; case 3.0:return 4; case 5.0:return 5; case 5.1:return 5; case 5.5:return 5.5; case 5.6:return 6; case 5.7:return 7; case 5.8:return 8; }}()||@*/0;

function removeNode (node) {
	if(node && node.parentNode)
	node.parentNode.removeChild(node);
}

/*function $(obj) {
	if (typeof obj=="string") {
		return document.getElementById(obj);
	} else {
		return obj;
	}
}*/

function showPreview (elm,e,jsp) {
	var vacio = "vacio";
/*
   	var id = elm.getAttribute("title");
   	var img = document.getElementById(id + "-img");
	var pvb =$(id+"-div");

	if(!IE) {
		if(img.width > 150) {
			if(img.height < 115) {
				img.style.paddingTop = "30px";
			}
			img.style.width = "145px";
		}
		if(img.height >= 150) {
			img.style.height = "130px";
		}
	} else {
		if (ieVer >= 6) {
			image = new Image();
			image.src = img.src;

			if(image.width > 150 || image.height > 130) {
				if(image.width > image.height) {
					redimensionaAncho(image,img,145);
				} else {
					redimensionaAlto(image,img,130);
				}
			}
			pvb.style.width = "152px";
		}
	}
   	if(currentPreviewBox) removeNode(currentPreviewBox);
   	var pos = findPos (elm);
   	var cmp = $(id);
   	pvb = document.body.appendChild(pvb.cloneNode(true));

	// Calcula posicion del popUp
	var sum = 0;
//	if(cmp != null) { // Hay compare en la pagina
//		sum = 75;
//	}
//	if(jsp == '/WEB-INF/jsp/pedidosAnteriores/mostrar_pedidos_anteriores.jsp') {
//		sum = 100;
//	}
   	if(IE) {
	   	var leftVar = pos[0]-parseInt(pvb.offsetWidth-elm.offsetWidth);
	   	if (ieVer>=6) {
			var leftVar=150 + sum;
	   	}
	} else {
		var leftVar = 140 + sum;
	}
   	pvb.style.left = leftVar+"px";
   	pvb.style.top = pos[1]-parseInt((pvb.offsetHeight-elm.offsetHeight)/2)-parseInt($("divCuerpo").scrollTop)+"px";

   	currentPreviewBox = pvb;
   	*/
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}

function hidePreview() {
	currentPreviewBox.style.display ="none";
}

function redimensionaAlto(image,img,max){
	if(parseFloat(image.height)>max){
		img.style.width=(max*parseFloat(image.width)/parseFloat(image.height))+"px";
		img.style.height=max+"px";
	}
}
function redimensionaAncho(image,img,max) {
	if(parseFloat(image.width)>max) {
		img.style.height=(max*parseFloat(image.height)/parseFloat(image.width))+"px";
		img.style.width=max+"px";
	}
}

/* pedidosAnteriores.js */

//Carga la jsp de gestionar pedidos anteriores
function mostrar_gestionar_pedidos_anteriores()
{
	$('divPublicidad').innerHTML="";
	$('center').className="";
	new Ajax.Updater('center','/alimentacion/GestionarPedidosAnteriores.aspx');
}
//Carga la jsp de un pedido anterior del usuario
function mostrar_pedido_anterior(id, fecha, subestado, mensaje, mensajeError)
{
	mostrarLoading(mensaje);
	//Guardamos el historico de navegación --BOTON VOLVER
	params = { "url" : "/alimentacion/MostrarPedidoAnterior.aspx?pedidoId="+id+"&subestado="+subestado+"&fechaPedido="+fecha};
	new Ajax.Request("GuardarNavegacion.aspx",
	{
		parameters: params,
		asynchronous: false
	}
	);

	$('divPublicidad').innerHTML="";
	var params = {"pedidoId" : id, "subestado" : subestado, "fechaPedido" : fecha};
	opts = {
		method: "post",
		parameters: params,
		onSuccess: function(transport){ocultarLoading();showResponse(transport,"center");},
		onError: function (){ocultarLoading();alert(mensajeError);},
		on404: function (){ocultarLoading();alert(mensajeError);},
		onFailure: function (){ocultarLoading();alert(mensajeError);}
	}
	new Ajax.Request("/alimentacion/MostrarPedidoAnterior.aspx", opts);
}

//Recarga el bloque de pedidos anteriores
function recargaBloquePedidosAnteriores(){
	new Ajax.Updater('recargaBloquePedidosAnteriores',"/alimentacion/BloquePedidosAnteriores.aspx");
}

function actualizarCantidadItemPedidoAnterior(campo, idPedido, antiguoValor, msg1, subestado, fecha)
{
	if (campo.value == '' || isNaN(campo.value))
	{
		// Aviso y se asigna valor por defecto
		alert(msg1);
		campo.value = antiguoValor;
	}
	else
	{
		var quantityList = $('qList-'.concat(campo.id));
		quantityList.value = campo.value;
		var quantityOrder = $('to-'.concat(campo.id));
		if(quantityOrder != null){
			quantityOrder.value = campo.value;
		}
		var formulario = $('f-'.concat(campo.id));
		var url = "/alimentacion/MostrarPedidoAnterior.aspx?pedidoId="+idPedido+"&subestado="+subestado+"&fechaPedido="+fecha;
		var boton = 'botonPedidoAnterior-' + campo.id;
		doConsultaActualizaItemsOrder(formulario, boton, url);
	}
}

//Funcionalidad que aumenta la cantidad de un commerceItem de un pedido anterior
function aumentarPedidoAnterior(id, idPedido, subestado, fecha){
	var cantidad = $(id);
	var cantidadLista = $("qList-" + id);
	var cantidadActualizada = (parseInt(cantidad.value) + 1)+"";
	cantidad.value = cantidadActualizada;
	cantidadLista.value = cantidadActualizada;
	var quantityOrder = $("to-" + id);
	if(quantityOrder != null){
		quantityOrder.value = cantidadActualizada;
	}
	var formulario = $("f-" + id);
	var url = "/alimentacion/MostrarPedidoAnterior.aspx?pedidoId="+idPedido+"&subestado="+subestado+"&fechaPedido="+fecha;
	var boton = "botonPedidoAnterior-" + id;
	doConsultaActualizaItemsOrder(formulario, boton, url);
}

//Funcionalidad que disminuye la cantidad de un commerceItem de un pedido anterior
function disminuirPedidoAnterior(id, idPedido, subestado, fecha){
	var cantidad = $(id);
	var cantidadLista = $("qList-" + id);
	var valor = (parseInt(cantidad.value) - 1)+"";
	if(valor > -1)
	{
		cantidad.value = valor;
		cantidadLista.value = valor;
		var quantityOrder = $("to-" + id);
		if(quantityOrder != null){
			quantityOrder.value = valor;
		}
		var formulario = $("f-" + id);
		var url = "/alimentacion/MostrarPedidoAnterior.aspx?pedidoId="+idPedido+"&subestado="+subestado+"&fechaPedido="+fecha;
		var boton = "botonPedidoAnterior-" + id;
		doConsultaActualizaItemsOrder(formulario, boton, url);
	}
}

function doConsultaActualizaItemsOrder(form, botonId, url)
{
	var opts = {
		method:'post',
		postBody : preparePostData(form.id, botonId),
		onSuccess: function(){showResponse(transport, 'center');}
	}
	new Ajax.Request(url, opts);
}

function doConsultaPreviusOrder(form, botonId, url)
{
	var opts = {
		method:'post',
		onInteractive: function (){mostrarLoading();},
		postBody : preparePostData(form.id, botonId),
		onSuccess: updateContentPreviusOrder,
		onError: function (){ocultarLoading();},
		on404: function (){ocultarLoading();},
		onFailure: function (){ocultarLoading();}
	}
	new Ajax.Request(url, opts);
}

function updateContentPreviusOrder(transport){
	if (transport.responseText.indexOf("<!-- Home -->") > 0){
		document.location="/alimentacion/HomeAlimentacion.aspx";
	}else{
		showResponse(transport, 'center');
		if($("erroresComprandoLista") != null){
			var listado = $("erroresComprandoLista").value;
			var productsError = listado.split(",");
			var texto = '';
			for (i=0;i<productsError.length;i++)
			{
				var txto = productsError[i];
				if (i==0)
				{
					var name= txto.split("[");
					txto = name[1];
				}
				if (i==productsError.length-1)
				{
					var name= txto.split("]");
					txto = name[0];
				}
				texto= texto + '\n' + txto;
			}
			alert(texto);
		}else{
			mostrarMensaje($("textoInterComprarPedido").value);
		}
		recargaBotonesDerecha();
		recargaCarrito();
		recargaBloquePedidosAnteriores();
		ocultarLoading();
	}
}

function mostrar_gestionar_pedidos_mi_cuenta(){
	document.location ='/alimentacion/SubHome.aspx?redirige=gestionarPedidosAnteriores';
}

/* popup.js */



//Abrir un pop up con mas fotos
function abrirPopUpMasFotos(url)
{
	var params = 'toolbar=no,location=no,menubar=no,resizable=no,width=250,height=250';
	var win=window.open(url,'ver_mas_fotos_popup',params);
	win.moveTo(2,30);
	win.focus();
}

//Abrir pop up promocional
function abrirPopUpPromocional(url)
{
	var params = 'toolbar=no,location=no,menubar=no,resizable=no,width=620,height=475';
	var win=window.open(url,'promocional_popup',params);
	win.moveTo(2,30);
	win.focus();
}

//Abrir un pop up de Proxima entrega
function  abrirPopUpProximaEntrega(url)
{
	var params = 'toolbar=no,location=no,menubar=no,resizable=no,width=440,height=355';
	var win=window.open(url,'proxima_entrega',params);
	win.moveTo(2,30);
	win.focus();
}

//abre un popup generico pasandole los parametros configurables
function  abrirPopUp(url,title,params,ejex,ejey)
{
    var params2= params +",left=" + ejex + ",top=" + ejey;
	var win=window.open(url,title,params2);
	return false;
}

function abrirPopUpCreatividad(pathOrigen,title,id,height,width,ejex,ejey)
{
	var win= window.open(pathOrigen+'?id='+id,title , 'toolbar=no,location=no,menubar=no,resizable=yes,scrollbars=yes,width=' +width+ ',height=' +height+ ',left=' +ejex+ ',top=' +ejey+'' );
	return false;
}

function avisoRegistroOk (pathOrigen,datosUsuario,texto,textoBoton)
{
	window.close();
	abrirPopUpConfirmacionEnvio(pathOrigen,130,580,datosUsuario,texto,textoBoton);
}

function abrirPopUpConfirmacionEnvio(pathOrigen,altura,anchura,datosUsuario,texto,textoBoton)
{
	var win= window.open(pathOrigen+'/PopUpFinalizadoEnvio.aspx?texto='+escape(texto)+'&textoBoton='+escape(textoBoton)+'&datosUsuario='+escape(datosUsuario), 'popUpAviso', 'toolbar=no,location=no,menubar=no,resizable=no,width=' +anchura+ ',height=' +altura+ '' );
	win.moveTo(2,30);
	win.focus();
}

// Pop up del formulario de cancelacion
function  abrirPopUpFormularioCancelacion(url)
{
	screen.width;
	screen.heigth;

	izquierda = screen.width / 2;
	arriba = screen.height / 2;

	izquierda -= 250;
	arriba -= 350;

	window.open(url, 'FormularioCancelacion', 'toolbar=no,location=no,menubar=yes,scrollbars=yes,resizable=yes,width=600,height=600,top='+arriba+',left='+izquierda+'' );
}

// Pop up del Politica de proteccion de datos
function  abrirPopUpProteccionDatos(url)
{
	screen.width;
	screen.heigth;

	izquierda = screen.width / 2;
	arriba = screen.height / 2;

	izquierda -= 250;
	arriba -= 350;

	window.open(url, 'Protecion', 'toolbar=no,location=no,menubar=yes,scrollbars=yes,resizable=yes,width=600,height=600,top='+arriba+',left='+izquierda+'' );
}

// Pop up Nodo Externo
function  abrirPopUpNodoExterno(url)
{
	screen.width;
	screen.heigth;

	izquierda = screen.width / 2;
	arriba = screen.height / 2;

	izquierda -= 250;
	arriba -= 350;

	window.open(url, 'Externo', 'toolbar=no,location=no,menubar=yes,scrollbars=yes,resizable=yes,width=600,height=600,top='+arriba+',left='+izquierda+'' );
}
//Pinta en el centro la url que viene del link de publicidad del iframe
function pinta_contenido_hipervPaso1(path,codHipervinculo)
{
	var izquierda = (screen.width / 2) - 300;
	var arriba = (screen.height / 2) - 350;
	window.open(path+"/PintaHtml.aspx?idHipervinculo="+codHipervinculo, 'paso1', 'toolbar=0,location=0,status=0,menubar=0,scrollbars=1,titlebar=0o,resizable=0,width=250,height=250,top='+arriba+',left='+izquierda+'',false );
}

/* prehome.js */


//-----------------------  IDIOMA
function idioma_over()
  {
	document.idioma.src = "/alimentacion/201111031215/media/es/web/boton/preHome_idiomaRoll.gif";
      	document.getElementById("Idiomas").style.visibility = "visible";
  }
function idioma_out()
  {
  	document.idioma.src = "/alimentacion/201111031215/media/es/web/boton/preHome_idioma.gif";
	document.getElementById("Idiomas").style.visibility = "hidden";
  }

//-----------------------  QUIENES SOMOS
function quienesSomos_over()
  {
	document.quienesSomos.src = "/alimentacion/201111031215/media/es/web/boton/preHome_quienesSomosRoll.gif";
  }
function quienesSomos_out()
  {
  	document.quienesSomos.src = "/alimentacion/201111031215/media/es/web/boton/preHome_quienesSomos.gif";
  }

//-----------------------  CALIDAD Y PRECIOS
function calidadPrecios_over()
  {
	document.calidadPrecios.src = "/alimentacion/201111031215/media/es/web/boton/preHome_calidadPreciosRoll.gif";
  }
function calidadPrecios_out()
  {
  	document.calidadPrecios.src = "/alimentacion/201111031215/media/es/web/boton/preHome_calidadPrecios.gif";
  }

//--------------------------  DONDE SERVIMOS
function dondeServimos_over()
  {
	document.dondeServimos.src = "/alimentacion/201111031215/media/es/web/boton/preHome_dondeServimosRoll.gif";
  }
function dondeServimos_out()
  {
  	document.dondeServimos.src = "/alimentacion/201111031215/media/es/web/boton/preHome_dondeServimos.gif";
  }

//---------------------------  ENTREGA A DOMICILIO
function entregaDomicilio_over()
  {
	document.entregaDomicilio.src = "/alimentacion/201111031215/media/es/web/boton/preHome_entregaDomicilioRoll.gif";
  }
function entregaDomicilio_out()
  {
  	document.entregaDomicilio.src = "/alimentacion/201111031215/media/es/web/boton/preHome_entregaDomicilio.gif";
  }

//----------------------------  MEDIOS DE PAGO
function mediosPago_over()
  {
	document.mediosPago.src = "/alimentacion/201111031215/media/es/web/boton/preHome_mediosPagoRoll.gif";
  }
function mediosPago_out()
  {
  	document.mediosPago.src = "/alimentacion/201111031215/media/es/web/boton/preHome_mediosPago.gif";
  }


//------------------------  VISITA GUIADA
function visitaGuiada_over()
  {
	document.visitaGuiada.src = "/alimentacion/201111031215/media/es/web/boton/bt_visita_guiadaR.gif";
  }
function visitaGuiada_out()
  {
  	document.visitaGuiada.src = "/alimentacion/201111031215/media/es/web/boton/bt_visita_guiada.gif";
  }

/* redimension.js */

// Funcion que redimensiona el contenido de las paginas
function redimensionar()
{

    var alto = document.documentElement.clientHeight;
    if(alto == 0) {
    	alto=document.body.clientHeight;
    }

    var ancho = document.documentElement.clientWidth;
    if(ancho == 0) {
    	ancho=document.body.clientWidth;
	}

    //Convertimos los pixeles en em
    alto = alto/16;
    ancho = ancho/16;
    alto= alto/1.03;

    if (ancho < 64)
    {
        ancho = 64;
    }

    var divCabecera = document.getElementById("divCabecera");
    var divSeparadorPie = document.getElementById("divSeparadorPie");
    var divPie = document.getElementById("divPie");
    var divContenedor = document.getElementById("divContenedor");
    var divPublicidad = document.getElementById("divPublicidad");
    var divMenu = document.getElementById("divMenu");
    var divDerecha = document.getElementById("divDerecha");
    var divIzquierda = document.getElementById("divIzquierda");
    var divCuerpo = document.getElementById("divCuerpo");
    var divListaCompra = document.getElementById("divListaCompra");
    var listaCompra = document.getElementById("listaCompra");
    var cabeceraLista = document.getElementById("cabeceraLista");
    var botonesDerecha = document.getElementById("botonesDerecha");

    var altoCabecera = divCabecera.clientHeight;
    //Convertimos los pixeles en em
    altoCabecera = altoCabecera/16;
    if (divPie!=null)
    {
    	 var altoPie = divPie.clientHeight;
    	 if(divSeparadorPie!=null) {
    	 	altoPie = altoPie + divSeparadorPie.clientHeight;
    	 }
    	 altoPie = altoPie/16;
    }

    var anchoIzq;
    var anchoDcha;

    if (divPie!=null)
    {
    	alto = alto - (altoCabecera + altoPie +1.94) ;
    }

    var altoContenedor = alto + "em";

    divContenedor.style.height =altoContenedor;
    divCuerpo.style.height = altoContenedor;

    var altoPubli;
    if (divPublicidad != null)
    {
        altoPubli = divPublicidad.clientHeight;
        //Convertimos los pixeles en em
        altoPubli = altoPubli/16;
        var altoMenu = alto - (altoPubli + 0.25);
        if(altoMenu < 19)
        {
            altoMenu = 19;
        }
        altoMenu = altoMenu + "em";

        divMenu.style.height=altoMenu;
    }
    else
    {
        altoPubli = 0;
    }


    if (divListaCompra != null)
    {
        var altoRestable = (listaCompra.clientHeight/16) + (cabeceraLista.clientHeight/16) + (botonesDerecha.clientHeight/16);
        var altoListaCompra = alto - (altoRestable);
        altoListaCompra = altoListaCompra * 1.6;
        if (altoListaCompra < 13)
        {
            altoListaCompra = 9;
        }
        divListaCompra.style.height = altoListaCompra + "em";

    }


    if (divIzquierda != null)
    {
        if (divDerecha==null || divIzquierda.clientHeight <= divDerecha.clientHeight)
        {
            if ((divIzquierda.clientHeight/16) < alto)
            {
                divContenedor.style.height = alto + "em";
                divCuerpo.style.height = alto + "em";
            }
            else
            {
                divContenedor.style.height = (divIzquierda.clientHeight/16) + "em";
                divCuerpo.style.height = (divIzquierda.clientHeight/16) + "em";
            }
        }
        else
        {
            if ((divDerecha.clientHeight/16) < alto)
            {
                divContenedor.style.height = alto + "em";
                divCuerpo.style.height = alto + "em";
            }
            else
            {
                divContenedor.style.height = (divIzquierda.clientHeight/16) + "em";
                divCuerpo.style.height = (divIzquierda.clientHeight/16) + "em";
            }
        }

    }


////    if (divContenedor.clientHeight < alto)
////    {
////        divContenedor.style.height =altoContenedor;
////    }
////
////    if (divCuerpo.clientHeight < alto)
////    {
////        divCuerpo.style.height = altoContenedor;
////    }
////
////    if (divContenedor.clientHeight < divCuerpo.clientHeight)
////    {
////        divContenedor.style.height = divCuerpo.style.height
////    }

    if (divIzquierda != null)
    {
        anchoIzq = divIzquierda.clientWidth;
        anchoDcha = divDerecha!=null? divDerecha.clientWidth : 0;
    }
    else
    {
        anchoIzq = 0;
        anchoDcha = 0;
    }

    //Convertimos los pixeles en em
    anchoIzq = anchoIzq/16;
    anchoDcha = anchoDcha/16;

    divCabecera.style.width = (ancho - 2.94) + "em";
    divContenedor.style.width = (ancho - 2.94) + "em";
    if (divPie!=null)
    {
    	 divPie.style.width = (ancho - 2.94) + "em";
    }
    //Sumandole 54 al divCuerpo, en lugar de 47 funciona bien
    if ((anchoIzq != 0) && (anchoDcha !=0))
    {
        divCuerpo.style.width = ancho - (anchoIzq + anchoDcha + 3.31) + "em";
    }
    else
    {
        divCuerpo.style.width = ancho - (anchoIzq + anchoDcha + 2.94) + "em";
    }
}

/* textil.js */

//-------------------------- detalle producto Textil
function seleccionarTalla(productId, comboTallas) {
	var idTalla=comboTallas.options[comboTallas.selectedIndex].value;
	var lastColorCode = $('actualColorCode').getValue();
	/* alert('idTalla');
	/ $('contenedorDetalleTextil').innerHTML='<H1>Producto '+productId+", Talla "+idTalla+'</H1>'; */

	//cambiar el include inferior para que muestre todos los colores para la talla seleccionada
	var urlRefreshTallaColor="/alimentacion/RefreshTallaColor.aspx";
	var optsTallaColores = {
		method:'post',
		parameters: "productId="+productId+"&selectedTalla="+idTalla+"&lastColorCode="+lastColorCode,
		onSuccess: handleRefreshTallaColor,
		onFailure: handleErrorSeleccionarColor
	}

	new Ajax.Request(urlRefreshTallaColor,optsTallaColores);

}


function seleccionarColor(productId, skuId, urlImagenGrande, altImagen, colorCode) {

	//$('contenedorDetalleTextil').innerHTML='<H1>SKU '+skuId+'</H1>';

	//refrescar botones de agregar a carrito, para comprar el SKU seleccionado
	var urlRefreshAgregarCarrito="/alimentacion/AnadirCarritoProductoTextil.aspx";
	var optsAgregarCarrito = {
		method:'post',
		parameters: "productId="+productId+"&skuId="+skuId,
		onSuccess: handleRefreshAgregarCarrito,
		onFailure: handleErrorSeleccionarColor
	}
	new Ajax.Request(urlRefreshAgregarCarrito,optsAgregarCarrito);

	//refrescar informacion de precios
	var urlRefreshPrecios="/alimentacion/DisplayPriceCompletoAjax.aspx";
	var optsPrecios = {
		method:'post',
		parameters: "productId="+productId+"&skuId="+skuId,
		onSuccess: handleRefreshPrecios,
		onFailure: handleErrorSeleccionarColor
	}
	new Ajax.Request(urlRefreshPrecios,optsPrecios);


	//cambiar la imagen principal del producto por la del SKU seleccionado

	var texto;
	if(urlImagenGrande != null && urlImagenGrande != ""){
		texto = "img="+urlImagenGrande+"&descrip="+altImagen+"&ficha=true"
	}else{
		texto = "descrip="+altImagen+"&ficha=true"
	}

	//actualizamos el color actual del sku
	var colorActual = $('actualColorCode');
	if( colorActual != null ){
		colorActual.setValue(colorCode);
	}

	var urlRefreshImagenPPal="/alimentacion/Imagen.aspx";
	var optsImgPpal = {
		method:'post',
		parameters: "img="+urlImagenGrande+"&descrip="+altImagen+"&ficha=true",
		onSuccess: handleRefreshImagenPpal,
		onFailure: handleErrorSeleccionarColor
	}

	new Ajax.Request(urlRefreshImagenPPal,optsImgPpal);

}

var handleRefreshAgregarCarrito= function(transport) {

	$('divAgregarCarrito').update(transport.responseText);

}

var handleRefreshPrecios= function(transport) {

	$('divDePrecios').update(transport.responseText);

}

var handleRefreshImagenPpal= function(transport) {

	$('divImagenPpal').update(transport.responseText);

}

var handleRefreshTallaColor= function(transport){
	$('divColores').update(transport.responseText);
	var defaultColorCode = "cajaColores"+$('defaultColorCode').getValue();
	// :: Cambio en la forma de recargar las imágenes para que funcione también en IE 6. ::
	if( $(defaultColorCode) ){
		var imagenes = $(defaultColorCode).childElements();
		if(imagenes != null && imagenes.length > 0){
			var imagenDefault = imagenes[0];
			if( imagenDefault != null ){
				Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;


				if(Prototype.Browser.IE && !Prototype.Browser.IE6)
				{
					imagenDefault.click();
				}

				else if(Prototype.Browser.IE6) {
					var imagenDefault = imagenes[0];
					var tempUrl = imagenDefault.href.split('javascript:seleccionarColor(');

					urlParametros = new Array();
					urlParametros = tempUrl[1].split(",");

					productId = urlParametros[0];
					productId = reemplazaParametros(productId);
					skuId = urlParametros[1];
					skuId = reemplazaParametros(skuId);
					largeImgUrl = urlParametros[2];
					largeImgUrl = reemplazaParametros(largeImgUrl);
					descripcionCompleta = urlParametros[3];
					descripcionCompleta = reemplazaParametros(descripcionCompleta);
					colorCode = urlParametros[4];
					colorCode = reemplazaParametros(colorCode);
					colorCode = colorCode.replace(");", "");

					seleccionarColor(productId, skuId, largeImgUrl, descripcionCompleta, colorCode);
				}

				else{
					// Workaround for firefox
					window.location.href = imagenDefault.href;
	    			return false;
				}
			}

		}
	}

}

// :: Funciones de Reemplazo de caracteres ::

function reemplazaParametros(p) {
	p = replaceAll(p, '%20', "");
	p = replaceAll(p, "'", "");

	return p;
}

function replaceAll( text, busca, reemplaza ){
  while (text.toString().indexOf(busca) != -1)
      text = text.toString().replace(busca,reemplaza);
  return text;
}


var handleErrorSeleccionarColor = function(t) {
	msg="Vuelva a intentarlo en unos minutos o dir\u00edjase \na nuestro Departamento de Atenci\u00f3n al Cliente.";
	alert(msg);
}

/* validaciones.js */


var errorCuponMostrado = false;

//funcion que elimina los espacios en blanco al inicio y fin de cadena
function trim(s)
{
	s = s.replace(/^(\s|\&nbsp;)*|(\s|\&nbsp;)*$/g,'');
	return s;
}

//llama a validaNombreLista cuando se pulsa la tecla intro
function compruebaTeclaGuardaLista(oEvent,form,msgError)
{
	var iKeyCode;
	if(document.all){
		iKeyCode = oEvent.keyCode;
	}
	else{
		iKeyCode = oEvent.which;
	}
	if (iKeyCode == 13)
	{
		return validaNombreLista(form,msgError);
	}
}

//valida que el nombre de la lista no este vacio
function validaNombreLista(form,msgError)
{
	if (form != null && form.popupNuevaLista != null)
	{
		var popupNuevaLista = trim(form.popupNuevaLista.value);
		if ( popupNuevaLista == "")
		{
			// Aviso y se asigna valor por defecto
			alert(msgError);
			form.popupNuevaLista.focus();
			return false;
		}
		$('popupBotonLista').click();
		return;
	}
}

//llama a validaCodPostal cuando se pulsa la tecla intro
function compruebaTeclaValidaCodPostal(oEvent,form,msg1,msg2,msg3,msg4)
{
	var iKeyCode;
	if(document.all){
		iKeyCode = oEvent.keyCode;
	}
	else{
		iKeyCode = oEvent.which;
	}
	if (iKeyCode == 13)
	{
		return validaCodPostal(form,msg1,msg2,msg3,msg4);
	}
}

//valida que el codigo postal sea numerico y tenga 5 caracteres
function validaCodPostal(form,msg1,msg2,msg3,msg4,errorCupon)
{
	if (form != null && form.cp != null)
	{
		var cp = trim(form.cp.value);
		if ( cp == "")
		{
			// Aviso y se asigna valor por defecto
			alert(msg1);
			form.cp.focus();
			return false;
		}
		if (isNaN(cp) )
		{
			// Aviso y se asigna valor por defecto
			alert(msg2);
			borraCodPostal();
			form.cp.focus();
			return false;
		}
		if (cp.length != 5 )
		{
			// Aviso y se asigna valor por defecto
			alert(msg3);
			borraCodPostal();
			form.cp.focus();
			return false;
		}
		if (errorCuponMostrado == true){
			form.submit();
			return;
		}
		if (errorCupon == 'null' || errorCupon == ''){
			form.submit();
		}else{
			errorCuponMostrado = true;
		}
		return;
	}
	else
	{
		alert(msg4);
		return false;
	}
}

function validarCodigoPostal(codigoPostal,msg){
    var codPostal = $(codigoPostal).value;
	var re = new RegExp("\\d{5}");
	var value = $(codigoPostal).getValue();
    if ( re.test(value) == true ) {
	    return true;
   } else {
   		alert(msg);
	    return false;
   }
}


function borraCodPostal()
{
	$('cp').value = '';
}

//Funcion que valida si un numero es entero, sino reasignar valor antiguo
function validarEntero(campo, antiguoValor, msg1)
{
	if (campo.value == '' || isNaN(campo.value))
	{
		// Aviso y se asigna valor por defecto
		alert(msg1);
		campo.value = antiguoValor;
	}
}

//Funcion que valida el acceso de invitado con codigo postal erroneo
function validarAccesoInvitado(codigoPostalErroneo, msg1, msg2, msg3, errorCupon)
{
	if(codigoPostalErroneo != 'null' && codigoPostalErroneo != '')
	{
		if(msg3==''){
			alert(msg1 + codigoPostalErroneo + msg2);
		} else {
			alert(msg1 + codigoPostalErroneo + msg2 +'\n'+ msg3);
		}
		if (errorCupon == 'null' || errorCupon == ''){
			$("formTiendaNacional").submit();
		}
	}
}

function loadingYValidaUnidadesCarrito(numUnid,msgAviso,mensCargando)
{
	var retorno = validaUnidadesCarrito(numUnid,msgAviso);
	if(retorno==true){
		mostrarLoading(mensCargando);
	}
   	return retorno;
}
function mostrarCargandoPagarCentro(mensCargando)
{
	p=$('center');
	p.className="divSubhome";
	p.innerHTML = "<div>"
	+"<br/><br/><br/>"
	+"<table style='text-align:center'><tr><th>"
	+"<img src='/alimentacion/201111031215/media/es/web/imagenes/reloj_arena.gif' style='align:center'/></th></tr>" ;
	p.innerHTML += "<tr><th ><span class='producto' style='width:99%;font-weight:bold;font-size:11px;align:center'>"+mensCargando
	+"</span><b></b></th></tr></table> </div>" ;
	document.location='/alimentacion/ProcesoPago01.aspx';
}
//valida que haya productos en el carrito
function validaUnidadesCarrito(numUnid,msgAviso)
{
   	if (numUnid>0)
   	{
   		return true;
   	}
   	else
   	{
   		alert (msgAviso);
   		return false;
   	}
}

//Funcion que valida el acceso a la pasarela de pagos sea correcta
function validarPasarela(errorPasarela, mensaje)
{
	if(errorPasarela != 'null' && errorPasarela == 'true')
	{
		alert(mensaje);
	}
}

function validacionTipoEntrega(){
	// alert("validacionTipoEntrega");
	var form = $('logonFormSoyCliente');
	if( eval('form.tipoEntrega[0] != null ')){
		if( form.tipoEntrega[0].checked == false &&
		    form.tipoEntrega[1].checked == false &&
		    form.tipoEntrega[2].checked == false ){
			alert(document.getElementById('mensajeErrorTipoEntrega').value);
			return false;
		}else{
			return true;
		}
	}else{
		return true;
	}
}

/* visualizacion.js */

// Descripcion: Funciones que sirven para la gestion de visualizacion de elementos,
//				submitir formularios,....
//

// Funcion que busca el formulario en el documento y realiza un submit
function submitFormulario(formularioId)
{
	var formulario = $(formularioId);
	if(formulario != null)
	{
		formulario.submit();
	}
}

function doClick(id){
	$(id).click();
}

//Funcionalidad de aumentar la cantidad de un elemento
function aumentar(id)
{
	var elemento = $(id);
	//le damos el foco
	elemento.focus();
	elemento.value = parseInt(elemento.value) + 1;
	//se lo kitamos
	elemento.blur();
}

//Funcionalidad de disminuir la cantidad de un elemento sin llegar a 0
function disminuir(id)
{
	var elemento = $(id);
	var valor = elemento.value - 1;
	if(valor > 0)
	{
		//le damos el foco
		elemento.focus();
		elemento.value = valor;
		//se lo kitamos
		elemento.blur();
	}
}

function aumentarDetalle(id,msgError)
{
	var elemento = $(id);

	if (elemento.value == '' || isNaN(elemento.value))
	{
		// Aviso y se asigna valor por defecto
		alert(msgError);
		return;
	}
	elemento.value = parseInt(elemento.value) + 1;
	if (parseInt(elemento.value) < 1)
	{
		alert(msgError);
		return;
	}
	else
	{
		var idBoton = "boton_"+id;
		$(idBoton).click();
	}
}

function disminuirDetalle(id,msgError)
{
	var elemento = $(id);

	if (elemento.value == '' || isNaN(elemento.value))
	{
		// Aviso y se asigna valor por defecto
		alert(msgError);
	return;
	}
	elemento.value = parseInt(elemento.value) - 1;
	if (parseInt(elemento.value) < 1)
	{
		alert(msgError);
		return;
	}
	else
	{
		var idBoton = "boton_"+id;
		$(idBoton).click();
	}
}

//Utilizada en el formulario del login para comprobar errores de cupon.
function comprobarCupon(){
	var txtCupon = document.getElementById('errorCupon');
	if(txtCupon != null){
		var texto = trim(txtCupon.value + "");
		alert(texto);
	}
}


//Utilizada en el formulario del login para activar y desactivar textfield de email y password
function comprobarRadioSelect()
{
      var misma=document.getElementById('mismaPersona');
      var otra=document.getElementById('otraPersona');
      if (misma!=null && otra!=null)
      {
	      if(misma.checked)
	      {
	            var campoEmail =document.getElementById('campoEmail');
	            campoEmail.disabled=true;
	            var campoPassword =document.getElementById('campoPassword');
	            campoPassword.disabled=true;
	      }
	      if(otra.checked)
	      {
	            var campoEmail =document.getElementById('campoEmail');
	            campoEmail.disabled=false;
	            var campoPassword =document.getElementById('campoPassword');
	            campoPassword.disabled=false;
	            limpiarTipoEntrega();
	      }
      }
      return;
}

function changeVisualizationOptionPurchaseDetails(id_contenedor) {
	var selectedOption = $('selectImagen').value;
	params = {"visualizationOption" : selectedOption};
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			method: 'POST',
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}

function changeVisualizationOptionPurchaseListDetails(id_contenedor,itemId) {
	var selectedOption = $('selectImagen').value;
	params = {"visualizationOption" : selectedOption, "indLista" : itemId};
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			method: 'POST',
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}

function changeVisualizationOptionPreviusOrderDetails(id_contenedor,itemId, subestado, fechaPedido) {
	var selectedOption = $('selectImagen').value;
	params = {"visualizationOption" : selectedOption, "pedidoId" : itemId, "subestado" : subestado, "fechaPedido" : fechaPedido};
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			method: 'POST',
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}

function showProductList(transport,containerID)
{
	if (transport.responseText.indexOf("<!-- Home -->") > 0){
		document.location="/alimentacion/HomeAlimentacion.aspx";
	}
	else{
		$(containerID).update(transport.responseText);
	}
}

//NAP
function changeVisualizacionNodoTerminalNap(itemId,anteriorSelected,selectedOption) {
	if (selectedOption==null||selectedOption=='')
	{
		selectedOption=-1;
	}
	if (((anteriorSelected==1 ||anteriorSelected==2)&& (selectedOption==3)) ||
		((anteriorSelected==3)&& (selectedOption==1 || selectedOption==2)))
	{
		//tenemos que actualizar path y tablaListado
		var recargaTodo ="si";
		params = {"visualizationOption" : selectedOption, "itemId" : itemId, "todo": recargaTodo , "nap" : 1};
		new Ajax.Request("ChangeVisualization.aspx",
			{
				parameters: params,
				onSuccess: function(transport){ showProductList(transport,'center');}
			}
		);
	}
	else
	{
		//solo recargar el tablaListado
		params = {"visualizationOption" : selectedOption, "itemId" : itemId, "nap" : 1};
		new Ajax.Request("ChangeVisualization.aspx",
			{
				parameters: params,
				onSuccess: function(transport){ showProductList(transport,'tablaListado');}
			}
		);
	}
}

function cargaVisualizationOptionNodoTerminalNap(id_contenedor,itemId,selectedOption) {
	if (selectedOption==null||selectedOption=='')
	{
		selectedOption=-1;
	}
	$('center').className="";
	$(id_contenedor).className="path";
	params = {"visualizationOption" : selectedOption, "itemId" : itemId};
	new Ajax.Request("IncNodoTerminalAjaxNap.aspx",
		{
			parameters: params,
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}

function changeVisualizacionListaProdNap(id_contenedor,itemId,selectedOption) {
	if (selectedOption==null || selectedOption=='')
	{
		selectedOption=-1;
	}
	params = {"visualizationOption" : selectedOption, "itemId" : itemId, "nap" : 1};
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			onSuccess: function(transport){ showProductList(transport,id_contenedor,params);}
		}
	);
}
//FIN NAP

//NODO TERMINAL
function cargandoNodoTerminal(mensaje)
{
	p=$('tablaListado');
	p.className="divSubhome";
	p.innerHTML = "<div>"
	+"<br/><br/><br/>"
	+"<table style='text-align:center'><tr><th>"
	+"<img src='/alimentacion/201111031215/media/es/web/imagenes/reloj_arena.gif' style='align:center'/></th></tr>" ;

	p.innerHTML += "<tr><th ><span class='producto' style='width:99%;font-weight:bold;font-size:11px;align:center'>"
	+mensaje
	+"</span></th></tr></table> </div>" ;
}
function cargaVisualizationOptionNodoTerminal(id_contenedor,itemId,selectedOption) {
	if (selectedOption==null||selectedOption=='')
	{
		selectedOption=-1;
	}
	$('center').className="";
	params = {"visualizationOption" : selectedOption, "itemId" : itemId};
	new Ajax.Request("IncNodoTerminalAjax.aspx",
		{
			parameters: params,
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}

function changeVisualizacionListaProd(id_contenedor,itemId,selectedOption,mensajeEspera) {
	cargandoNodoTerminal(mensajeEspera);
	if (selectedOption==null || selectedOption=='')
	{
		selectedOption=-1;
	}
	params = {"visualizationOption" : selectedOption, "itemId" : itemId};
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			onSuccess: function(transport){ showProductList(transport,id_contenedor,params);}
		}
	);
}

function changeVisualizacionNodoTerminal(itemId,anteriorSelected,selectedOption) {
	if (selectedOption==null||selectedOption=='')
	{
		selectedOption=-1;
	}
	if (((anteriorSelected==1 ||anteriorSelected==2)&& (selectedOption==3)) ||
		((anteriorSelected==3)&& (selectedOption==1 || selectedOption==2)))
	{
		//tenemos que actualizar path y tablaListado
		var recargaTodo ="si";
		params = {"visualizationOption" : selectedOption, "itemId" : itemId, "todo": recargaTodo };
		new Ajax.Request("ChangeVisualization.aspx",
			{
				parameters: params,
				onSuccess: function(transport){ showProductList(transport,'center');}
			}
		);
	}
	else
	{
		//solo recargar el tablaListado
		params = {"visualizationOption" : selectedOption, "itemId" : itemId };
		new Ajax.Request("ChangeVisualization.aspx",
			{
				parameters: params,
				onSuccess: function(transport){ showProductList(transport,'tablaListado');}
			}
		);
	}
}
//FIN NODO TERMINAL

function orderBySelect(itemId){
	var orderByProp = $('sel_orden').value;
	params = {"sortProperties" : orderByProp, "itemId" : itemId};
	var id_contenedor = "tablaListado";
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			method: 'POST',
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}

function orderBySelect(itemId,visualizationOption){
	var orderByProp = $('sel_orden').value;
	params = {"sortProperties" : orderByProp, "itemId" : itemId, "visualizationOption" : visualizationOption};
	var id_contenedor = "tablaListado";
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			method: 'POST',
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}


function orderBy(itemId,orderByProp){
	params = {"sortProperties" : orderByProp, "itemId" : itemId};
	var id_contenedor = "tablaListado";
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			method: 'POST',
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}

function orderBySelectNap(itemId){
	var orderByProp = $('sel_orden').value;
	params = {"sortProperties" : orderByProp, "itemId" : itemId, "nap" : 1};
	var id_contenedor = "tablaListado";
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			method: 'POST',
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}

function orderByNap(itemId,orderByProp){
	params = {"sortProperties" : orderByProp, "itemId" : itemId, "nap" : 1};
	var id_contenedor = "tablaListado";
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			method: 'POST',
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}

function paginacionFichaPromocion(url, pagina,id, promoId){

	params={"pagina":pagina,"id":id,"promoId":promoId};
	var id_contenedor = "listadoFichaPromocion";
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			method: 'POST',
			onSuccess: function(transport){showProductList(transport,id_contenedor);}
		}
	);
}

//funcion que refresca mediante Ajax cuando se hace click en el enlace anterior
function paginacion(url, pagina,itemId){

	params={"pagina":pagina,"itemId":itemId};
	var id_contenedor = "tablaListado";
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters: params,
			method: 'POST',
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}

//funcion que refresca mediante Ajax cuando se hace click en el enlace anterior
function paginacionListasPersonales(url, pagina, indLista){

	params={"pagina":pagina,"indLista":indLista};
	var id_contenedor = "center";
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters:params,
			method: 'POST',
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}

//funcion que refresca mediante Ajax cuando se hace click en el enlace anterior
function paginacionPedidosAnteriores(url, pagina){

	params={"pagina":pagina,"gestPedidos":"eee"};
	var id_contenedor = "center";
	new Ajax.Request("ChangeVisualization.aspx",
		{
			parameters:params,
			method: 'POST',
			onSuccess: function(transport){ showProductList(transport,id_contenedor);}
		}
	);
}

//funcion para comprobar si ha habido cambio de tienda
function comprueba_cambioTienda(cambio,origen,msg)
{
	if(cambio != null && cambio != '' && cambio=='true')
	{
		alert(msg);
	}
}

//actualiza el center con el detalle de mi compra
function mostrar_detalle_mi_compra(cambioTienda)
{
	$('center').className="";
	if (cambioTienda==true)
	{
		params = {"cambioTienda" : "true"};
	}
	else
	{
		params = {"cambioTienda" : "false"};
	}
	loadPurchaseDetails(params);
}

function comprueba_redireccion(value){
	if(value != null && value != ''){
		if(value == "gestionarListas"){
			mostrar_gestionar_listas();
		}
		if(value == "gestionarPedidosAnteriores"){
			mostrar_gestionar_pedidos_anteriores();
		}
		if(value == "miCompraCambioTienda"){
			mostrar_detalle_mi_compra(true);
		}
		if(value == "miCompraSinCambioTienda"){
			mostrar_detalle_mi_compra(false);
		}
		if(value == "preRegistro"){
			cargaPreRegistroCenter();
		}
	}
}

function guardarNavegacion(url){
	params = { "url" : url};
	new Ajax.Request("GuardarNavegacion.aspx",{
			parameters: params,
			asynchronous: false
		}
	);
}

