//
// los textos de los alerts los coge de utilsjsText.tpl
//

//MM_showHideLayers para la cesta
function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}



//Para el mouseover de las pestañas del menu
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}





function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
{
myfield.form.submit();
return false;
}
else
return true;
}

function muestra() {
ns4 = (document.layers)? true:false
ie4 = (document.all)? true:false
   if (ns4) {
     obj = document.menu
  }else  if (ie4) {
   obj = menu.style
 }else{
	 obj = document.getElementById("menu").style

	 }

 if (ns4)  obj.visibility = "show"
 else if(ie4)  obj.visibility = "visible"
 else
 	obj.visibility = "visible"
}

function oculta(obj) {
ns4 = (document.layers)? true:false
ie4 = (document.all)? true:false
   if (ns4) {
     obj = document.menu
  }else  if (ie4) {
   obj = menu.style
  }else{
	 obj = document.getElementById("menu").style
	 }
 if (ns4) obj.visibility = "hide"
 else if (ie4)  obj.visibility = "hidden"
 else
 	obj.visibility = "hidden"
}

function enviar(login) {
	document.getElementById(login).submit();
}


function procesarDatos(login) {
	//* los índices para phone_type1 corresponden a:
	//												0: mobile
	//												1: home
	//* los índices para phone_type2 corresponden a:
	//												0: --
	//												1: mobile
	//												2: home
	var phone_type1 = document.getElementById('phone_type1').selectedIndex;
	var phone_type2 = document.getElementById('phone_type2').selectedIndex;
	var phone_1 = document.getElementById('phone_1').value;
	var phone_2 = document.getElementById('phone_2').value;
	// [Xavier Arnaus 12/08/2008]
	// Toma de valores para birth_date check
	var birth_day_idx 	= document.getElementById('birth_day').selectedIndex;
	var birth_month_idx = document.getElementById('birth_month').selectedIndex;
	var birth_year_idx 	= document.getElementById('birth_year').selectedIndex;
	var birth_day 	= document.getElementById('birth_day')[birth_day_idx].value;
	var birth_month = document.getElementById('birth_month')[birth_month_idx].value;
	var birth_year 	= document.getElementById('birth_year')[birth_year_idx].value;
	var now = new Date();
	var isleap = ((birth_year % 4 == 0 && birth_year % 100 != 0) || birth_year % 400 == 0);
	// [Xavier Arnaus 12/08/2008]
	// Check for adult
	if (getTimestamp(birth_day, birth_month, birth_year) > getTimestamp(now.getDate(), now.getMonth()+1, now.getFullYear()-16)) {
		//alert('No puedes ser usuario de Privalia siendo menor de 16 años.');
		alert(s_alert_16age);
	}
	//[Xavier Batlle & Maure Noguera 23/08/08}
	//check for month days
	else if ((birth_month==4 || birth_month==6 || birth_month==9 || birth_month==11) && birth_day==31) {
		//alert("Este mes no tiene 31 días");
		alert(s_alert_31days);
	}
	
	else if (birth_month == 2 && birth_day>29 || (birth_day==29 && !isleap && birth_month == 2)) { // check for february 29th
		//alert("Febrero del año " + birth_year + " no tuvo " + birth_day + " días");
		alert(s_alert_february + birth_year + s_alert_donthave + birth_day + s_alert_days);
	}
	else if (phone_1 != '' && phone_type1 == '0' && phone_1.charAt(0) != '6') {
		//alert('Revisa los datos del teléfono de contacto. El número indicado no corresponde a un teléfono movil');
		alert(s_alert_notacell);
	}

	else if (phone_1 != '' && phone_type1 == '1' && phone_1.charAt(0) != '9') {
		alert(s_alert_notatlp);
	}

	else if (phone_2 != '' && phone_type2 == '1' && phone_2.charAt(0) != '6') {
		alert(s_alert_notacellad);
	}

	else if (phone_2 != '' && phone_type2 == '2' && phone_2.charAt(0) != '9') {
		alert(s_alert_notatlpad);
	}
	else if (phone_1 != '' && phone_2 != '') {
		//if (phone_type1 == 0 && phone_type2 == 1) alert('Solo podemos guardar un teléfono movil');
		if (phone_type1 == 0 && phone_type2 == 1) alert(s_alert_onecell);
		//else if (phone_type1 == 1 && phone_type2 == 2) alert('Solo podemos guardar un teléfono fijo');
		else if (phone_type1 == 1 && phone_type2 == 2) alert(s_alert_onetlp);
		else enviar(login);

	}
	
	else {
		enviar(login);
	}
}

