// Documento JavaScript. Funciones genéricas
function checkDatosForm(objForm) {
	var alerta = 0;
		//campos texto
	if((document.getElementById("usr_nombre_apellidos").value == '') | 
	(document.getElementById("usr_nif").value == '') | 
	(document.getElementById("usr_email").value == '') |
	(document.getElementById("usr_telefono").value == '') |
	(document.getElementById("usr_direccion").value == '') |
	(document.getElementById("usr_poblacion").value == '') |
	(document.getElementById("usr_cp").value == '') |
	(document.getElementById("usr_provincia").value == '')
	){
		alerta = 1;
	}
	
		//selects
	/*
	 * Patch 0905: Se elimina el listado de provincias. 
	 * La provincia se calcula dinámicamente a través del código postal.
	 */
	 /*
	 
	if (document.getElementById("data[usr_provincia]").options[document.getElementById("data[usr_provincia]").selectedIndex].value== ''){
		alerta = 1;
	}	
	*/

	alertaMsj = '';
	if (alerta) alertaMsj = 'Debe rellenar TODOS los campos marcados con *.\n';
	
	//validación de email
	var filter= /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (!filter.test(document.getElementById("usr_email").value)){
		alerta = 1;
		alertaMsj +=  'El valor del campo email no es correcto.\n';
	}
	
	if (document.getElementById("usr_envio_email").value!=""){//sólo si no está vacío ya que este no es obligatorio
		if (!filter.test(document.getElementById("usr_envio_email").value)){
			alerta = 1;
			alertaMsj +=  'El valor del campo email de envío no es correcto.\n';
		}
	}

	//validación de provincias. 
	if (document.getElementById("usr_provincia_ok").value == 0){
		alerta = 1;
		alertaMsj +=  'El valor del campo código postal no es correcto.\n';
	}
	
	//usr_envio_provincia_ok sólo valida si el campo de usr_envio_cp no está vacío
	if ((document.getElementById("usr_envio_provincia_ok").value == 0)& 
			(document.getElementById("usr_envio_cp").value != '') ){
		alerta = 1;
		alertaMsj +=  'El valor del campo código postal de envío no es correcto.\n';
	}
	
	//validación de NIF
	if (!validaNif(document.getElementById("usr_nif").value)){
		alerta = 1;
		alertaMsj +=  'Por favor introduzca un NIF o NIE válido con el formato correcto, sin espacios ni guiones.\n';
	}
	
	if (alerta){
		window.alert(alertaMsj);
		return false;
	}else{
		objForm.submit();
		return false;
		
	}
}

function someteKartDatosForm(){
	if (document.kart_form){
		//paso las observaciones al formulario
		document.kart_form.kart_observaciones.value = document.getElementById("kart_obs_visible").value;
        if(document.kart_form.nodatos.value==0){//formulario completo
            /*
		 	* Patch 0905: este código ya no es necesario
			if (checkDatosForm(document.kart_form)){
                //someto
                document.kart_form.submit();
                return false;
            }else{
                return false;	
            }
			*/
			//esto ya hace el submit si los datos son correctos y devuelve false.
			checkDatosForm(document.kart_form);
			return false;
         }else{//distingo si hay envío a terceros
		 	if (document.getElementById('kart_envio_terceros').checked){
				checkEnvioTercerosDatosForm(document.kart_form);
				return false;
			}else{
	         	document.kart_form.submit();
	            return false;
			}
         }
	}else{
		return true;	
	}
}

function unblockCp(inputObj, dstId, url_root){
	//alert('cargando ajax:\n -cp='+inputObj.value+'\n -prefix='+dstId);
	cargarAsincrono(url_root+'ajax_provincia.php?cp='+inputObj.value+'&prefix='+dstId, 'ajax_'+dstId);
}

function blockCp(dstId){
	document.getElementById(dstId+"_ok").value = 0;
}

