//Funcion diferenciaFechas en dias
function diferenciaFechas (miFecha1,miFecha2) {  
   
    //Resta fechas y redondea  
    var diferencia = miFecha1.getTime() - miFecha2.getTime()  
    var dias = Math.floor(diferencia / (1000 * 60 * 60 * 24))  
    var segundos = Math.floor(diferencia / 1000)  
    //alert ('La diferencia es de ' + dias + ' dias,\no ' + segundos + ' segundos.')  
      
    return dias
}  

function rellenarDias(ultimodia){
    //alert(document.forms.form.dia.selectedIndex);
    var diaSeleccionado = (document.forms.form.dia.selectedIndex);
    if (diaSeleccionado == -1) diaSeleccionado = 0;

    document.forms.form.dia.options.length = 0;

    for(i=1;i<=ultimodia;i++){
    
        var elOptNew = document.createElement('option');
        elOptNew.text = i;
        elOptNew.value = i;                                                
    
        try {
        document.forms.form.dia.add(elOptNew, null); // standards compliant; doesn't work in IE
        }
        catch(ex) {
        document.forms.form.dia.add(elOptNew); // IE only
        }                                                                                                
    
    }
    
    if (diaSeleccionado>document.forms.form.dia.options.length) diaSeleccionado = 0;
    else document.forms.form.dia.selectedIndex = diaSeleccionado;
  
}

function rellenarMes(){

    for(i=1;i<=12;i++){
    
        var elOptNew = document.createElement('option');
        elOptNew.text = i;
        elOptNew.value = i;                                                
    
        try {
        document.forms.form.mes.add(elOptNew, null); // standards compliant; doesn't work in IE
        }
        catch(ex) {
        document.forms.form.mes.add(elOptNew); // IE only
        }                                                                                                
    
    }                                            

}

function rellenarAnyosReg(){
    for(i=1900;i<=2011;i++){
    
        var elOptNew = document.createElement('option');
        elOptNew.text = i;
        elOptNew.value = i;
        if(i==1970) elOptNew.selected = true;                                                
    
        try {
        document.forms.form.anyo.add(elOptNew, null); // standards compliant; doesn't work in IE
        }
        catch(ex) {
        document.forms.form.anyo.add(elOptNew); // IE only
        }                                                                                                
    
    }                                            

}

function daysInMonth(month,year) {
	//alert(year);
    var dd = new Date(year, month, 0);
    return dd.getDate();
}                 

function cambiaDias(){
    rellenarDias(daysInMonth(document.forms.form.mes.selectedIndex+1,document.forms.form.anyo.selectedIndex));
}  

//Funcion para Aceptar Form al darle a Enter
function loginEnterKey(e){
    var key;      
    if(window.event)
          key = window.event.keyCode; //IE
    else
          key = e.which; //firefox      

	if(key == 13) checkFormLogin();
	
    return (key != 13);
}

//Funcion para saber los dias del mes
function daysInMonth(month,year) {
    var dd = new Date(year, month, 0);
    return dd.getDate();
}    

//Función para solo introducir un tipo de caracteres en un Input
var numb = "0123456789.,";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
var alphanumb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
function res(t,v){
    var w = "";
    for (i=0; i < t.value.length; i++) {
    x = t.value.charAt(i);
    if (v.indexOf(x,0) != -1)
    w += x;
    }
	t.value = w;
}

//Funcion para limitar el Texto en un Input
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } 
}

//Funcion de Check Email
function cmail(email){ 
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 
	return email.match(re) 
}

