/*
  Compara fechas, los tipos de comparación son:
  - mayor_sistema: En este caso se valida que la fecha no sea mayor a la del sistema.
  				   Los campos necesarios son: tipo = 'mayor_sistema', fecha_1 = id fecha a comparar, fecha_2 = null.
  - menor_sistema: En este caso se valida que la fecha no sea menor a la del sistema.
  				   Los campos necesarios son: tipo = 'menor_sistema', fecha_1 = id fecha a comparar, fecha_2 = null.
  - mayor_fecha: En este caso se valida que la fecha 1 no sea mayor a la fecha 2.
  				 Los campos necesarios son: tipo = 'mayor_sistema', fecha_1 = fecha a comparar, fecha_2 = null.
  - menor_fecha: En este caso se valida que la fecha 1 no sea menor a la fecha 2.
  				 Los campos necesarios son: tipo = 'mayor_sistema', fecha_1 = fecha a comparar, fecha_2 = null.
  Nota: Debido al calendario de estandares el campo fecha debe ser en formato yyyy-mm-dd.
  
  Existen 2 implementaciones: 
	* compararFechasById = Esta recibe el id del campo y el método se encarga de comparar los valores y resetear el valor
						   en caso de que el rango sea incorrecto. Además retorna el booleano correspondiente.
	* compararFechasByValue = Este recibe el valor del campo y el método se encarga de comparar los valores y retornar el
							  booleano correspondiente.
*/
function compararFechasById(tipo, fecha_1, fecha_2) {
	var retorno = true;
	
	switch(tipo) {
		case "mayor_sistema":
			var strFecha_1 = document.getElementById(fecha_1).value;
			
			if(!compararFechasByValue(tipo, strFecha_1, null)) {
				document.getElementById(fecha_1).value = "";
				document.getElementById(fecha_1).focus();
				retorno = false;
			}
			break;
		case "menor_sistema":
			var strFecha_1 = document.getElementById(fecha_1).value;
			
			if(!compararFechasByValue(tipo, strFecha_1, null)) {
				document.getElementById(fecha_1).value = "";
				document.getElementById(fecha_1).focus();
				retorno = false;
			}
			break;
		case "mayor_fecha":
			var strFecha_1 = document.getElementById(fecha_1).value;
			var strFecha_2 = document.getElementById(fecha_2).value;
			
			if(!compararFechasByValue(tipo, strFecha_1, strFecha_2)) {
				document.getElementById(fecha_1).value = "";
				document.getElementById(fecha_2).value = "";
				document.getElementById(fecha_1).focus();
				retorno = false;
			}		
			break;
		case "menor_fecha":
			var strFecha_1 = document.getElementById(fecha_1).value;
			var strFecha_2 = document.getElementById(fecha_2).value;
			
			if(!compararFechasByValue(tipo, strFecha_1, strFecha_2)) {
				document.getElementById(fecha_1).value = "";
				document.getElementById(fecha_2).value = "";
				document.getElementById(fecha_1).focus();
				retorno = false;
			}		
			break;									
		default:
			alert("Ha enviado los parametros de comparación de manera incorrecta.");
			retorno = false;
			break;
	}
	
	return retorno;
}

