//
// Variables globales

defaultCurrentTab = null;
defaultIndexTab = null;
var detect = navigator.userAgent.toLowerCase();
var OS,browser,total,thestring;
var version = 0;
var defaultKeyList = new Array();
var defaultTxtList = new Array();


//
// Detecci?n de Browser

if (checkIt('konqueror'))
{
	browser = "Konqueror";
	OS = "Linux";
}
else if (checkIt('omniweb')) browser = "OmniWeb"
else if (checkIt('opera')) browser = "Opera"
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab"
else if (checkIt('msie')) browser = "MSIE"
else if (!checkIt('compatible'))
{
	browser = "NSN"
	version = detect.charAt(8);
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

if (!OS)
{
	if (checkIt('linux')) OS = "Linux";
	else if (checkIt('x11')) OS = "Unix";
	else if (checkIt('mac')) OS = "Mac"
	else if (checkIt('win')) OS = "Windows"
	else OS = "an unknown operating system";
}

function checkIt(string)
{
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

//
//

		function moveLayerObject(lyr){
			this.fIn = false;
			this.fSel = false;
			this.fX0 = 0;
			this.fY0 = 0;
			this.fX = lyr.style.pixelLeft;
			this.fY = lyr.style.pixelTop;
			this.layer = lyr;
			
			this.onMouseDown = moveMouseDown;
			this.onMouseUp = moveMouseUp;
			this.onMouseOver = moveMouseOver;
			this.onMouseOut = moveMouseOut;
			this.onMouseMove = moveMouseMove;

			function moveMouseDown(){
				if (this.fIn){
					if (!this.fSel){
						this.fX0 = event.screenX;
						this.fY0 = event.screenY;
						this.fSel = true;
					}
				}
			}
			
			function moveMouseUp(){
				this.fSel = false;
			}
			
			function moveMouseOver(){
				if (!this.fIn) this.fIn = true;
			}
			
			function moveMouseOut(){
				this.fIn = false;
				this.fSel = false;
			}
			
			function moveMouseMove(){
				if (this.fSel && this.fIn){
					dx = event.screenX - this.fX0;		
					dy = event.screenY - this.fY0;
					this.fX = this.fX + dx;
					this.fY = this.fY + dy;
					this.fX0 = event.screenX;
					this.fY0 = event.screenY;
					this.layer.style.left =  this.fX + "px";
					this.layer.style.top = this.fY  + "px";
				}
			}


		}
		
//

function switchFilterListado(){
	var estado = document.getElementById("lyrFiltroListado").style.visibility;
	if (estado == "visible") estado = "hidden";
	else estado = "visible";
	document.getElementById("lyrFiltroListado").style.visibility = estado;
}

function promptAndLoadWindowToLayer(w, url, extra){
	idCurr = w.getSelectedIndex() + 1;
	idLyr = parseInt(prompt(w.windowToLayerPrompt, 1));
	if ((isNaN(idLyr)) || (idLyr < 1) || (idLyr > 10)) alert(w.windowToLayerError);
	else {
		st = true;
		if (idLyr == idCurr) st = confirm(w.windowToLayerConfirm);
		if (st){
			w.setSelectedIndex(idLyr - 1);
			w.changeWindow();
			w.windowToLayer(idLyr, url, extra);			
		}
	}
}


function EntraCelda(id){
	rowOver = eval(id);
	lastOverClassName = rowOver.className;
	rowOver.className = "listaRowOver";		
}

function SaleCelda(id){
	rowOver = eval(id);
	rowOver.className = lastOverClassName;					
}


function logOut(){
	window.location.href = ('logout.php');
}

function setMaskDateText(){
	idPersonaFechaNacimiento.innerText = "El formato el dd/mm/yyyy";
}

//
// Accion a realizar cuando se va de una p?gina a otra

function docBeforeUnload(x, y){
	try{
		lyrGo.style.left = x;
        	lyrGo.style.top = y;
		lyrGo.style.visibility = "visible";
		document.recalc;
	} catch(e){
		return true;
	}
}

//
// Colocaci?n del mensaje "Cambiando ... "

function docPopUpBeforeUnload(){
	try{
		s1 = new Number((tblPopUp.clientWidth - 300)/2);
		s1 = s1.toString();
		lyrGo.style.left = s1.concat("px");
		s1 = new Number((tblPopUp.clientHeight - 30)/2);
		s1 = s1.toString();
		lyrGo.style.top = s1.concat("px");
		lyrGo.style.visibility = "visible";
		document.recalc;
	} catch(e){
		return true;
	}
}

//
// 

function docPopUpBeforeUnloadCandidato(){
	try{
		s1 = new Number((734 - 350)/2);
		s1 = s1.toString();
		lyrGo.style.left = s1.concat("px");
		s1 = new Number((500 - 30)/2);
		s1 = s1.toString();
		lyrGo.style.top = "-150px";
		lyrGo.style.visibility = "visible";
		//document.write(defaultOnUnloadMessage);
		document.recalc;
	} catch(e){
		return true;
	}
}


//
// Recarga la ventana que abri? a la actual.

function reloadOpener(){
	if (window.opener != null) window.opener.reload();
}


function ReloadRoot(){
	window.location.href = window.location.protocol + "//" + window.location.hostname + window.location.pathname + window.location.port;
}

//
// A?ade al texto de selecci?n del buscador el ?tem de ayuda

function clickHelpItem(itemKey){
	/*w = window.opener;
	while ((w.name != "Finder") && (w != null)) w = w.opener;
	if (w.name == "Finder"){
		w.document.formBuscador.consulta.value = w.document.formBuscador.consulta.value + itemKey;
		return w.document.formBuscador.consulta.focus();
	}*/
	wLast = window;
	w = window;
	while (wLast != null) {
		w = wLast;
		wLast = w.opener;
	}
	w.document.formBuscador.consulta.value = w.document.formBuscador.consulta.value + itemKey;
	return w.document.formBuscador.consulta.focus();
}

//
//

function ToolSubmitForm(varName, varVal){
	doChecks = false;
  if (varName && varVal) defaultSubmitForm.action = defaultSubmitForm.action + "&" + varName + "=" + varVal;
	if(defaultSubmitObject) defaultSubmitObject.click();
	else defaultSubmitForm.submit();
}

//
// Rellena los arrays de provincias para la construcci?n din?mica

function InitComboProvincias(Pro){
	for (i = 0; i < Pro.options.length; i++){
		defaultKeyList[i] = Pro.options(i).value;
		defaultTxtList[i] = Pro.options(i).text;
	}
}


//
// Cambio de pais -> Relleno el combo de provincias

function DoChangePais(Obj, idProvincia){
	Pro = getFormElementById(defaultSubmitForm, "id_provincia");
	while (Pro.options.length != 0) Pro.options.remove(0);
	if (Obj.value == 24){
		for (i = 0; i < defaultKeyList.length; i++){
			var oOption = document.createElement("OPTION");
			Pro.options.add(oOption);
			oOption.innerText = defaultTxtList[i];
			oOption.value = defaultKeyList[i];
		}
	} else	{
		var oOption = document.createElement("OPTION");
		Pro.options.add(oOption);
		oOption.innerText = "-";
		oOption.value = "";
	}
	if (idProvincia) Pro.selectedIndex = idProvincia;
}

//
// Funci?n para realizar el submit de un form cuando hay que recargar
// un combo: Ej. combo paises

function DoChangeElement(Obj){
	doChecks = false;
	defaultSubmitForm.action = defaultSubmitForm.action + "&" + Obj.idChange + "=" + Obj.value + "&tabName=" + defaultCurrentTab;
	defaultSubmitObject.click();
}

//
// Acci?n para a?adir un nuevo objeto a la lista

function DoAddObjectToList(Name, Value){
	doChecks = false;
	defaultSubmitForm.action = defaultSubmitForm.action + "&" + Name + "=" + Value +  "&tabName=" + defaultCurrentTab;
	defaultSubmitObject.click();
}

//
// Funci?n para realizar el submit de un form cuando hay que recargar
// un combo: Ej. combo idioma
function DoChangeAspectoElement(Obj){
	defaultSubmitForm.action = defaultSubmitForm.action + "&" + Obj.idChange + "=" + Obj.value;
	if (Obj.value) defaultSubmitObject.click();
}


function OpenTraduccion(name){
 if (window.event) 
	return window.open("Translate." + name + ".php", "Traduccion", "left=" + GetX(300) + ",top=" + GetY(255) + ",width=700,height=450,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");
  else
	return window.open("Transalate." + name + ".php", "Traduccion", "width=700,height=450,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");
}


function OpenHelp(tema){
	window.open('Help.php?tema=' + tema, 'Help', 'left=10,top=10,width=300,height=280,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no');
}

function OpenClientesGeneral(){
	//window.location.href = 'Clientes.general.php';
	windowToLayer(defaultIndexTab, "Clientes.general.php", "Clientes");
}

function OpenUsuariosGeneral(){
	//window.location.href = 'Usuarios.general.php';
	windowToLayer(defaultIndexTab, "Usuarios.general.php", "Usuarios");
}

function OpenMantenimientoDerechosGruposUsuarios(idUsu){
	return window.open('Derechos.GruposUsuarios.php?idSelected=' + idUsu, 'MantenimientoDerechosGruposUsuarios', 'width=680,height=325,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no');
}

function OpenMantenimientoClientes(act, idcli){
    if (window.event)
        return window.open('Clientes.mantenimiento.php?act=' + act + '&idcli=' + idcli, 'MantenimientoClientes', 'left=' + GetX(650) + ',top=' + GetY(470) + ',width=650,height=470,resizable=yes,scrollbars=no,menubar=no,toolbar=no,directories=no,location=no,status=no')
	else
    	return window.open('Clientes.mantenimiento.php?act=' + act + '&idcli=' + idcli, 'MantenimientoClientes', 'width=650,height=470,resizable=yes,scrollbars=no,menubar=no,toolbar=no,directories=no,location=no,status=no')
}

// Abre la ventana de mantenimiento de usuarios

function OpenMantenimientoUsuarios(act, idusr){
    if (window.event)
        return window.open('Usuarios.mantenimiento.php?act=' + act + '&idusr=' + idusr, 'MantenimientoUsuarios', 'left=' + GetX(650) + ',top=' + GetY(470) + ',width=650,height=470,resizable=yes,scrollbars=no,menubar=no,toolbar=no,directories=no,location=no,status=no')
	else
    	return window.open('Usuarios.mantenimiento.php?act=' + act + '&idusr=' + idusr, 'MantenimientoUsuarios', 'width=650,height=470,resizable=yes,scrollbars=no,menubar=no,toolbar=no,directories=no,location=no,status=no')
}

//
// Abre la ventana de mantenimiento de grupos

function OpenDerechosGrupos(id){
  if (window.event) 
	return window.open('Derechos.Grupos.php?idSelected=' + id, 'MantenimientoGrupos', 'left=' + GetX(700) + 'top=' + GetY(470) + ',width=700,height=550,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no')
  else
	return window.open('Derechos.Grupos.php?idSelected=' + id, 'MantenimientoGrupos', 'width=700,height=550,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no')
}

//
// Abre la ventana de mantenimiento de grupos de usuarios

function OpenDerechosGruposUsuarios(){
  if (window.event) 
	return window.open('Derechos.GruposUsuarios.php', 'MantenimientoGruposUsuarios', 'left=' + GetX(700) + 'top=' + GetY(470) + ',width=700,height=525,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no')
  else
	return window.open('Derechos.GruposUsuarios.php', 'MantenimientoGruposUsuarios', 'width=700,height=525,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no')
}

//
// Muestra la lista de usuarios

function OpenListaUsuarios(idcli){
	if (window.event) 
	  return window.open('Usuarios.cliente.php?idcli=' + idcli, "listausuarioscliente", "left=" + GetX(790) + ",top=" + GetY(255) + ",width=450,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no,z-lock=yes,alwaysRaised=yes");  
	else
	  return window.open('Usuarios.cliente.php?idcli=' + idcli, "listausuarioscliente", "width=450,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no,z-lock=yes,alwaysRaised=yes");  
}
//
// Ventanas de ayuda
function OpenItemHelp(tema,name) {
	if(!name) name="";
  if (window.event) 
	return window.open("Help.mostrarItem.php?tema=" + tema, "HelpItem" + name, "left=" + GetX(600) + ",top=" + GetY(255)+",width=600,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");  
  else 
    return window.open("Help.mostrarItem.php?tema=" + tema, "HelpItem" + name, "width=600,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");  
}

//TX
function OpenItemHelpModulo(tema,name) {
	if(!name) name="";
  if (window.event) 
	return window.open("Help.mostrarItemModulo.php?tema=" + tema, "HelpItem" + name, "left=" + GetX(600) + ",top=" + GetY(255)+",width=600,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");  
  else 
    return window.open("Help.mostrarItemModulo.php?tema=" + tema, "HelpItem" + name, "width=600,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");  
}
function OpenItemHelpModuloPregunta(id_modulo) {
	if(!name) name="";
  if (window.event) 
	return window.open("Help.mostrarItemModuloPregunta.php?id_modulo=" + id_modulo, "HelpItemPregunta" + id_modulo, "left=" + GetX(600) + ",top=" + GetY(255)+",width=600,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");  
  else 
    return window.open("Help.mostrarItemModuloPregunta.php?id_modulo=" + id_modulo, "HelpItemPregunta" + id_modulo, "width=600,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");  
}
function OpenItemHelpModuloRespuesta(id_pregunta) {
	if(!name) name="";
  if (window.event) 
	return window.open("Help.mostrarItemModuloRespuesta.php?id_pregunta=" + id_pregunta, "HelpItemRespuesta" + id_pregunta, "left=" + GetX(600) + ",top=" + GetY(255)+",width=600,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");  
  else 
    return window.open("Help.mostrarItemModuloRespuesta.php?id_pregunta=" + id_pregunta, "HelpItemRespuesta" + id_pregunta, "width=600,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");  
}

//

function OpenEncoded(url, windowName){
  if (window.event) 
	return window.open(url, windowName, "left=" + GetX(600) + ",top=" + GetY(255)+",width=600,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");  
  else
	return window.open(url, windowName, "width=600,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");  
}

function OpenTreeHelp(tema) {
  if (window.event) 
	return window.open("Help.php?tema=" + tema, "Help", "left=" + GetX(300) + ",top=" + GetY(255) + ",width=300,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");
  else
	return window.open("Help.php?tema=" + tema, "Help", "width=300,height=255,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");
}


function OpenTranslateClases(){
 if (window.event) 
	return window.open("Translate.clases.php", "TranslateClases", "left=" + GetX(300) + ",top=" + GetY(255) + ",width=780,height=515,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");
  else
	return window.open("Translate.clases.php", "TranslateClases", "width=780,height=515,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no");
}

function GetX(w){
	x0 = window.event.screenX;
	ww = window.screen.width;
	if ((x0 + w) > ww) x0 = ww - w - 20;
	return x0;
}

function GetY(h){
	y0 = window.event.screenY;
	hw = window.screen.height;
	if ((y0 + h) > hw) y0 = hw - h - 20;
	return y0;
}


// Ajusta el tama?o de ventana
function Previa(){
	self.resizeTo(800, 580);
	self.moveTo(0, 0);
	self.focus();
}

// Obtiene el elemento del form por su id
function getFormElementById(f, id){
	if (f != null){
		for(i = 0; i < f.elements.length; i++)
		  if (f.elements[i].id == id) return f.elements[i];
	} return null;
}


// Limita el tama?o de un campo texto
function LimitText(field, maxlimit) {
	try{
 		if (field.value.length >= maxlimit){
			event.returnValue = false;
			if (defaultCheckTextLimitError != "") alert(defaultCheckTextLimitError);
		} 
		//else event.returnValue = true;
	} catch(e){
	}

}

// Verifica formato num?rico. Admite decimales.
// El sgundo parametro es opcional e indica el valor maximo permitido en el campo
function checkNumeric(Obj, max){
	
	if (isNaN(Obj.value) && (Obj.value != "")){
		var tmp = Obj.value.replace(/,/gi, ".");
		if (isNaN(tmp) && (tmp != "")) {
			Obj.value = "";
			if (defaultCheckNumericError != "") alert(defaultCheckNumericError);
			Obj.focus();
			return false;
		}
		Obj.value = tmp;
	}
	
	if (max) {
		if ((Obj.value * 1) > max)
		{
			Obj.value = "";
			if (defaultCheckNumericError != "") alert(defaultCheckNumericError);
			Obj.focus();
		}
	}
	
	return true;
}

function checkPasteAndLength(Obj, maximo){
	var	i;
	var dataIn;
	var dataOut;
	dataIn = window.clipboardData.getData('Text');
	dataOut = new String("");
	for(i = 0; i < dataIn.length; i++){
	  	if ((i < maximo) || (maximo == 0)){
  			c = dataIn.charCodeAt(i);
  			if (c == 34 || c == 39) dataOut = dataOut.concat("`")
	      else dataOut = dataOut.concat(dataIn.charAt(i));
    	}
	}		
 	window.clipboardData.setData('Text', dataOut);
}

// Verifica formato date
function checkdate(Obj){
	var timestamp = chkTimeStamp(Obj.value);
	if (timestamp != 'error') {
		Obj.value = timestamp;
		return true;
	}
	else {
		Obj.value = '';
		if (defaultCheckDateError != "") alert(defaultCheckDateError);
		else alert('DATETIME ERROR');
		Obj.focus();
		return false;
	}
}


function chkTimeStamp(timestamp){
	var date = '';
	var time = '';
	var fields = new Array();
	var strSeparador = ' ';

	if (timestamp == '') return '';	
	fields = timestamp.split(strSeparador);
	date = chkDateDDMMYYYY(fields[0]);
	if (date == 'error') return 'error';
	if (fields.length > 1) time = chkTimeHHMMSS(fields[1]);
	if (date == 'error' || time == 'error') return 'error';
	if (time != '') return date + strSeparador + time;
	else return date;
}


function chkTimeHHMMSS(time){
	var intHoras = 0;
	var intMinutos = 0;
	var intSegundos = 0;
	var strHoras = '';
	var strMinutos = '';
	var strSegundos = '';
	var strSeparador = ':';
	var fields = new Array();

	if (time == '') return '';
	fields = time.split(strSeparador);
	if (fields.length == 1 && fields[0].length == 6){
		intHoras = fields[0].substr(0, 2);
		intMinutos = fields[0].substr(2, 2);	
		intSegundos = fields[0].substr(4, 2);	
	}	else if (fields.length == 1 && fields[0].length == 4) {
		intHoras = fields[0].substr(0, 2);
		intMinutos = fields[0].substr(2, 2);	
		intSegundos = 0;	
	} else {
		for (var i = 0; i < 3; i++) if (fields[i] == '')  fields[i] = '0';
		for (var i = fields.length; i < 3; i++) fields[i] = '0';
		intHoras = parseInt(fields[0]);
		intMinutos = parseInt(fields[1]);
		intSegundos = parseInt(fields[2]);
	}
	if (isNaN(intHoras) || (intHoras < 0) || (intHoras > 23)) return 'error';	
	if (isNaN(intMinutos) || (intMinutos < 0) || (intMinutos > 59)) return 'error';	
	if (isNaN(intSegundos) || (intSegundos < 0) || (intSegundos > 59)) return 'error';	
	if (intHoras < 10) strHoras = '0' + intHoras;
	else strHoras = intHoras;
	if (intMinutos < 10) strMinutos = '0' + intMinutos;
	else strMinutos = intMinutos;
	if (intSegundos < 10) strSegundos = '0' + intSegundos;
	else strSegundos = intSegundos;
	return strHoras + strSeparador + strMinutos + strSeparador + strSegundos
}

function chkDateDDMMYYYY(date) {
 var strDate;
 var strDateArray;
 var strDay;
 var strMonth;
 var strYear;
 var intday;
 var intMonth;
 var intYear;
 var booFound = false;
 var strSeparatorArray = new Array("-"," ","/",".");
 var intElementNr;
 var err = 0;
 
 strDate = date;
 if (!strDate) return ''; 
 if ((strDate.length < 6)&(strDate.length>0)) return 'error';
 for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
  if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {	
		strDateArray = strDate.split(strSeparatorArray[intElementNr]);
		if (strDateArray.length != 3){
				err = 1;
				return 'error';
		 } else {	
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
		 }
 		booFound = true;
  }
 }
 if (booFound == false) {
  if (strDate.length>5) {
		strDay = strDate.substr(0, 2);
		strMonth = strDate.substr(2, 2);
		strYear = strDate.substr(4);
   }
 	}
 if ((strYear.length != 4) || (strYear == '0000')) {
  err = 2;
  return 'error';
 }
 
 if (strDay.length  == 1) strDay = '0'+ strDay;
 if (strMonth.length == 1) strMonth = '0' + strMonth;
 intday = parseInt(strDay, 10);
 if (isNaN(intday)) {
  err = 2;
  return 'error';
 }
 intMonth = parseInt(strMonth, 10);
 if (isNaN(intMonth)) {
		for (i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
			}
		}
		if (isNaN(intMonth)) {
			err = 3;
			return 'error';
		}
 }
 intYear = parseInt(strYear, 10);
 if (isNaN(intYear)){
   err = 4;
   return 'error';
 }
 if (intMonth>12 || intMonth<1) {
   err = 5;
   return 'error';
 }
 if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
   err = 6;
   return 'error';
 }
 if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)){
   err = 7;
   return 'error';
 }
 if (intMonth == 2){
   if (intday < 1){
     err = 8;
     return 'error';
   }
   if ((((intYear % 4 == 0) && (intYear % 100 != 0)) || (intYear % 400 == 0)) ? 1 : 0){
	 		// Es bisiesto
     if (intday > 29){
     	err = 9;
     	return 'error';
     }
   }
   else{
	 	// No es bisiesto
 			if (intday > 28){
		 		err = 10;
 				return 'error';
     	}
   }
 }
 return  strDay + "/" + strMonth + "/" + strYear;
 }