//Funcion AJAX
function getHTTPObject() {
    var xmlhttp;
    /*@cc_on
    @if (@_jscript_version >= 5)
       try {
          xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
       } catch (e) {
          try {
             xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (E) { xmlhttp = false; }
       }
    @else
    xmlhttp = false;
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
       try {
          xmlhttp = new XMLHttpRequest();
       } catch (e) { xmlhttp = false; }
    }
    return xmlhttp;
}

//Funcion Generica de Aceptar Formulario, y pasarlo por AJAX
function checkForm(nombreFichero,handleResponse){

	if (!enProceso && http) {
	   
		carroForm = "";
		for(i=0;i<document.forms.form.elements.length;i++){
			if(document.forms.form.elements[i].type == "checkbox"){
				
				if(escape(document.forms.form.elements[i].checked) == "true") carroForm = carroForm + document.forms.form.elements[i].name + "=1&";
				else carroForm = carroForm + document.forms.form.elements[i].name + "=0&";
				
			}
			else if(document.forms.form.elements[i].type == "radio"){

				if(escape(document.forms.form.elements[i].checked) == "true")  carroForm = carroForm + document.forms.form.elements[i].name + "=" + escape(document.forms.form.elements[i].value) + "&";
			
			}
			else carroForm = carroForm + document.forms.form.elements[i].name + "=" + escape(document.forms.form.elements[i].value) + "&";
		}
	   
		var url = nombreFichero+".php?"+carroForm
		//alert(url);
		
		//document.getElementById("checkDiv").innerHTML = "<img src='img/def.gif' />";
		
		http.open("GET", url, true);
		http.onreadystatechange = handleResponse;
		enProceso = true;

		http.send(null);

	}
	
}

var http = getHTTPObject(); // Creamos el objeto XMLHttpRequest  
var enProceso = false; // lo usamos para ver si hay un proceso activo 

//Funciones Propias
function muestraFaccion(faccion){

	document.getElementById("botonSoloOsadia").style.display = "none";
	document.getElementById("botonSoloAbnegacion").style.display = "none";
	document.getElementById("botonSoloVerdad").style.display = "none";
	document.getElementById("botonSoloErudicion").style.display = "none";
	document.getElementById("botonSoloCordialidad").style.display = "none";
	
	document.getElementById("botonSolo"+faccion).style.display = "inline";
	
	document.getElementById("faccionOsadia").style.display = "none";
	document.getElementById("faccionAbnegacion").style.display = "none";
	document.getElementById("faccionVerdad").style.display = "none";
	document.getElementById("faccionErudicion").style.display = "none";
	document.getElementById("faccionCordialidad").style.display = "none";
	
	document.getElementById("barraFaccion").style.display = "inline";
	document.getElementById("faccion"+faccion).style.display = "inline";

}


function contacto(){

	if(document.forms.form.nombre.value == ""){
		alert("Por favor, introduce tus datos de contacto.");
	}
	else if(document.forms.form.email.value == ""){
		alert("Por favor, introduce tus datos de contacto.");
	}	
	else if(!cmail(document.forms.form.email.value)){
		alert("Por favor, introduce tus datos de contacto.");
	}
	else if(document.forms.form.texto.value == ""){
		alert("Por favor, introduce tus datos de contacto.");
	}
	else{

		document.getElementById("checkDiv").innerHTML = "<table cellspacing='0' cellpadding='0' width='73' style='height:25px;'><tr><td align='center' style='vertical-align:middle;'><img src='img/def.gif' style='height:24px;' /></td></tr></table>";
		checkForm("contacto_sql",handleHttpResponseContacto);
	
	}

}

function handleHttpResponseContacto() {

	if (http.readyState == 4) {
		if (http.status == 200) {
			if (http.responseText.indexOf('invalid') == -1) {
				//alert(http.responseText);
				if (http.responseText == 1){
					alert("Tu mensaje ha sido enviado correctamente. ");
					document.getElementById("checkDiv").innerHTML = '';
					window.location = "home.php";
				}
				else{
					alert("Tenemos problemas técnicos. Vuelve a intentarlo más tarde");
					document.getElementById("checkDiv").innerHTML = '<img src="img/botonEnviar.png" style="cursor:pointer;" onclick="javascript:contacto();" />';
				}

			}
		}	
		else{
			alert("Tenemos problemas técnicos. Vuelve a intentarlo más tarde");
			document.getElementById("checkDiv").innerHTML = '<img src="img/botonEnviar.png" style="cursor:pointer;" onclick="javascript:contacto();" />';
		}
		
		enProceso = false;
	}
	
}


  	
