/*globals $ window document */
// the line above helps JSLint ignore certain globals; keep it and customize it if you're using JSLint's "good parts" to check your scripts

// The script below does essentially nothing other than define some nearly empty methods and a few settings for demonstration purposes
// You can delete this whole thing, or do whatever you want with it, it's just a basic starting point that I've been using lately

$(function () {
	// variable for caching settings
	var s = null,

	PrimaryNameSpace = {
		// define your oft-used settings below
		settings: {
			basicExample: $("#main"),
			nestedExample: {
				first: true,
				second: true,
				third: true,
				fourth: true,
				fifth: ['one', 'two', 'three', 'four', 'five', 'six']
			},

			foo: "bar"
		},

		// the method that initializes stuff
		init: function () {
			/*	the line below can be included in each method to reference the settings 
				without always having to type "this.settings" each time */
			s = this.settings;
			// using firebug you can view all settings with "console.log(s)";

			// after you do stuff here, you can call the next method
			// You can use "this" in the current context to reference "PrimaryNameSpace" directly
			this.nextMethod();

		},
		
		nextMethod: function () {
			s = this.settings;
			// do stuff here
		},
		
		anotherMethod: function () {
			s = this.settings;
			// do more stuff here
		}

		// remember not to use a trailing comma after the last method is defined; you could leave a dummy method here to prevent that error
	};

	// This line initializes the whole thing; you could pass in some JSON data or some other object that needs to be worked with
	PrimaryNameSpace.init();

});
//validar login
function ValidoLoginCabecera(NombreForm){
	//alert(document.getElementById("contra").value)
	//valido si los campos del formulario son correctos
	if (document.getElementById("usuario").value.length==0 || document.getElementById("usuario").value=="Email/Usuario"){
		alert("Debe introducir su Email/Usuario para continuar");
		document.getElementById("usuario").focus();
		return false;
	}
	if (document.getElementById("contra").value.length==0 || document.getElementById("contra").value=="Clave") {
		alert("Debe introducir la Clave para continuar");
		document.getElementById("contra").focus();
		return false;
	}
	return true;
}
function Valido(NombreForm){
	//valido si los campos del formulario son correctos
	//cuando hay varios formularios iguales por ejemplo en pestanas no fucniona correctamente, ahora validamos en base al objeto
	if ($(NombreForm).children('input[name="usuario"]').val()==""){
		alert("Debe introducir su Email/Usuario para continuar");
		$(NombreForm).children('input[name="usuario"]').focus();
		return false;
	}
	if ($(NombreForm).children('input[name="pass"]').val()=="") {
		alert("Debe introducir la Clave para continuar");
		$(NombreForm).children('input[name="pass"]').focus();
		return false;
	}

	/*
	if (document.getElementById("usuarioWeb").value.length==0){
		alert("Debe introducir su Email/Usuario para continuar");
		document.getElementById("usuarioWeb").focus();
		return false;
	}
	if (document.getElementById("contraWeb").value.length==0) {
		alert("Debe introducir la Clave para continuar");
		document.getElementById("contraWeb").focus();
		return false;
	}
	*/
	return true;
}
//JS de Fisterrae
//Comorbilidad
function ValidoPato(numero){
		j=0;
		for (i=1; i<=numero; i++) {
		    if (document.getElementById("idPatologia"+i).checked) {
		      j=j+1
		    }
		  }
		 if(j<2){
		 	alert("Seleccione al menos 2 patologias para obtener consejos y/o advertencias relacionadas")
		 	return false;
		 }
		 else{
		 	return true;
		 }
}
function desabilitaPato(valor,numero){
	for (v=1; v<=numero; v++) {
	    document.getElementById("idPatologia"+v).disabled=false;
	  }
	document.getElementById("idPatologia"+valor).checked=false;
	document.getElementById("idPatologia"+valor).disabled=true;
}

function ValidoApartados(){
	 if(document.getElementById("apartado1").checked==false && document.getElementById("apartado2").checked==false&& document.getElementById("apartado3").checked==false && document.getElementById("apartado4").checked==false){
	 	alert("Seleccione al menos 1 apartado para obtener advertencias y/o recomendaciones relacionadas")
	 	return false;
	 }
	 if(document.getElementById("tipo1").checked==false && document.getElementById("tipo2").checked==false){
	 	alert("Seleccione al menos 1 tipo para obtener advertencias y/o recomendaciones relacionadas")
	 	return false;
	 }
	 else{
	 	return true;
	 }
}
function filtrar(){
	if (document.getElementById("filtroRegistros").style.visibility=="hidden"){
		document.getElementById("filtroRegistros").style.visibility="visible";
		document.getElementById("filtroRegistros").style.display="block";
	}
	else{
		document.getElementById("filtroRegistros").style.visibility="hidden";
		document.getElementById("filtroRegistros").style.display="none";
	}
}

