// Navegador
//------------------------------------------------------------------------------------------------
var ie = document.all ? 1 : 0;
var ns = document.layers ? 1 : 0;

// Popups
//------------------------------------------------------------------------------------------------
function abrePop(cual, nombre, alto, ancho, ajustable, scroll) {
	if (ie) {    
		window.open(cual, nombre, 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars='+scroll+',resizable='+ajustable+',copyhistory=no,width='+ancho+', height='+alto+', top=0, left=0');
	} else if (ns) {
		window.open(cual, nombre,'width=740,height=500,location=no,toolbar=no,directories=no,menubar=no,resizable='+ajustable+',scrollbars=yes, status=no');		
	} else {
		window.open(cual, nombre, 'left=0,top=0,width='+ancho+',height='+(alto+5)+',location=no,toolbar=no,directories=no,menubar=no,resizable='+ajustable+',scrollbars='+scroll+', status=no');
	}
}

// VALIDA un texto de tipo alfanumerico
// -----------------------------------------------------------------------------------------------

function esNumerico(texto){
    var valido 	= true; 
	var decimal	= false;
    var cadena = "1234567890";
	var i;
    for (i=0;i<texto.length;i++){

		caracter=texto.substr(i, 1);

		if(caracter==","){		// la "," es el símbolo decimal
			if(decimal==false){
				decimal=true;
			}else{
				valido=false;	// se encontro mas de una coma
				break;
			}
		}else{
			if (cadena.indexOf(caracter, 0) == -1){
				valido=false;
				break;
			}
		}
    }
    return valido;
}

// función GENÉRICA para cualquier formulario
//------------------------------------------------------------------------------------------------
function chekea(cual) {
	var i, tipo, valor;
	if (cual.elements) {
		for (i=0; i<cual.elements.length; i++) {
			if (cual.elements[i].name != null) {
				if (cual.elements[i].name.substr(0,4) == "chk|") {
					tipo = cual.elements[i].name.split("|");
					valor = cual.elements[i].value;
					//if (valor != null) alert(valor);
					switch (tipo[2]) {
						case "mce":	// editor MCE
							valor = tinyMCE.getContent();
							// Primero veo si es obligatorio RELLENARLO
							if ((valor.length == 0) && tipo[5] == "true") {
								alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
								tinyMCE.execCommand("mceFocus", cual.elements[i].name);// ERROR: no sitúa el cursor
								return false;
							}
							// Después veo si es menor que el mínimo
							if (tipo[5] == "true" && valor.length < parseInt(tipo[3],10)) {
								alert("El campo \""+tipo[6]+"\" NO puede ser menor de "+tipo[3]+" caracteres");				
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Y por último si es mayor que el máximo
							if (valor.length > parseInt(tipo[4],10)) {
								alert("El campo \""+tipo[6]+"\" NO puede ser mayor de "+tipo[4]+" caracteres");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							break;
						case "str":	// alfanumérico
							// Primero veo si es obligatorio RELLENARLO
							if ((valor.length == 0) && tipo[5] == "true") {
								alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después veo si es menor que el mínimo
							if (tipo[5] == "true" && valor.length < parseInt(tipo[3],10)) {
								alert("El campo \""+tipo[6]+"\" NO puede ser menor de "+tipo[3]+" caracteres");				
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Y por último si es mayor que el máximo
							if (valor.length > parseInt(tipo[4],10)) {
								alert("El campo \""+tipo[6]+"\" NO puede ser mayor de "+tipo[4]+" caracteres");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							break;
						case "int":	// numerico
							// Primero veo si es obligatorio RELLENARLO
							if ((valor.length == 0) && tipo[5] == "true") {
								alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después compruebo que sea NUMÉRICO
							if (!(esNumerico(valor))) {
								alert("El campo \""+tipo[6]+"\" debe ser NUMÉRICO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
									cual.elements[i].select();
								}
								return false;
							}
							// Después veo si es menor que el mínimo
							if (parseInt(valor,10) < parseInt(tipo[3],10)) {
								alert("El campo \""+tipo[6]+"\" NO puede ser menor que "+tipo[3]);
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Y por último si es mayor que el máximo
							if (parseInt(valor,10) > parseInt(tipo[4],10)) {
								alert("El campo \""+tipo[6]+"\" NO puede ser mayor que "+tipo[4]);
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
									cual.elements[i].select();
								}
								return false;
							}
							break;
						case "date":	// fecha
							// Primero veo si es obligatorio RELLENARLO
							if ((valor.length == 0) && tipo[5] == "true") {
								alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después compruebo que sea FECHA
							if (validaFecha(valor) != "ok" && valor != "") {
								alert("El campo \""+tipo[6]+"\" debe ser de tipo fecha: DD/MM/AAAA\n"+validaFecha(valor));
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después veo si es menor que el mínimo
							if (convierteFecha(valor) < convierteFecha(tipo[3])) {
								alert("El campo \""+tipo[6]+"\" NO puede ser menor de "+tipo[3]);
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después veo si es mayor que el máximo
							if (convierteFecha(valor) > convierteFecha(tipo[4])) {
								alert("El campo \""+tipo[6]+"\" NO puede ser mayor de "+tipo[4]);
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							break;
						case "fechaCad":	// fecha caducidad
							// Primero veo si es obligatorio RELLENARLO
							if ((valor.length == 0) && tipo[5] == "true") {
								alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después compruebo que sea FECHA
							if (validaFecha(valor) != "ok" && valor != "") {
								alert("El campo \""+tipo[6]+"\" debe ser de tipo fecha: DD/MM/AAAA\n"+validaFecha(valor));
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después compruebo que sea mayor que la actual
							if (convierteFecha(valor) < convierteFecha(devuelveFechaActual())){
								alert("El campo \""+tipo[6]+"\" NO puede ser menor que la fecha actual.");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
	
							// Después veo si es menor que el mínimo
							if (convierteFecha(valor) < convierteFecha(tipo[3])) {
								alert("El campo \""+tipo[6]+"\" NO puede ser menor de "+tipo[3]);
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después veo si es mayor que el máximo
							if (convierteFecha(valor) > convierteFecha(tipo[4])) {
								alert("El campo \""+tipo[6]+"\" NO puede ser mayor de "+tipo[4]);
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							break;
						case "eml":	//E-mail
							// Primero veo si es obligatorio RELLENARLO
							if ((tipo[5] == "true") && (valor.length == 0)) {
								alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después compruebo que sea EMAIL válido
							if ((esMail(valor)!=true) && (valor!="")){
								alert("El campo \""+tipo[6]+"\" debe ser una dirección de correo válida");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							break;
						case "file":	// archivo
							// Primero veo si es obligatorio RELLENARLO
	
							if ((valor == "") && tipo[5] == "true") {
								alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}		
	
							break;
						case "fechahora":	// fecha hora
							// Primero veo si es obligatorio RELLENARLO
							if ((valor.length == 0) && tipo[5] == "true") {
								alert("El campo \""+tipo[6]+"\" es OBLIGATORIO");
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Después compruebo que sea FECHA HORA
							if (validaFechaHora(valor) != "ok" && valor != "") {
								alert("El campo \""+tipo[6]+"\" debe ser de tipo fecha: DD/MM/AAAA hh:mm\n"+validaFechaHora(valor));
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							
							break;
						default:
							alert("No existen restricciones de tipo \""+tipo[2]+"\"");
							return false;
							break;
					}
				}
			}
		}
	}
	return true;
}

// COMPRUEBA que una fecha sea correcta
//------------------------------------------------------------------------------------------------
function validaFecha(dato){
	var fecha, dia, mes, ano, aux, formato;

	dia 	= dato.substr(0, 2);
	mes 	= dato.substr(3, 2);
	ano 	= dato.substr(6, 4);

	aux		= "DD"+dato.substr(2, 1)+"MM"+dato.substr(5, 1)+"AAAA";
	formato	= "DD/MM/AAAA";	// formato de fecha y hora
	
//	comprobamos si el formato recibido es el correcto
	if(isNaN(dia+mes+ano)==false && aux==formato && dato.length==formato.length){
		fecha=new Date(ano, mes-1, dia);
		
		if(fecha.getDate() != dia){
			aux="El día no es correcto";
		}else if(fecha.getMonth() != (mes-1)){
			 aux="El mes no es correcto";
		}else if(fecha.getFullYear() != ano){
			aux="El año no es correcto";
		}else{
			aux="ok"; // la fecha es correcta
		}
	}else{
		aux="'"+dato+"'";
	}
	return aux;
}

// CONVIERTE una FECHA
// -----------------------------------------------------------------------------------------------
function convierteFecha(quien) {
	var fecha_split;	
	var tdia, tmes, tano;
	fecha_split = quien.split('/');
	tdia = parseInt(fecha_split[0],10);
	tmes = parseInt(fecha_split[1],10);
	tano = parseInt(fecha_split[2],10);
	return date = new Date(tano,tmes-1,tdia);
}

// VALIDA un email
// -----------------------------------------------------------------------------------------------
function esMail(texto){
    var valido = true;             
    var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890@._-";
    var arroba = texto.indexOf("@", 0);
    if ((texto.lastIndexOf("@")) != arroba) arroba = -1;
    var punto = texto.lastIndexOf(".");
	var i;
    for (i=0 ;i<texto.length;i++){
		if (cadena.indexOf(texto.substr(i, 1),0) == -1){
			valido = false;
			break;
    	}
    }
	if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (texto.length)) && (valido == true) && (texto.indexOf("..",0) == -1)){
    	valido = true;
	}else{
		valido = false;
	}
    return valido;
}

// CAMBIA el valor de una variable de nº de registros
// -----------------------------------------------------------------------------------------------
function cambiaNumRs(todo, varQuery, varQueryValor) {
	window.location = ""+todo+"&"+varQuery+"="+varQueryValor;
}

// AÑADE un 0 a la izda de un nº de una cifra
// ------------------------------------------------------------------------------------------------
function numDosCifras(num){
	var aux =num;
	if (num < 10){
		aux = "0" + aux;
	}
	return aux;
}

// Para recargar un combo
// ------------------------------------------------------------------------------------------------------
function select_innerHTML(objeto,innerHTML){
	// Vaciamos el contenedor
	objeto.innerHTML = "";
	//creating phantom element to receive temp innerHTML
	var selTemp = document.createElement("micoxselect");
	var opt;
	selTemp.id="micoxselect1";
	document.body.appendChild(selTemp);
	selTemp = document.getElementById("micoxselect1");
	selTemp.style.display="none";
	if(innerHTML.toLowerCase().indexOf("<option")<0){//if not option, convert do option
		innerHTML = "<option>" + innerHTML + "</option>";
	}
	innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span");
	selTemp.innerHTML = innerHTML;
	var seleccionado = -1;
	//transfering childs of phantom element to options
	for(var i=0;i<selTemp.childNodes.length;i++){
		if(selTemp.childNodes[i].tagName){
			opt = document.createElement("OPTION");
			sel = selTemp.childNodes[i].getAttribute("selected");
			opt.value = selTemp.childNodes[i].getAttribute("value");
			opt.text = selTemp.childNodes[i].innerHTML;
			if(sel == "1"){
				opt.selected = "selected";
				seleccionado = i;
			}
			if(document.all){ //IEca
				objeto.add(opt);
			}else{
				objeto.appendChild(opt);
			}
		}
	}
	objeto.options[seleccionado].selected = "selected";
	//clear phantom
	document.body.removeChild(selTemp);
	selTemp = null;
}

// Para insertar hiddens con las familias y subfamilias que se están buscando y aparezcan desplegadas
// ------------------------------------------------------------------------------------------------------
function creaHiddens(form){
			if(form.bsqFamilia.value != "-1"){
				window.document.getElementById("hiddens").innerHTML += '<input type="hidden" name="padreURL" value="'+form.bsqFamilia.value+'" />';
			}
			if(form.bsqSubFamilia.value != "-1"){
				window.document.getElementById("hiddens").innerHTML += '<input type="hidden" name="hijoURL" value="'+form.bsqSubFamilia.value+'" />';
			}
		}


//  muestra y oculta las hojas de pedidos //
var hojaActiva = 0;
function muestraHojas(id,menu){
	for(i=0;i<7;i++){
		window.document.getElementById("pagina"+i).style.display="none";
		window.document.getElementById("iconoHoja"+i).innerHTML ="<img border=\"0\" title=\"\" alt=\"\" src=\"img/mas.gif\"/>";
		if (window.document.getElementById("pag"+i)) {
			window.document.getElementById("pag"+i).style.display="none";
		}
	}
	window.document.getElementById(id).style.display="block";
	hojaActiva = parseInt(id.replace("pagina", ""), 10);
	window.document.getElementById("iconoHoja"+hojaActiva).innerHTML ="<img border=\"0\" title=\"\" alt=\"\" src=\"img/menos.gif\"/>";
	if (window.document.getElementById(menu)) {	
		window.document.getElementById(menu).style.display="block";
	}
	regargaBotonesPaginas()
}
function cambiaHojaPedido(valor) {
	hojaActiva += valor;
	muestraHojas("pagina" + hojaActiva,"pag" + hojaActiva)
}
function regargaBotonesPaginas() {
	if (hojaActiva == 0) {
		window.document.getElementById("botonAnterior").style.visibility = "hidden";
		window.document.getElementById("botonAnterior2").style.visibility = "hidden";
		window.document.getElementById("botonSiguiente").style.visibility = "visible";
		window.document.getElementById("botonSiguiente2").style.visibility = "visible";
		window.document.getElementById("btnAceptar").style.visibility = "hidden";
	} else if (hojaActiva == 6) {
		window.document.getElementById("botonAnterior").style.visibility = "visible";
		window.document.getElementById("botonAnterior2").style.visibility = "visible";
		window.document.getElementById("botonSiguiente").style.visibility = "hidden";
		window.document.getElementById("botonSiguiente2").style.visibility = "hidden";
		window.document.getElementById("btnAceptar").style.visibility = "visible";
	} else {
		window.document.getElementById("botonAnterior").style.visibility = "visible";
		window.document.getElementById("botonAnterior2").style.visibility = "visible";
		window.document.getElementById("botonSiguiente").style.visibility = "visible";
		window.document.getElementById("botonSiguiente2").style.visibility = "visible";
		window.document.getElementById("btnAceptar").style.visibility = "visible";
	}
	if (hojaActiva == 0) {	
		window.document.getElementById("txtHoja").innerHTML = " - Datos generales";
	} else {
		window.document.getElementById("txtHoja").innerHTML = " - Hoja \"" + String.fromCharCode(64 + hojaActiva) + "\"";
	}
	
}

/*
function cambiaHojas(direccion){
		
	if(direccion==1){
		for(i=1;i<7;i++){
			if (document.getElementById("pagina"+i).style.display=="block"){alert("HOLA");
				i++;
				muestraHojas("pagina"+i,"pag"+i);
				alert("pagina"+i);
				break;
			}
		}
	}
	if(direccion==0){
		for(i=1;i<7;i++){
			if (window.document.getElementById("pagina"+i).style.display=="block"){
				i--;
				muestraHojas("pagina"+i,"pag"+i);
				break;
			}
		}
	}
}*/