// [Xavier Arnaus 12/08/2008]
// Returns the timestamp from a given date
function getTimestamp(day, month, year)
{
var dia_aux = parseInt(day,10);
var mes_aux = parseInt(month,10);
var ano_aux = parseInt(year,10);
var fecha = new Date();
fecha.setFullYear(ano_aux);
fecha.setMonth(mes_aux-1);
fecha.setDate(dia_aux);
fecha.setHours(0);
fecha.setMinutes(0);
fecha.setSeconds(0);
fecha.setMilliseconds(0);
var timestamp = parseInt(fecha.getTime(),10);
alert(day+'/'+month+'/'+year+':  '+timestamp);

return timestamp;
}
//
//comprueba ademas el telefono de la direccion
//
function procesarDatosTelf(login, phone_dir) {
	//* los ï¿½ndices para phone_type1 corresponden a:
	//												0: mobile
	//												1: home
	//* los ï¿½ndices para phone_type2 corresponden a:
	//												0: --
	//												1: mobile
	//												2: home
	var phone_type1 = document.getElementById('phone_type1').selectedIndex;
	var phone_type2 = document.getElementById('phone_type2').selectedIndex;
	var phone_1 = document.getElementById('phone_1').value;
	var phone_2 = document.getElementById('phone_2').value;

	var phone_3 = document.getElementById(phone_dir).value;
	
	if (phone_1 != '' && phone_type1 == '0' && phone_1.charAt(0) != '6') {
		//alert('Revisa los datos del teléfono de contacto. El número indicado no corresponde a un teléfono movil');
		alert(s_alert_notacell);
	}

	else if (phone_1 != '' && phone_type1 == '1' && phone_1.charAt(0) != '9') {
		//alert('Revisa los datos del teléfono de contacto. El número indicado no corresponde a un teléfono fijo');
		alert(s_alert_notatlp);
	}

	else if (phone_2 != '' && phone_type2 == '1' && phone_2.charAt(0) != '6') {
		//alert('Revisa los datos del teléfono adicional. El número indicado no corresponde a un teléfono movil');
		alert(s_alert_notacellad);
	}

	else if (phone_2 != '' && phone_type2 == '2' && phone_2.charAt(0) != '9') {
		//alert('Revisa los datos del teléfono adicional. El número indicado no corresponde a un teléfono fijo');
		alert(s_alert_notatlpad);
	}

	else if (phone_3 != '' && phone_3.charAt(0) != '9' && phone_3.charAt(0) != '6') {
		//alert('Revisa los datos del teléfono de dirección. El número indicado no corresponde a un teléfono válido');
		alert(s_alert_notadirtlp);
	}

	else if (phone_3.length != 0 && phone_3.length != 9 || isNaN(phone_3)) {
		//alert('Revisa los datos del teléfono de dirección. El número indicado no corresponde a un teléfono válido');
		alert(s_alert_notadirtlp);
	}

	else if (phone_1 != '' && phone_2 != '') {
		//if (phone_type1 == 0 && phone_type2 == 1) alert('Solo podemos guardar un teléfono movil');
		if (phone_type1 == 0 && phone_type2 == 1) alert(s_alert_onecell);
		else if (phone_type1 == 1 && phone_type2 == 2) alert(s_alert_onetlp);
		//else if (phone_type1 == 1 && phone_type2 == 2) alert('Solo podemos guardar un teléfono fijo');
		else enviar(login);
	}

	else {
		enviar(login);
	}
}


// [Xavier Arnaus 12/08/2008]
// Returns the timestamp from a given date
function getTimestamp(day, month, year)
{
var dia_aux = parseInt(day,10);
var mes_aux = parseInt(month,10);
var ano_aux = parseInt(year,10);
var fecha = new Date();
fecha.setFullYear(ano_aux);
fecha.setMonth(mes_aux-1);
fecha.setDate(dia_aux);
fecha.setHours(0);
fecha.setMinutes(0);
fecha.setSeconds(0);
fecha.setMilliseconds(0);
var timestamp = parseInt(fecha.getTime(),10);

return timestamp;
}