// Filtra caracteres "comillas" pulsados
function formkeypress(){
	if ((event.keyCode == 219) || ((event.keyCode == 50) && (event.shiftKey))) event.returnValue = false;
	//else{
		//event.returnValue = true;
	//}
}

// Recarga la p?gina despu?s de un click en la fila de la tabla
function SelectRow(pUrl){
	if (pUrl != "") window.location.href = (pUrl);  
}


// Cambia el color de celda al pasar el mouse
function RowColor(nombre, color){
	try{
		switch(browser){
			case "NSN": eval(nombre + ".background='" + color + "'"); break;
			default: eval(nombre + ".style.background='" + color + "'"); break;
		}
  		
	} catch(e){
	}
	
}
function CheckAll(){
    var max;
	max = defaultSubmitForm.length;
	for(i=0;i<=max;i++) {
      try{
    	if(defaultSubmitForm.elements[i].type == "checkbox")	
          defaultSubmitForm.elements[i].checked='true';
	  } catch(e){}
}    }

//grupo de funciones para el formulario de aspecto
var vinc;

function recuperar_def(nombre,color) 
 {
  if(nombre=="") nombre=vinc;  
  clr =color;
  var cadena="";
  var cadena1="";
  cadena=nombre+'.style.background=\"'+clr+'\"';
  eval(cadena);
  cadena1='document.formAspecto.'+nombre+'.value=\"'+clr+'\"';
  eval(cadena1);
}