function toggleEnvioTerceros(checkObj){
//alert('checkObj.checked = '+checkObj.checked+'\n datos1.style.display = '+document.getElementById('datos_1').style.display);
	if (checkObj.checked){
		//muestro form
		document.getElementById('datos_1').style.display = 'none';
		document.getElementById('datos_2').style.display = 'block';
	}
	else{
		//oculto form
		document.getElementById('datos_1').style.display = 'block';
		document.getElementById('datos_2').style.display = 'none';
		//borro los campos
		document.getElementById("kart_envio_nombre").value = '';
		document.getElementById("kart_envio_direccion").value = '';
		document.getElementById("kart_envio_poblacion").value = '';
		document.getElementById("kart_envio_cp").value = '';
		document.getElementById("kart_envio_provincia").value = '';
		document.getElementById("kart_envio_provinciaStr").value = '';
		document.getElementById("kart_envio_telefono").value = '';
		document.getElementById("kart_envio_email").value = '';
		document.getElementById("kart_envio_forma").value = '';
		document.getElementById("prov_msj").innerHTML = '';
		
		
	}
}

function checkEnvioTercerosDatosForm(objForm) {
	var alerta = 0;
		//campos texto
	if((document.getElementById("kart_envio_nombre").value == '') | 
	(document.getElementById("kart_envio_direccion").value == '') | 
	(document.getElementById("kart_envio_poblacion").value == '') |
	(document.getElementById("kart_envio_cp").value == '') |
	(document.getElementById("kart_envio_provincia").value == '') |
	(document.getElementById("kart_envio_telefono").value == '') |
	(document.getElementById("kart_envio_email").value == '') |
	(document.getElementById("kart_envio_forma").value == '')
	){
		alerta = 1;
	}

	alertaMsj = '';
	if (alerta) alertaMsj = 'Debe rellenar TODOS los campos marcados con *.\n';
	
	//validación de email
	var filter= /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (!filter.test(document.getElementById("kart_envio_email").value)){
		alerta = 1;
		alertaMsj +=  'El valor del campo email no es correcto.\n';
	}

	//validación de provincias
	if (document.getElementById("kart_envio_provincia_ok").value == 0){
		alerta = 1;
		alertaMsj +=  'El valor del campo código postal no es correcto.\n';
	}
	
	if (alerta){
		window.alert(alertaMsj);
		return false;
	}else{
		objForm.submit();
		return false;
		
	}
}

function kartConfirm(url_root){
	if (confirm('¿Confirma el envío del pedido?')){
		//showLightbox();//sustituyo por lo siguiente
		window.location.href = url_root+'?pagina=confirmar';
		document.getElementById ('extranet_content').innerHTML = '<div class="extranet_cargando"></div>';
	}else{
		return false;
	}
}

function kartConfirmFormaPago(objForm){
	if (objForm.fromform.value==1){//se requiere confirmación de forma de pago
		var alerta = true; 
		for (var i=0; i<objForm.usr_pago_forma.length; i++){
			alerta = (alerta)&(!(objForm.usr_pago_forma[i].checked));
		}
		if (alerta){
			window.alert('Debe seleccionar una forma de pago.');
			return false;
		}
	}
	if (confirm('¿Confirma el envío del pedido?')){
		//showLightbox();//sustituyo por lo siguiente
		objForm.submit();
		document.getElementById ('extranet_content').innerHTML = '<div class="extranet_cargando"></div>';
	}else{
		return false;
	}
}

function delDatosEnvio(objForm) {
	/*
	Borra los campos del formulario de datos de envío de la extranet.
	*/
	document.getElementById("usr_envio_nombre").value = '';
	document.getElementById("usr_envio_direccion").value = '';
	document.getElementById("usr_envio_poblacion").value = '';
	document.getElementById("usr_envio_cp").value = '';
	document.getElementById("usr_envio_provincia").value = '';
	document.getElementById("usr_envio_provinciaStr").value = '';
	document.getElementById("usr_envio_provincia_ok").value = 0;
	document.getElementById("usr_envio_telefono").value = '';
	document.getElementById("usr_envio_email").value = '';
}

function validaCif(cif) {
	return validaNif(cif)
}

function validaNif(nif) {
	var res = validarDocumento(nif);
	
	if (res==1 | res==2 | res==3) return true;
	else return false;
}

