﻿/////////////////////////////////////////////////
/// Invocador de ajax ////////////////
///////////////////////////////////////////
function AjaxInvoker() {
	this.parameters = new Array();
	this.httpReq;
	this.url = "index.aspx";
	this.params;
    this.responseStream = '';
	this.async = false;	// Indica si se utilizará una comunicació asíncrona
	this.hasErrors = (!this.httpReq || this.httpReq.status != 200);
	this.waitResponseHandler = function() {};
    
	/* Inizializa Ajax para nuevas llamadas */
	this.clear = function () {
		this.parameters = new Array();
		this.responseStream = '';
	}

	// Añade un parámetro POST
	this.addPostParameter = function(sName, sValue) {
		if (sName!=null && sValue!=null) {
			this.parameters[this.parameters.length] = sName + "=" + encodeURIComponent(sValue);
		}
	}	
	
	// Devuelve el valor de un nodo del XML que se le pasa
	this.getXMLNodeValue = function (oXMLNode, sTagName) {
		var value = oXMLNode.getElementsByTagName(sTagName);
		return (value!=null && value.length>0 && value[0].firstChild!=null)
			? value[0].firstChild.nodeValue
			: '';
	}
	
	// Establece el objeto de conexión HTTP
	this.setupHttpRequestObject = function () {
	/*  if (window.XMLHttpRequest) { // Mozilla, Safari,...
			this.httpReq = new XMLHttpRequest();
			if (this.async)
				this.httpReq.onreadystatechange = this.waitResponseHandler;
		} else if (window.ActiveXObject) { // IE
			try {
				this.httpReq = new ActiveXObject("Msxml2.XMLHTTP");
				if (this.async)
					this.httpReq.onload = this.waitResponseHandler;
			} catch (e) {
				try {
				this.httpReq = new ActiveXObject("Microsoft.XMLHTTP");
				if (this.async)
					this.httpReq.onreadystatechange = this.waitResponseHandler;
				} catch (e) {}
			}
		} */
		this.httpReq = null;
		try { 
			this.httpReq = new ActiveXObject("Msxml2.XMLHTTP"); 
			if (this.async) this.httpReq.onload = this.waitResponseHandler;
		} catch (e) {
			try {
				this.httpReq = new ActiveXObject("Microsoft.XMLHTTP");
				if (this.async) this.httpReq.onreadystatechange = this.waitResponseHandler;
				} catch (E) {this.httpReq = null;}
		}
		if (this.httpReq==null && XMLHttpRequest) {
			try {
				this.httpReq = new XMLHttpRequest();
				if (this.async) this.httpReq.onreadystatechange = this.waitResponseHandler;
			} catch (e) {this.httpReq=null;}
		}
		if (this.httpReq==null && window.createRequest) {
			try { 
				this.httpReq = window.createRequest();
				if (this.async) this.httpReq.onreadystatechange = this.waitResponseHandler;
			} catch (e) {this.httpReq=null;}
		}
	}
	
	// Establece la cadena de parámetros de llamada
	this.setupParameters = function() {
		this.params = "";
		for (var i=0; i<this.parameters.length; i++) {
		  if (this.params!="") this.params += "&";
		  if (this.parameters[i]!=undefined)	this.params += this.parameters[i];
		}
	}

    // Llamada a la url	
	this.doCall = function() {
		this.httpReq.open("POST", this.url, this.async);
		this.httpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		this.httpReq.send(this.params);
		if (!this.async) this.responseStream = this.httpReq.responseText;
	}
	
	// Función que realiza petición ajax
	// Url que se le pasa enviando un POST con la cadena de parÃ¡metros.
	this.call = function ()  {

        //Monta el objeto HTTP
        this.setupHttpRequestObject();
        
		if (!this.httpReq) {
			alert('No puedo crear una instancia AJAX');
			return false;
		}

		this.url=this.url.replace('#','');

        // Configura los parámetros
        this.setupParameters();
	
	    // Efectua Llamada a la URL
	    this.doCall();
	};
		
};

//////////////////////////////////////////
//////////////////////////////////////////
//////////////////////////////////////////

function doAction(_action, _form, _confirmMsg) {
    var action = "index.aspx?action=" + _action;
    
    if (_confirmMsg && _confirmMsg!=null) {
        if (!confirm(_confirmMsg)) return;
    }
    
    if (_form==null) {
        document.location.href = action;
        return;
     }
    _form.action = action;
    _form.method = "POST";
    _form.submit();
}

// Login de usuario
function doLogin(form, prefix) {
    var oAjax = new AjaxInvoker();
	var sUserName = form.login_txt.value;
	var sPassword = form.password_txt.value;
	
	if (sUserName=='') {
	    alert('Te has olvidado de introducir tu email.')
	    form.login_txt.focus();
	    return false;
	}
		
	if (sPassword=='') {
	    alert('Te has olvidado de introducir tu contraseña.')
	    form.password_txt.focus();
	    return false;
	}
	try {
	    // Login PHP
	    oAjax.url = prefix + 'foro/ucp.php?mode=login';
		oAjax.addPostParameter("username", sUserName);
		oAjax.addPostParameter("password", sPassword);
		oAjax.addPostParameter("login", "LOGIN");
		oAjax.call();
	} catch (ex) {}
/*
	try {
	    // Login ASP
	    oAjax.clear();
		oAjax.url = prefix + 'asp/dologin.asp?action=login';
		oAjax.addPostParameter("login", sUserName);
		oAjax.addPostParameter("password", sPassword);
		oAjax.call();
		//alert(oAjax.responseStream);
	} catch (ex) { // Realiza 3 intenteos de Login en el resto de plataformas.
		//if (retry==null) retry=0;
		//return (retry<3) ? doLogin(form, prefix, retry+1) : false;
	}
*/	return true;
}