function view_color(nom) 
 {
   colors.style.visibility="visible";
   vinc=nom; 
}

function hidden_color() 
 {
   colors.style.visibility="hidden";
}

function colorfons(objName,nombre) 
{
  var color = objName;
  if(color.value.length == 7) {
    var clr;  
    clr =color.value;  
    cadena=nombre+'.style.background=\"'+clr+'\"';
    eval(cadena);
  } 	
}

// paleta de colores

var x0;
var y0;
var moving = false;

function ToolMouseDown() {
  x0 = window.event.x;
  y0 = window.event.y; 
  moving = true;
}

function ToolMouseUp() {
  moving = false;
}

function ToolMouseMove() {
  if (moving){
   dx = (window.event.x - x0);
   dy = (window.event.y - y0);
   x0 = window.event.x;
   y0 = window.event.y;
   tx = Math.ceil(colors.style.left.substr(0, colors.style.left.length - 2)) + dx;
   ty = Math.ceil(colors.style.top.substr(0, colors.style.top.length - 2)) + dy;
   if (tx < 0) tx = 0;
   if (ty < 0) ty = 0;
   colors.style.left = tx;
   colors.style.top = ty;
  }
	
}
//
// Muestra una imagen en una nueva ventana
function OpenImage(image,name){
	if (window.event) 
	  return window.open(image, name, "left=" + GetX(790) + ",top=" + GetY(255) + ",width=300,height=300,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no,z-lock=yes,alwaysRaised=yes");  
	else
	  return window.open(image, name, "width=300,height=300,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no,z-lock=yes,alwaysRaised=yes");  
}