//Retorna: 1 = NIF ok, 2 = CIF ok, 3 = NIE ok, -1 = NIF error, -2 = CIF error, -3 = NIE error, 0 = ??? error
function validarDocumento(a) {

	var temp = a.toUpperCase();
	var cadenadni = "TRWAGMYFPDXBNJZSQVHLCKE";

	if (temp !== '') {
		//si no tiene un formato valido devuelve error
		if ((!/^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp) && !/^[T]{1}[A-Z0-9]{8}$/.test(temp)) && !/^[0-9]{8}[A-Z]{1}$/.test(temp)) {
			return 0;
		}

		//comprobacion de NIFs estandar
		if (/^[0-9]{8}[A-Z]{1}$/.test(temp)) {
			posicion = a.substring(8, 0) % 23;
			letra = cadenadni.charAt(posicion);
			var letradni = temp.charAt(8);
			if (letra == letradni) {
				return 1;
			} else {
				return -1;
			}
		}

		//algoritmo para comprobacion de codigos tipo CIF
		suma = parseInt(a.charAt(2)) + parseInt(a.charAt(4)) + parseInt(a.charAt(6));
		for (i = 1; i < 8; i += 2) {
			temp1 = 2 * parseInt(a.charAt(i));
			temp1 += '';
			temp1 = temp1.substring(0, 1);
			temp2 = 2 * parseInt(a.charAt(i));
			temp2 += '';
			temp2 = temp2.substring(1, 2);
			if (temp2 == '') {
				temp2 = '0';
			}
			suma += (parseInt(temp1) + parseInt(temp2));
		}
		suma += '';
		n = 10 - parseInt(suma.substring(suma.length - 1, suma.length));

		//comprobacion de NIFs especiales (se calculan como CIFs)
		if (/^[KLM]{1}/.test(temp)) {
			if (a.charAt(8) == String.fromCharCode(64 + n)) {
				return 1;
			} else {
				return -1;
			}
		}

		//comprobacion de CIFs
		if (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp)) {
			temp = n + '';
			if (a.charAt(8) == String.fromCharCode(64 + n) || a.charAt(8) == parseInt(temp.substring(temp.length - 1, temp.length))) {
				return 2;
			} else {
				return -2;
			}
		}

		//comprobacion de NIEs
		//T
		if (/^[T]{1}[A-Z0-9]{8}$/.test(temp)) {
			if (a.charAt(8) == /^[T]{1}[A-Z0-9]{8}$/.test(temp)) {
				return 3;
			} else {
				return -3;
			}
		}

		//XYZ
		if (/^[XYZ]{1}/.test(temp)) {
			//pos = str_replace(['X', 'Y', 'Z'], 0, ['0', '1', '2'], temp).substring(0, 8) % 23;
			temp = temp.replace('X','0');
			temp = temp.replace('Y','1');
			temp = temp.replace('Z','2');
			pos = temp.substring(0, 8) % 23;
			if (a.charAt(8) == cadenadni.substring(pos, pos + 1)) {
				return 3;
			} else {
				return -3;
			}
		}
	}
	return 0;
}

function str_replace(search, replace, subject, count) {
	// Replaces all occurrences of search in haystack with replace  
	// 
	// version: 1109.2015
	// discuss at: http://phpjs.org/functions/str_replace    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Gabriel Paderni
	// +   improved by: Philip Peterson
	// +   improved by: Simon Willison (http://simonwillison.net)
	// +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)    // +   bugfixed by: Anton Ongson
	// +      input by: Onno Marsman
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +    tweaked by: Onno Marsman
	// +      input by: Brett Zamir (http://brett-zamir.me)    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   input by: Oleg Eremeev
	// +   improved by: Brett Zamir (http://brett-zamir.me)
	// +   bugfixed by: Oleg Eremeev
	// %          note 1: The count parameter must be passed as a string in order    // %          note 1:  to find a global variable in which the result will be given
	// *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
	// *     returns 1: 'Kevin.van.Zonneveld'
	// *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
	// *     returns 2: 'hemmo, mars'    var i = 0,
	j = 0, temp = '', repl = '', sl = 0, fl = 0, f = [].concat(search), r = [].concat(replace), s = subject, ra = Object.prototype.toString.call(r) === '[object Array]', sa = Object.prototype.toString.call(s) === '[object Array]';
	s = [].concat(s);
	if (count) {
		this.window[count] = 0;
	}
	for (i = 0, sl = s.length; i < sl; i++) {
		if (s[i] === '') {
			continue;
		}
		for (j = 0, fl = f.length; j < fl; j++) {
			temp = s[i] + '';
			repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
			s[i] = (temp).split(f[j]).join(repl);
			if (count && s[i] !== temp) {
				this.window[count] += (temp.length - s[i].length) / f[j].length;
			}
		}
	}
	return sa ? s : s[0];
}