//vademecum
function AjaxGenerica(){
	/* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por
	lo que se puede copiar tal como esta aqui */
	var xmlhttp=false; 
	try 
	{ 
		// Creacion del objeto AJAX para navegadores no IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch(e)
	{ 
		try
		{ 
			// Creacion del objet AJAX para IE 
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch(E) { xmlhttp=false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest(); } 
	return xmlhttp; 
}

function AjaxNomenclator(orden){
	
	if (document.getElementById("via").value=="" && document.getElementById("composicion").value=="" && document.getElementById("especialidad").value=="" && document.getElementById("codigoNacional").value=="" && document.getElementById("PVPminimo").value=="" && document.getElementById("PVPmaximo").value==""){
		alert("Debe cubrir un criterio para buscar")
	}
	else{
		// Obtendo la capa donde se muestran las respuestas del servidor
		var capa=document.getElementById("resultadoNomenclator");
		// Creo el objeto AJAX
		var ajax=AjaxGenerica();
		// Coloco el mensaje "Cargando..." en la capa
		capa.innerHTML="Cargando resultados, esta consulta puede durar varios segundos ...";
		// Abro la conexion, envio cabeceras correspondientes al uso de POST y envio los datos con el metodo send del objeto AJAX
		ajax.open("POST", "consultaNomenclator.asp", true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.send("orden="+orden+"&via="+document.getElementById("via").value+"&composicion="+document.getElementById("composicion").value+"&especialidad="+document.getElementById("especialidad").value+"&codigoNacional="+document.getElementById("codigoNacional").value+"&PVPminimo="+document.getElementById("PVPminimo").value+"&PVPmaximo="+document.getElementById("PVPmaximo").value);
		//'campo1='+document.getElementById('campo1').value+'&campo2='+document.getElementById('campo2').value
		//ajax.send("composicion="+document.getElementById("composicion").value);
		ajax.onreadystatechange=function()
		{
			if (ajax.readyState==4)
			{
				// Respuesta recibida. Coloco el texto plano en la capa correspondiente
				capa.innerHTML=ajax.responseText;
			}
		}
	}
}


//de momento valida select-one, select-multiple y text
//en base al validationmsg, si es 0 o sin definir no es obligatorio,
	function ValidoAcceso(NombreForm){
		var sFormulario=document.forms[NombreForm];
		var validado = true
								
		for (i=0; i<= sFormulario.length-1; i++){
			if (sFormulario.elements[i].validationmsg){
				switch (sFormulario.elements[i].type ) {  
					case "select-multiple" :  
						if (sFormulario.elements[i].options.length =="0"){
							alert(sFormulario.elements[i].validationmsg)
							sFormulario.elements[i].focus()
							return false
						}
						break;
				 	
					case "textarea" :  
						if (sFormulario.elements[i].value.length >= sFormulario.elements[i].maxlength){
							validado=false
							respuesta=1
						}
						if (sFormulario.elements[i].value.length == "0" ){
							validado=false
							respuesta=2
						}
						if (validado==false){
							if (respuesta ==2){
								alert(sFormulario.elements[i].validationmsg)
							}else{
								alert("Hay demasiados texto en el campo comentarios, por favor, borre algo")
							}
							//esta funcion edita nuestro textarea para poner el foco
//							editor_setmode(sFormulario.elements[i].name)
//							sFormulario.elements[i].focus()
							return false
//							editor_setmode(sFormulario.elements[i].name)
						}
						break;
					
					default :  
						if (sFormulario.elements[i].type !="image" && sFormulario.elements[i].type !="select-multiple" &&
						 sFormulario.elements[i].type !="textarea" && sFormulario.elements[i].type !="checkbox" && 
						 sFormulario.elements[i].type !="radio" && sFormulario.elements[i].validationmsg != "0" && 
						 sFormulario.elements[i].validationmsg != "undefined" && sFormulario.elements[i].disabled == false && 
						 (sFormulario.elements[i].value =="" || sFormulario.elements[i].value =="0" )){
							alert(sFormulario.elements[i].validationmsg)
							sFormulario.elements[i].focus()
							return false
						}
						break;
				}  
				if (validado==false){
					alert(sFormulario.elements[i].validationmsg)
					sFormulario.elements[i].focus()
					return false
				}
			}
			
		}
		return true
	}
	//tienda
	function ValidoActu(Numero){
		for (i=0; i<=Numero; i++) {
	      campo=document.forms("modificar").elements["unidades"+i];
	      if(campo.value=="" || campo.value=="0"){
		  	alert("Por favor, indica el n&uacute;mero de unidades que deseas, si lo que quieres es quitar el producto de la cesta de la compra pincha en 'Borrar'.")
			campo.focus();
		  	return false;
		  }
	     }
		 return true;
	}
	function SoloNum(){
		//Prop&oacute;sito:	Evitar que se escriban letras en los campos num&eacute;ricos.
		//Efectos:		Si se pulsa una tecla de texto no ocurrir&aacute; nada.
			if (event.keyCode!=13&&(event.keyCode<48||event.keyCode>57))
				event.keyCode=0;
		}
	function Aceptar(){
		if (document.getElementById("aceptoCondiciones2")){
			if (document.getElementById("aceptoCondiciones2").checked){
				return (true)
			}
			else{
				alert("Debe aceptar las condiciones de uso")
				return false
			}
		}
	}
	
	function Pago(tipo,cuenta){
		document.forms["frmPedido"].action="pago.asp?tipo="+tipo+"&cuenta="+cuenta;
	}
	function Seguridad() {
			var win= null;
			var w=650;
			var h=450;
			var winl = (screen.width-w)/2;
			var wint = (screen.height-h)/2;
			settings='height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars=yes,fullscreen=no,toolbar=no,location=no,directories=no,status=no,menubar=auto,resizable=yes'
			win=window.open("seguridad.asp","politica",settings)
		}
	
	//fin tienda