function emailCheck (emailStr) {
	/* The following pattern is used to check if the entered e-mail address
		 fits the user@domain format.  It also is used to separate the username
		 from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
		 characters.  We don't want to allow special characters in the address. 
		 These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a 
		 username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
		 which case, there are no rules about which characters are allowed
		 and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
		 is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
		 rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
		 e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
		 non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
		 For example, in john.doe@somewhere.com, john and doe are words.
		 Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
		 domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	
	
	/* Finally, let's start trying to figure out if the supplied address is
		 valid. */
	
	/* Begin with the coarse pattern to simply break up user@domain into
		 different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
		/* Too many/few @'s or something; basically, this address doesn't
			 even fit the general mould of a valid e-mail address. */
		alert(defaultCheckMailAddressError)
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	
	// See if "user" is valid 
	if (user.match(userPat)==null) {
			// user is not valid
			alert(defaultCheckMailAddressError)
			return false
	}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
		 host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
			// this is an IP address
			for (var i=1;i<=4;i++) {
				if (IPArray[i]>255) {
						alert(defaultCheckMailAddressError)
			return false
				}
			}
			return true
	}
	
	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert(defaultCheckMailAddressError)
			return false
	}
	
	/* domain name seems valid, but now make sure that it ends in a
		 three-letter word (like com, edu, gov) or a two-letter word,
		 representing country (uk, nl), and that there's a hostname preceding 
		 the domain or country. */
	
	/* Now we need to break up the domain to get a count of how many atoms
		 it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
			domArr[domArr.length-1].length>3) {
		 // the address must end in a two letter or three letter word.
		// alert(defaultCheckMailAddressError)
		 return false
	}
	
	// Make sure there's a host name preceding the domain.
	if (len<2) {
		 var errStr="This address is missing a hostname!"
		 alert(errStr)
		 return false
	}
	
	// If we've gotten this far, everything's valid!
	return true;
}

//
// Funciones para llamadas As?ncronas a un servicio desde un tag <SCRIPT>

	var globalSufix = 0;
	
	function jsAcGetSufix(){
		globalSufix++;
		return globalSufix;
	}
	
	function jsAcDoCall(jsAcUrlService, jsAcTimeOut){
		this.jsAcUrlService = jsAcUrlService;
		this.jsAcTimeOut = jsAcTimeOut;
		if (this.jsAcSufix == "") this.jsAcSufix = this.getSufix();
		if (this.jsAcCreateChildElement){
			this.jsAcParentElement.innerHTML = this.jsAcParentElement.innerHTML + "<script id='" + this.jsAcName + this.jsAcSufix + "'><\/script>";
			//this.jsAcIdScript = eval(this.jsAcName + this.jsAcSufix);
			this.jsAcIdScript = document.getElementById(this.jsAcName + this.jsAcSufix);
		} else this.jsAcIdScript = this.jsAcParentElement;
		this.jsAcIdScript.src = this.jsAcUrlService + "&sufix=" + this.jsAcSufix;
		//window.clipboardData.setData('Text', this.jsAcIdScript.src);
		setTimeout("jsAcCheckFinish('" + this.jsAcVarName + "')", 100);
	}

	function jsAcRemoveScriptData(){
		eval("returnCall" + this.jsAcSufix + " = ''");
		eval("statusCall" + this.jsAcSufix + " = ''");
		if (this.jsAcCreateChildElement) this.jsAcIdScript.removeNode();
	}

	function jsAcDoCallBack(){
		eval(this.callBack + "('" + this.jsAcVarName + "');");
	}
	
	function jsAcCheckFinish(jsAcVarName){
		jsAcObj = eval(jsAcVarName);
		try {
			eval("loadedCall" + jsAcObj.jsAcSufix);
			jsAcObj.returnCall = eval("returnCall" + jsAcObj.jsAcSufix);
			jsAcObj.statusCall = eval("statusCall" + jsAcObj.jsAcSufix);
			jsAcObj.removeScriptData();
			jsAcObj.doCallBack();
		} catch(e) {
			if (jsAcObj.jsAcTimeOut > 0){
				jsAcObj.jsAcTimeOutCount = jsAcObj.jsAcTimeOutCount + 20;
				if (jsAcObj.jsAcTimeOutCount < jsAcObj.jsAcTimeOut) setTimeout("jsAcCheckFinish('" + jsAcObj.jsAcVarName + "')", 20);
				else {
					jsAcObj.returnCall = "";
					jsAcObj.statusCall = "Time Out Reached (" + jsAcObj.jsAcTimeOutCount + ") for '" + jsAcObj.jsAcIdScript.src + "' in '" + jsAcObj.jsAcVarName + "." + jsAcObj.jsAcVarName + "'";
					jsAcObj.removeScriptData();
					jsAcObj.doCallBack();
				}
			}
			else setTimeout("jsAcCheckFinish('" + jsAcObj.jsAcVarName + "')", 20);
		}
	}
	
	function jsAsyncCall(jsAcVarName, jsAcName, jsAcSufix, jsAcParentElement, jsAcCreateChildElement, jsAcCallBack){
		
		this.returnCall = "";
		this.statusCall = "";
		
		this.getSufix = jsAcGetSufix;
		this.doCall = jsAcDoCall;
		this.callBack = jsAcCallBack
		this.checkFinish = jsAcCheckFinish;
		this.removeScriptData = jsAcRemoveScriptData;
		this.doCallBack = jsAcDoCallBack;
		
		this.jsAcVarName = jsAcVarName;
		this.jsAcName = jsAcName;
		this.jsAcSufix = jsAcSufix;
		this.jsAcParentElement = jsAcParentElement;
		this.jsAcIdScript = null;
		this.jsAcTimeOutCount = 0;
		this.jsAcCreateChildElement = jsAcCreateChildElement;
		
	}

	function defaultJsCallBackObject(jsAcVarName){
		jsAcObj = eval(jsAcVarName);
		if (jsAcObj.statusCall != "") alert(jsAcObj.statusCall)
		else if (jsAcObj.returnCall != "") alert(jsAcObj.returnCall);
	}

/* Busca un elemento hijo de node que tenga el id indicado.*/
function get_element_by_id(node, id) {
		
	var n;
		
	for(var i = 0; i < node.childNodes.length; i++) {
		
		if (node.childNodes[i].id == id) return node.childNodes[i];
		n = get_element_by_id(node.childNodes[i], id);
		if (n) return n;
	}
		
	return null;
}