function doLogoff(prefix) {
    var oAjax = new AjaxInvoker();
	// Logoff PHP
	oAjax.url = prefix + 'foro/ucp.php?mode=logout';
	oAjax.call();
/*	oAjax.clear();
    // ASP
	oAjax.url = prefix + 'asp/dologin.asp?action=logoff';
	oAjax.call();
	*/
}

function _changeCountry(objCountry, timeZonesIdStr) {
    var sValue = objCountry[objCountry.selectedIndex].value;
    var ajax = new AjaxInvoker();
    ajax.addPostParameter('action','gettz');
    ajax.addPostParameter('cid',sValue);
    ajax.call();
    _fillTimezones(timeZonesIdStr, ajax.responseStream, 'tz_sel');
}

function _fillTimezones(tzObjId, _timezoneStr, tzId) {
    var tzObj = document.getElementById(tzObjId);
    if (tzObj==null) return;

    var svalues = _timezoneStr.split('|');
    for (i=tzObj.options.length-1;i>=0; i--) tzObj.options[i] = null;
    if (_timezoneStr=="") { 
        tzObj.options[tzObj.options.length] = new Option('No hay zonas horarias','-1');
        return;
    }
    //opt = new Option('Selecciona una opción','');
    //tzObj.options[tzObj.options.length] = opt;
    for (i=0;i<svalues.length;i=i+2) {
        opt = new Option(svalues[i+1], svalues[i]);
        tzObj.options[tzObj.options.length] = opt;
    }
}

function _changeTimeZone(selectTZ, tzHourStr) {
    var ajax = new AjaxInvoker();
    var tzHObj = document.getElementById(tzHourStr);
    if (tzHObj==null) return;
    var sValue = selectTZ[selectTZ.selectedIndex].value;
    ajax.addPostParameter('action','gettzrange');
    ajax.addPostParameter('tzid',sValue);
    ajax.call();
    // Borra los elementos del array
    for (i=tzHObj.options.length-1;i>=0; i--) tzHObj.options[i] = null;
    if (ajax.responseStream=="") { 
        tzHObj.options[tzHObj.options.length] = new Option('--','-1');
        return;
    }
    var _rng = ajax.responseStream.split('|');
    for (idx=0;idx<_rng.length;idx++) {
        tzHObj.options[tzHObj.options.length] = new Option(_rng[idx] + ':00', _rng[idx]);
    }
    /*
    var iLow = parseInt(_rng[0]);
    var iTop = parseInt(_rng[1]);
    while (iLow!=iTop) {
        if (iLow>=24) iLow=0;
        tzHObj.options[tzHObj.options.length] = new Option(iLow + ':00',iLow);
        iLow++;
    }
    */
}

function _saveSignon(formObj) {
    if (!formObj.conditions_chk.checked) {
        alert('Debes aceptar las condiciones legales.');
        return;
    }
    doAction('usersignon&save=1', formObj, null);
}

function _hideDisplay(check, id) {
    var oDiv = document.getElementById(id);
    if (!oDiv) return;
    oDiv.style.display = (check.checked) ? '' : 'none';
}

function _printContent(fromId) {
    var _from = document.getElementById(fromId);
    if (_from==null) return;
    window.frames.printCanvas.document.open();
    window.frames.printCanvas.document.write("<html><head><link href='styles.css' rel='stylesheet' type='text/css'/></head><body>"
        + _from.innerHTML + 
        + "</body></html>");
    window.frames.printCanvas.document.close();
    window.frames.printCanvas.focus();
    window.frames.printCanvas.print();
}

////////////////////////////////////////////////////////////////////////
/// OLD ASP ///////////////////////
////////////////////////////////////////////////////////////////////////
function verify_date(){
	var c = new Date();
	sDay = document.getElementById('dia').value;
	sMon = document.getElementById('mes').value;
	sYea = document.getElementById('anyo').value;
	sDate = sDay + '/' + sMon + '/' + sYea;
	
	cDay = c.getDate();
	cMon = c.getMonth()+1;
	cYea = c.getFullYear();
	cDate =  cDay + "/" + cMon + "/" + cYea;
	iDayDiff = Math.floor(sDay) - Math.floor(cDay);
	
	
	if ((sMon < cMon) && (sYea == cYea)){
		alert('La fecha indicada no es correcta. Escoja otro mes para la consulta.');
	}else{
		if ((sMon == cMon) && (sYea == cYea) && (iDayDiff < 3)){
			alert('Para solicitar una consulta, debe ser programada con al menos 2 dias de anterioridad');
		}else{
			return true;
		}
	}

}

function chequea_box() {	
	if (document.getElementById("recibir informacion").checked == true){
		document.getElementById("inscripcion").submit();
	}else{
		alert ("Debe aceptar el Codigo Etico para completar el proceso");
	}
}


function validate_data(objFrm){	

	sMsg = "";
	sBrf = eval('document.'+objFrm);
	
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(sBrf.email.value)) { sMsg = sMsg + '- El email no esta correctamente escrito.\n' };		
	if (!sBrf.codigo_etico.checked) { sMsg = sMsg + '- Debe aceptar el Codigo Etico para continuar.\n' };
			
	if (sMsg.length > 0){ alert(sMsg); }else{ sBrf.submit(); }

}

function clear_box(sRef){
	sTxt = "usuario (e-mail)";
	if (sRef == "pass") { sTxt = "contrasena" };
	sObj = eval("document.frmlogin."+sRef);
	if (sObj.value == sTxt) { sObj.value = "" };
}

function GetTimeZones(countryObj, tzselId) {
    var selTZ = document.getElementById(tzselId);
}