function compararFechasByValue(tipo, fecha_1, fecha_2) {
	var retorno = true;
	
	switch(tipo) {
		case "mayor_sistema":
			var dtmFechaSys = new Date(new Date().getYear(), new Date().getMonth(), new Date().getDate());
			var strFecha_1 = fecha_1;
			var dtmFecha_1 = new Date(strFecha_1.substr(0,4), strFecha_1.substr(5,2) - 1, strFecha_1.substr(8,2));			
			
			if(dtmFecha_1.getTime() > dtmFechaSys.getTime()) {
				alert("La fecha no puede ser superior a la fecha del sistema.");
				retorno = false;
			}
			break;
		case "menor_sistema":
			var dtmFechaSys = new Date(new Date().getYear(), new Date().getMonth(), new Date().getDate());
			var strFecha_1 = fecha_1;
			var dtmFecha_1 = new Date(strFecha_1.substr(0,4), strFecha_1.substr(5,2) - 1, strFecha_1.substr(8,2));			
			
			if(dtmFecha_1.getTime() < dtmFechaSys.getTime()) {
				alert("La fecha no puede ser inferior a la fecha del sistema.");
				retorno = false;
			}
			break;
		case "mayor_fecha":
			var strFecha_2 = fecha_2;
			var dtmFecha_2 = new Date(strFecha_2.substr(0,4), strFecha_2.substr(5,2) - 1, strFecha_2.substr(8,2));
			var strFecha_1 = fecha_1;
			var dtmFecha_1 = new Date(strFecha_1.substr(0,4), strFecha_1.substr(5,2) - 1, strFecha_1.substr(8,2));			
			
			if(dtmFecha_1.getTime() > dtmFecha_2.getTime()) {
				alert("El rango de fechas ingresado es incorrecto.");
				retorno = false;
			}		
			break;
		case "menor_fecha":
			var strFecha_2 = fecha_2;
			var dtmFecha_2 = new Date(strFecha_2.substr(0,4), strFecha_2.substr(5,2) - 1, strFecha_2.substr(8,2));
			var strFecha_1 = fecha_1;
			var dtmFecha_1 = new Date(strFecha_1.substr(0,4), strFecha_1.substr(5,2) - 1, strFecha_1.substr(8,2));			
			
			if(dtmFecha_1.getTime() < dtmFecha_2.getTime()) {
				alert("El rango de fechas ingresado es incorrecto.");
				retorno = false;
			}		
			break;									
		default:
			alert("Ha enviado los parametros de comparación de manera incorrecta.");
			retorno = false;
			break;
	}
	
	return retorno;
}

/**
 * Valida que el formato de la fecha sea yyyy-mm-dd
 * Debe existir el atributo nombreCampo para informar al usuario del campo.
 * @author Juan David Aristizábal Ocampo
 * @param id de la fecha 
**/
function validarFormatoFecha(fechaId) {
    var filter=/^([0-9]){4}(\-){1}([0][1-9])|([1][0-2])(\-)((([0]){1}([1-9]){1})|(([1-2]){1}([0-9]){1})|(([3]){1}([0-2]){1}))$/;
    var retorno = true;
    var campo = document.getElementById(fechaId);
    if(!filter.test(campo.value)) {    
        alert("La fecha ingresada (" + campo.value + ") NO tiene el formato yyyy-mm-dd.");
        document.getElementById(fechaId).focus();
        retorno = false;
    }
    
    return retorno;
}

function addZero(vNumber){
	return ((vNumber < 10) ? "0" : "") + vNumber
}

//Muestra una ventana modal con la informacion requerida.
function openDialog(url, idWin, w, h, tipoVentana) {
	var win = null;
	var LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	var TopPosition  = (screen.height) ? (screen.height-h)/2 : 0;
	if(tipoVentana == 'd') {
		configuracion = "dialogHeight: " + h + "px; dialogWidth: " + w + "px; dialogLeft: " + LeftPosition + "px; dialogTop: " + TopPosition + "px; resizeable: no; status: no; scroll: yes; help: no;";
		win = window.showModalDialog(url, "", configuracion);
	} else {
		configuracion = "toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no,height=" + h + ",width=" + w + ",top="+TopPosition+",left="+LeftPosition;
		win = window.open(url, idWin, configuracion);
		win.focus();
	}
}

function openDialogListener(url, idWin, w, h, tipoVentana, urlToRefresh) {
	openDialog(url, idWin, w, h, tipoVentana);
	xurlToRefresh = urlToRefresh
}


function alfrescoCallback() {
	window.location.href = xurlToRefresh;
}

function login(panelId, context) {
	var queryString = context + "/views/components/arkimia-login-page.jsp";
	openPanel(panelId, queryString, "Ingresar");
}

function sendComment(panelId, topicId, context) {
	var queryString = context + "/views/components/arkimia-send-comment.jsp?docId="
		+ topicId ;
	openPanel(panelId, queryString, "Enviar Comentario");
}