function OpenFichaEmpresa(){
	window.open("Mantenimiento.Empresa.php?act=update", "MantenimientoEmpresa", "width=445,height=360,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no,z-lock=yes,alwaysRaised=yes");
}

function OpenMANSolicitud(act, idSolicitud){
	window.open("Mantenimiento.Solicitud.php?act=" + act + "&idSolicitud=" + idSolicitud, "MantenimientoSolicitud", "width=570,height=395,resizable=yes,scrollbars=no,menubar=no,toolbar=no,directories=no,location=no,status=no,z-lock=yes,alwaysRaised=yes");
}

function OpenLISSolicitud(){
	windowToLayer(defaultIndexTab, "Listado.Solicitud.php", "WSConSolicitud");
}

function OpenMANComunicados(act, idComunicados, cliente_destino, entidad_referenciada, tipo){
	window.open("Mantenimiento.Comunicados.php?act=" + act + "&idComunicados=" + idComunicados + "&cliente_destino=" + cliente_destino + "&entidad_referenciada=" + entidad_referenciada + "&tipo=" + tipo, "MantenimientoComunicados", "width=445,height=370,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no,z-lock=yes,alwaysRaised=yes");
}

/*
* Contiene la informaci?n de validaci?n de un campo del formulario.
*
* field_name: nombre del campo.
* obj_name: id del elemento HTML que contiene el valor del campo.
* error_msg: mensaje de error que se mostrara cuando el campo este vac?o.
* required: boleano que indica si es obligatorio que el campo contenga algun valor antes de enviar el formulario.
*/
function FieldCheck(field_name, obj_name, error_msg, required)
{
	this.field_name = field_name;
	this.obj_name = obj_name;
	this.error_msg = error_msg;
	this.required = required;
	this.check = required; 	// Indica si hay que validar el campo. Por defecto tiene el mismo valor que "required" pero
							// hay casos en que interesa que un campo requerido no se valide siempre (ej: campos que solo 
							// son necesarios si hay algun valor concreto en otro campo (decisiones dinamicas)).
	
	return this;
}