function getRadioButtonSelectedValue(ctrl)
{
    for(i=0;i<ctrl.length;i++)
        if(ctrl[i].checked) return ctrl[i].value;
}

// crea objeto xmlhttprequest
function nuevoAjax(){
	var xmlhttp=false;
 	try {
 		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 	} catch (e) {
 		try {
 			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 		} catch (E) {
 			xmlhttp = false;
 		}
  	}

	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
 		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}
//vota en una encuesta
function votar(id, contenedor){
	voto = getRadioButtonSelectedValue(document.encuesta.voto);
	ajax=nuevoAjax();
	ajax.open("GET", 'do_voto.php?id_encuesta='+id+'&id_alternativa='+voto,true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			//contenedor.innerHTML = ajax.responseText;
			window.location="../index.php"
		}
	}
	ajax.send(null);
}
//para dismunuir fuente y aumentar
var min=9;
var max=16;
function increaseFontSize() {
   var p = document.getElementById('pag_noticias').getElementsByTagName('p');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=max) {
         s += 1;
      }
      p[i].style.fontSize = s+"px"
   }
      var p = document.getElementById('pag_noticias').getElementsByTagName('h3');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=max) {
         s += 1;
      }
      p[i].style.fontSize = s+"px"
   }
      var p = document.getElementById('pag_noticias').getElementsByTagName('li');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=max) {
         s += 1;
      }
      p[i].style.fontSize = s+"px"
   }

}
function decreaseFontSize() {
   var p = document.getElementById('pag_noticias').getElementsByTagName('p');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=min) {
         s -= 1;
      }
      p[i].style.fontSize = s+"px"
   }
         var p = document.getElementById('pag_noticias').getElementsByTagName('li');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=min) {
         s -= 1;
      }
      p[i].style.fontSize = s+"px"
   }
      var p = document.getElementById('pag_noticias').getElementsByTagName('h3');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=min) {
         s -= 1;
      }
      p[i].style.fontSize = s+"px"
   }

}
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_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.id; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' debe ser una dirección email válida.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' solo permite numeros.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' es un campo obligatorio.\n'; }
  } if (errors) alert('Se encontraron errores:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function MM_validateForm_rut() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm_rut.arguments;
  errors=validar_rut(document.form2.rut_paciente.value);
  for (i=0; i<(args.length-2); i+=3) 
  { 
	test=args[i+2]; 
	val=MM_findObj(args[i]);
    if (val) 
	{ 
		nm=val.id; 
		if ((val=val.value)!="") 
		{
			if (test.indexOf('isEmail')!=-1) 
			{ 
				p=val.indexOf('@');
				if (p<1 || p==(val.length-1)) 
					errors+='- '+nm+' debe ser una dirección email válida.\n';
			}
			
			
			
			
			else if(test.indexOf('esCodigo')!=-1) 
			{
				var exp_reg = /^\d{2}-\d{2}-\d{3}/
				if(!exp_reg.test(val))
				{
					errors+='- '+nm+' debe ser ingresado en la forma XX-XX-XXX.\n';
				}
			}
			
			
			
			else if (test!='R') 
			{ 
				num = parseFloat(val);
				if (isNaN(val)) 
					errors+='- '+nm+' solo permite numeros.\n';
				if (test.indexOf('inRange') != -1) 
				{ 
					p=test.indexOf(':');
					min=test.substring(8,p); max=test.substring(p+1);
					if (num<min || max<num) 
						errors+='- '+nm+' al menos debe contener '+min+' and '+max+'.\n';
				} 
			} 
		} 
		else if (test.charAt(0) == 'R') 
			errors += '- '+nm+' es un campo obligatorio.\n'; }
  } 
  if (errors) 
	alert('Se encontraron errores:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function buscador(str){
	if(str.length < 3){
		alert('Debe ingresar al menos 3 letras para buscar');
	}else{
		document.buscar.submit();	
	}
}

function validar() {

	if (document.form2.nombre_paciente.value=='') {
		alert('Debe ingresar nombre del paciente');
		document.form2.nombre_paciente.className='alerta';
		document.form2.nombre_paciente.focus();
		document.form2.nombre_paciente.select();
		return false;
	}
	
	if (document.form2.apellido_paterno.value=='') {
		alert('Debe ingresar apellido parterno del paciente');
		document.form2.apellido_paterno.className='alerta';
		document.form2.apellido_paterno.focus();
		document.form2.apellido_paterno.select();
		return false;
	}
	
	if (document.form2.apellido_materno.value=='') {
		alert('Debe ingresar apellido materno del paciente');
		document.form2.apellido_materno.className='alerta';
		document.form2.apellido_materno.focus();
		document.form2.apellido_materno.select();
		return false;
	}
	
	if (document.form2.anno_nac.value=='') {
		alert('Debe ingresar fecha de nacimiento');
		document.form2.anno_nac.className='alerta';
		document.form2.anno_nac.focus();
		document.form2.anno_nac.select();
		return false;
	}
	
	if (document.form2.telefono.value=='') {
		alert('Debe ingresar telefono');
		document.form2.telefono.focus();
		document.form2.telefono.select();
		return false;
	}
	
		if (document.form2.e_mail.value=='') {
		alert('Debe ingresar E-Mail');
		document.form2.e_mail.focus();
		document.form2.e_mail.select();
		return false;
	}
	
return true;

}

function MM_CheckFlashVersion(reqVerStr,msg){
  with(navigator){
    var isIE  = (appVersion.indexOf("MSIE") != -1 && userAgent.indexOf("Opera") == -1);
    var isWin = (appVersion.toLowerCase().indexOf("win") != -1);
    if (!isIE || !isWin){  
      var flashVer = -1;
      if (plugins && plugins.length > 0){
        var desc = plugins["Shockwave Flash"] ? plugins["Shockwave Flash"].description : "";
        desc = plugins["Shockwave Flash 2.0"] ? plugins["Shockwave Flash 2.0"].description : desc;
        if (desc == "") flashVer = -1;
        else{
          var descArr = desc.split(" ");
          var tempArrMajor = descArr[2].split(".");
          var verMajor = tempArrMajor[0];
          var tempArrMinor = (descArr[3] != "") ? descArr[3].split("r") : descArr[4].split("r");
          var verMinor = (tempArrMinor[1] > 0) ? tempArrMinor[1] : 0;
          flashVer =  parseFloat(verMajor + "." + verMinor);
        }
      }
      // WebTV has Flash Player 4 or lower -- too low for video
      else if (userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 4.0;

      var verArr = reqVerStr.split(",");
      var reqVer = parseFloat(verArr[0] + "." + verArr[2]);
  
      if (flashVer < reqVer){
        if (confirm(msg))
          window.location = "http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
      }
    }
  } 
}
function buscador_medicos(tipo){
	if(tipo=='esp'){
		if(document.getElementById('especialidad').options[document.getElementById('especialidad').selectedIndex].value != '-1'){
			document.doctores_e.submit();	
		}else{
			alert('Seleccione especialidad');
		}
	}else{
		if(document.getElementById('medico').value.length >= 3){
			document.doctores_n.submit();	
		}else{
			alert('Ingrese un nombre o apellido con al menos 3 letras');
		}
	}
}
function ClearForm(form){
    resul = document.getElementById('informacion');
    resul.innerHTML= "";
    form.weight.value = "";
    form.height.value = "";
    form.bmi.value = "";
    }
function bmi(weight, height) {
          bmindx=weight/eval(height*height);
          return bmindx;		  
}
function checkform(form) {
       if (form.weight.value==null || form.weight.value.length==0 || form.height.value==null || form.height.value.length==0){
            alert("Completa el formulario");
            return false;
       }
       else if (parseFloat(form.height.value) <= 0||
                parseFloat(form.height.value) >=500||
                parseFloat(form.weight.value) <= 0||
                parseFloat(form.weight.value) >=500){
                alert("Revisa los valores ingresados, al parecer existe un error");
                ClearForm(form);
                return false;
       }
       return true;
}
function computeform(form) {
       if (checkform(form)) {
		   yourbmi=Math.round(bmi(form.weight.value, form.height.value/100));
		   total = yourbmi;
  		   resul = document.getElementById('informacion');
		   pa="&peso="+document.imc.weight.value+"&altura="+document.imc.height.value;
		   if(total < 18.5){
//			   GB_myShow('Cálculo del IMC','../../resultado_imc_res.php?op=1&total='+total+pa,150,420);
                           html="<center><font color='#f8b603' size='-1'>Su peso está por debajo de lo normal. Le recomendamos visitar a un especialista.</font></center>";
                           }
		   if(total > 18 && total < 25){
//			   GB_myShow('Cálculo del IMC','../../resultado_imc_res.php?op=2&total='+total+pa,150,420);
                           html="<center><font color='#7ec114' size='-1'>No necesita bajar de peso. Su estado es NORMAL.</font></center>";
			   }
		   if(total >24 && total < 30){
//			   GB_myShow('Cálculo del IMC','../../resultado_imc_res.php?op=3&total='+total+pa,150,420);
                           html="<center><font color='#ff7c00' size='-1'>Usted tiene sobrepeso. Le recomendamos visitar a un especialista.</font></center>";
			   }
		   if(total >29 ){
//			   GB_myShow('Cálculo del IMC','../../resultado_imc_res.php?op=4&total='+total+pa,150,420);
                           html="<center><font color='#ee290c' size='-1'>Es muy importante que baje de peso. Su riesgo de padecer complicaciones es MUY ALTO. Le recomendamos visitar a un especialista.</font></center>";
			   }
           resul.innerHTML= html;
			   
		   form.bmi.value = total;
       }else{
  	         form.weight.value = "";
             form.height.value = "";
             form.bmi.value = "";
		    }
	   //alert(total);
       return;
}
function calcular()
{
	fecha_inicio = new Date();
	dia_parto = new Date();
	hoy = new Date();
	lleva = new Date();
	falta = new Date();
	
	day = document.form1.dia.options[document.form1.dia.options.selectedIndex].value;
	month = document.form1.mes.options[document.form1.mes.options.selectedIndex].value;
	year = document.form1.anio.options[document.form1.anio.options.selectedIndex].value;

	fecha_dada = new Date(year, (month-1), day);//month+"/"+day+"/"+year
	

//Validación de la fechas
	if ((month=='04' || month=='06' || month=='09' || month=='11') && day==31) 
	{
		alert("Este mes no tiene 31 dias!")
		return false;
	}
	if (month == 2) 
	{ // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap))
		{
			alert("Febrero " + year + " no tiene " + day + " días!");
			return false;
		}
	}

	//Calculamos la fecha probable del parto
	fecha_inicio.setTime(fecha_dada.getTime())
	dia_parto.setTime(fecha_inicio.getTime() + (280 * 86400000)); //(14 * 86400000) es la fecha de concepción
    
	//Calculamos el tiempo que lleva
	
	lleva.setTime(hoy.getTime() - fecha_inicio.getTime());
	llevasemanas = parseInt(((lleva.getTime()/86400000)/7));
	llevadias = Math.floor(((lleva.getTime()/86400000)%7));
	//Calculamos el tiempo faltante
	falta.setTime(dia_parto.getTime() - hoy.getTime());
	
	faltasemanas = parseInt(((falta.getTime()/86400000)/7));
	faltadias = parseInt(((falta.getTime()/86400000)%7));

   if(llevasemanas<0 || llevasemanas >40 || llevadias>280 || llevadias<0 || faltadias < 0 )
	{ 
	  alert("Existe un error con la fecha proporcionada anteriormente");
	  return false;
	}

	document.getElementById('semanas').innerHTML = llevasemanas + " semanas y " + llevadias +" d&iacute;as";
	document.getElementById('faltante').innerHTML = faltasemanas + " semanas y " + faltadias+ " d&iacute;as";
	document.getElementById('fecha_p').innerHTML = dispDate(dia_parto)+", est&aacute;s en la semana "+llevasemanas+" de embarazo.";

}


function dispDate(dateObj) 
{
	month = dateObj.getMonth()+1;
	var months = new Array(12);
	months[1] = "Enero";
	months[2] = "Febrero";
	months[3] = "Marzo";
	months[4] = "Abril";
	months[5] = "Mayo";
	months[6] = "Junio";
	months[7] = "Julio";
	months[8] = "Agosto";
	months[9] = "Septiembre";
	months[10] = "Octubre";
	months[11] = "Noviembre";
	months[12] = "Diciembre";
	day   = dateObj.getDate();
	var days = new Array(7);
	days[0] = "Domingo";
	days[1] = "Lunes";
	days[2] = "Martes";
	days[3] = "Mi&eacute;rcoles";
	days[4] = "Jueves";
	days[5] = "Viernes";
	days[6] = "S&aacute;bado";
	dayw = dateObj.getDay();
	day = (day < 10) ? "0" + day : day;
	year  = dateObj.getYear();
	if (year < 2000) year += 1900;
	return (days[dayw] + " " + day + " de " + months[month] + " del " + year);
}

function dv(T){var M=0,S=1;for(;T;T=Math.floor(T/10))
S=(S+T%10*(9-M++%6))%11;return S?S-1:'K';}

function validar_rut(rut,obj)
 {
	 var aux_rut= rut.toUpperCase();
	 var aux_rut=aux_rut.split("-"); 
	 if(dv(aux_rut[0])!=aux_rut[1])
	   {
		   mensaje="- Rut esta mal ingresado\n"
		   return mensaje;
	   }else{return false;}
 }

function eliminar_correo(username)
{
  window.location="adm_delete_user.php?user="+username;
}