function createNewTopic(panelId, documentId, context) {
	var queryString = context + "/views/components/arkimia-send-comment.jsp?createNewTopic="
		+ documentId ;
	openPanel(panelId, queryString, "Crear Discusión");
}

function sendMail(panelId, docId, docName, tipoProducto,
		planilla, documento, empleador, fecha, periodo, plan, estado, 
		context) {
	var queryString = context + "/views/components/arkimia-send-mail.jsp?docId="
		+ docId + "&docName=" + docName + "=&subEspacio=" + tipoProducto 
		+ "&planilla=" + planilla + "&documento=" + documento + "&empleador="
		+ empleador + "&fecha=" + fecha + "&periodo=" + periodo + "&plan=" 
		+ plan + "&estado=" +estado;
	openPanel(panelId, queryString, "Enviar Correo");
}

function suscribe(panelId, context) {
	var queryString = context + "/views/components/arkimia-suscribe.jsp";
	openPanel(panelId, queryString, "Suscripción");
}

function openContactPage(panelId, context) {
	var queryString = context + "/views/components/arkimia-send-mail.jsp?showFrom=true&showTo=false&showAttachment=false";
	openPanel(panelId, queryString, "Contáctenos");
}

function openPanel(panelId, queryString, title) {
	var oDiv = document.getElementById(panelId);

	var handleSuccess = function(o){

		if(o.responseText !== undefined){
			oDiv.innerHTML = "<div class=\"hd\">" + title + "</div>";
			oDiv.innerHTML += "<div class=\"bd\">" + o.responseText + "</div>";
			oDiv.innerHTML += "<div class=\"ft\">&#32;</div>";
			
			oDiv.style.display = "inline";
			
			// Define various event handlers for Dialog
			var handleSubmit = function() {
				this.submit();
				setTimeout('window.location.reload()', 1000);
			};
			
			var myDialog = new YAHOO.widget.Dialog(panelId, 
					{
						width:"500px", 
						zindex:9999,
						visible:false, 
						constraintoviewport:true,
						fixedcenter:true,
						draggable:true,
						modal:true,
						close:true,
						buttons : [ { text:"&#32;", handler:handleSubmit, isDefault:true } ]
					} 
			);
			/*
			myDialog.hideEvent.subscribe(function () {
		        window.setTimeout(function () {
		        	myDialog.destroy();
		        }, 0);
		    });
			*/
			myDialog.render();
			
			myDialog.show();
		}
	}

	var handleFailure = function(o){

		if(o.responseText !== undefined){
			oDiv.style.display = "inline";
			
			oDiv.innerHTML = "<div class=\"hd\">Error</div>";
			oDiv.innerHTML += "<div class=\"bd\"><ul><li>Transaction id: " + o.tId + "</li><li>HTTP status: " + o.status + "</li><li>Status code message: " + o.statusText + "</li></ul></div>";
			oDiv.innerHTML += "<div class=\"ft\">&#32;</div>";
			
			var myPanel = new YAHOO.widget.Panel(panelId, 
					{
						width:"500px", 
						zindex:9999,
						visible:false, 
						constraintoviewport:true,
						fixedcenter:true,
						draggable:false,
						modal:true,
						close:true
					} 
			);
			/*
			myDialog.hideEvent.subscribe(function () {
		        window.setTimeout(function () {
		        	myDialog.destroy();
		        }, 0);
		    });
			*/
			myPanel.render();
			
			myPanel.show();
		}
	}

	var callback =
	{
	  cache:false,
	  success:handleSuccess,
	  failure:handleFailure
	};

	var request = YAHOO.util.Connect.asyncRequest('GET', queryString, callback);	
}
function reloadAfterAsyncRequest(method, url) {
	var logoutOK = function(o){
		window.location.reload();
	}
	var logoutErr = function(o){
		window.location.reload();
	}

	var callback =
	{
	  success:logoutOK,
	  failure:logoutErr
	};
	var request = YAHOO.util.Connect.asyncRequest(method, url, callback);	
}

function logout() {
	reloadAfterAsyncRequest('GET', '?logout');	
}