function addToCart(login)
{
	//* Mï¿½nica (09/10/2007) Si el producto tiene atributos, y no tiene ningï¿½n valor seleccionado, se muestra un alert informativo.
	if((typeof(document.getElementById('attrib1')) != 'undefined') && (attr1_label != '') ) {
		if(document.getElementById('attrib1').value == '') {
			alert(s_alert_necessary + attr1_label + s_alert_toadd);
			return;
		}
	}
	/* Natali (06/08/08) Cada vez que se sube algun producto al carrito se agrega al formulario un
	 * un input hidden con un numero aleatorio que se pasara por post y servirá verificar que el usuario
	 * ha hecho click sobre el boton de "anyadir a la cesta" y no un F5 por ejemplo.
	 */
	document.getElementById("hidden").value = Math.random() * 1000;

    //12/05/2010 - Problemas con Facebook por falta de action
    // 2010/08/03 Carles Mateo
    // Això fallava amb IE7 perquè hi ha una variable hidden anomenada 'action'.
    // La he canviat per 'actionAdd'
    
    var act =  document.getElementById(login).getAttribute('action');
    if (! act) {
        act = window.location.href.split('?');

        // Carles Mateo cmateo: Un cop hem elimiant els input hidden='action' que fan conflicte amb el
        // formulari.action ja podem emprar getAttribute i setAttribute amb IE7        
             document.getElementById(login).setAttribute('action', act[0]);
        
    }
   
	document.getElementById(login).submit();

	
	
	

}

function enviarConParams(s_formId, s_params) {
	var form = document.getElementById(s_formId);
	form.action += s_params;
	form.submit();
}


function unsuscribe(login, option)
{
	document.getElementById("type_remove").value = option;
	document.getElementById(login).submit();

}

/**
 * Funciï¿½n que comprueba el tamaï¿½o que se ha introducido en un textarea. Si el tamaï¿½o del texto excede
 * el mï¿½ximo permitido, mostrarï¿½ un mensaje de error.
 * @params string s_string: Cadena de caracteres a comprobar.
 * @params integer i_max_length: Nï¿½mero mï¿½ximo de caracteres permitidos.
 * @returns boolean. True si es un numero entero sin signo o false en caso contrario.
 */
function checkMaxLength(s_string, i_max_length){
	if(s_string.length >= i_max_length){
		//alert('Has superado el tamaño máximo de caracteres permitidos.');
		alert(s_alert_maxchar);
		return false;
	}
	return true;
}


/**
 * Funciï¿½n que comprueba si el parï¿½metro es un numero entero sin signo.
 * @params integer i_number: Nï¿½mero a comprobar.
 * @returns boolean. True si es un numero entero sin signo o false en caso contrario.
 */
function isUnsignedInteger(i_yourNumber)
{
	var s_template = /^\d+$/; //Formato de numero entero sin signo
	return s_template.test(i_yourNumber);
}



/**
 * Funcion para ocultar o mostrar el contenido de la ayuda
 *
 *
 */
	function setHelpActiveItem(helpItems, helpItem) {
		obj_helpBar = document.getElementById('helpBar'); //la barra que separa el menu del texto y que solo se verï¿½ en caso de que el texto este visible
		for(key in helpItems) {
			if(obj_helpItem = document.getElementById(helpItems[key])) {
				if(helpItems[key] == helpItem) {
					// if not expanded then expand, else contract
					if(obj_helpItem.style.display != "block") {
						obj_helpItem.style.display="block";
						obj_helpBar.style.display="block";
					} else {
						obj_helpItem.style.display="none";
						obj_helpBar.style.display="none";
					}
				} else {
					obj_helpItem.style.display="none";
				}
			}
		}
	}

	var helpItems = new Array(	"dummy",
								"helpItem1", "helpItem2", "helpItem3", "helpItem4",
								"helpItem5", "helpItem6", "helpItem7", "helpItem8",
								"helpItem9", "helpItem10", "helpItem11", "helpItem12");

	activeItemID = '';
	if(activeItemID != '') {
		activeItem = 'helpItem' + activeItemID;
		setHelpActiveItem(helpItems, activeItem);
	}
	
// [Xavier Arnaus 12/8/2008]
// Check NIF validity
// Took from backoffice/application/views/helpers/SpanishVatNumber.php by Gerard Edo
function checkNIF(a)
{ //Entra un this desde el input
	var temp=a.toUpperCase();
	var cadenadni="TRWAGMYFPDXBNJZSQVHLCKET";
	var v1 = new Array(0,2,4,6,8,1,3,5,7,9);
	if (temp!=='')
	{
		if (!/^[ABCDEFGHKLMNPQSX]/.test(temp))/*No es un CIF ni un NIE, es un DNI*/
		{
			posicion = a % 23; /*Resto de la division entre 23 es la posicion en la cadena*/
			letra = cadenadni.charAt(posicion);
			if (!/^[A-Za-z0-9]{9}$/.test(temp))
			{ //Es menos de 9 dígitos, añadimos la letra
				//alert('El DNI tiene que tener 9 dígitos');
				alert(s_alert_9dni);
				a=a+letra ;
			}
			else
			{ //Tiene los 9 dígitos, comprobamos si la letra esta bien
				posicion = a.substring(8,0) % 23; /*Resto de la division entre 23 es la posicion en la cadena*/
				letra = cadenadni.charAt(posicion);
				var letradni=temp.charAt(8);
				if (letra != letradni)
				{
					//alert("Error al introducir el DNI");
					alert(s_alert_dnierror);
				}
			}
		}
		else
		{ //Es un NIE o un CIF
			if (/^[X]/.test(temp))
			{ //Es un NIE
				var temp1=temp.substr(1,8);
				posicion = temp1 % 23; /*Resto de la division entre 23 es la posicion en la cadena*/
				letra = cadenadni.substring(posicion,posicion+1);
				if (!/^[A-Za-z0-9]{9}$/.test(temp))
				{ //Es menos de 9 dígitos, añadimos la letra
					//alert('El NIE tiene que tener 9 dígitos');
					alert(s_alert_9nie);
					a=a+letra ;
				}
				else
				{ //Tiene los 9 dígitos, comprobamos si la letra esta bien
					var temp1=temp.substr(1,7);
					posicion = temp1 % 23; /*Resto de la division entre 23 es la posicion en la cadena*/
					letra = cadenadni.charAt(posicion);
					var letranie=temp.charAt(8);
					if (letra != letranie)
					{
						//alert("Error al introducir el NIE");
						alert(s_alert_nieerror);
					}
				}
			}
			else
			{ //Es un CIF
				var cifcontrol = 0;
				for( i = 2; i <= 6; i += 2 )
				{
					cifcontrol = cifcontrol + v1[ parseInt(temp.substr(i-1,1)) ];
					cifcontrol = cifcontrol + parseInt(temp.substr(i,1));
				};
				cifcontrol = cifcontrol + v1[ parseInt(temp.substr(7,1)) ];
				cifcontrol = (10 - ( cifcontrol % 10));

				if (!/^[A-Za-z0-9]{9}$/.test(temp))
				{ //Es menos de 9 dígitos, añadimos el dígito de control
					//alert('CIF has to have 9 digits');
					alert(s_alert_9cif);
					a=a+cifcontrol;
				}
				else
				{
					if (cifcontrol!=temp.substr(8,1))
						alert ('Control number on CIF is wrong. Correct is '+cifcontrol);
				}
			}
		}
	}
}

// Xavier Batlle 12-8-08
//Añadida función para comprobar que algún checkbox está marcado en el último paso del proceso de darse de baja
function isChecked(remove)
	{
		var b=false;
		var form=document.getElementById(remove);
		
		
		for(i=0; i<form.elements.length; i++)
		{
		    var element = form.elements[i];
			if (element.type == "checkbox" && element.checked){
				b=true;
			} else if(element.type=="textarea" && element.value!='')
					{
						b=true;
					}
			
		}
		//if(b==false) {alert('No has marcado ninguna opción');}
		if(b==false) {alert(s_alert_nooption);}
		return b;
	}