
/** Deshabilita y habilita los campos del formulario mientras cargo AJAX
*/
function cargando1(){

	for (i = 0 ; i < document.forms[0].elements.length ; i++){
		document.forms[0].elements[i].disabled = true;
	}
}
function cargando2(){

	for (i = 0 ; i < document.forms[0].elements.length ; i++){
		document.forms[0].elements[i].disabled = false;
	}
}



/** Comprueba si los campos de los formularios de una páginas están llenos
*
* @param	Campos			Array con el nombre de los campos a comprobar
* @param	Alertas			Array con el literal de las alertas a visualizar para cada campo
* @return	true			Si los campos están cumlimentados
* 			false			Si los campos están vacios
*
* @example					function comprueba(){
							var Campos= new Array("campo1","campo2");
							var Alertas= new Array("alerta1","alerta2");
							return CompruebaForm(Campos,Alertas);
}
*/
function CompruebaForm(Campos,Alertas){
	var k=0;
	var resultado=0;
	for (k=0;k<Campos.length;k++){
		resultado=resultado + EstaLleno(Campos[k],Alertas[k]);
	}
	if (resultado==0){
		return true;
	} 
	else {
		return false;
	}
}
function EstaLleno(campo,alerta){
  for(i=0; i < document.forms.length; ++i) {
    var obj = document.forms[i].elements[campo];
    if (obj.value == ''){
		alert (alerta);
		obj.focus();
		obj.style.background='#FFF59F';
		return 1;
	}
	else{
		return 0;
	}
  }
}


/** Copia el contenido de un campo del texto en el portapapeles
*
* @param	campo			objeto textField
* @return					Texto copiado al portapapeles
* @example					<input name="Texto" type="text" onClick="CopiaralPortapapeles(this);">
*/
function CopiaralPortapapeles(campo){
	campo.select();
	if (document.all){
		rango=campo.createTextRange();
		rango.execCommand("Copy");
		alert ("El contenido del campo se ha guardado en el portapapeles");
	}
}

/** Abre una ventana en un popup
*
* @param	url				string con la dirección de destino a abrir
* @return	AbrirVentana	Ventana Abierta
* @example					AbrirVentana("destino.php")
*/
function AbrirVentana(url){
	var nwin=window.open(url,'Ventana',"width=600,height=500,left=80,top=80,scrollbars=yes,resizable=no,status=yes,menubar=no,location=no,directories=no,copyhistory=no,toolbar=no",true);
	nwin.focus();
}

function AbrirVentanaPequeña(url){
	var nwin=window.open(url,'Ventana',"width=300,height=100,left=80,top=80,scrollbars=no,resizable=no,status=no,menubar=no,location=no,directories=no,copyhistory=no,toolbar=no",true);
	nwin.focus();
}

/** Pregunta antes de enviar a una página de borrado
*
* @param	argumentos		string con la dirección de destino donde se borra
* @return	ConfirmaBorrado	true si se pulsa si y redirige a la página de destino
							false no realiza ninguna acción
* @example					ConfirmaBorrado("borrado.php?borrar=si&id=4")
*/
function ConfirmaBorrado(argumentos){
	var pregunta=window.confirm("¿ Está seguro de que quiere borrar ese registro ?");
	if (pregunta == true){
		window.location.href=argumentos;
	}
}


/** Comprueba si el argumento pasado es una fecha válida
*
* @param	string con la fecha en formato dd/mm/aaaa
* @return	true si la fecha es válida
*			false si la fecha no es correcta
* @example
			function Comprueba(){
				if ((alta.Fecha.value!='')){
					if (isDate(alta.Fecha.value)==false){
						alta.Fecha.focus();
						return false;
					}
				}
			}
*/
function isDate(dateStr) {
	
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat);
	if (matchArray == null) {
		alert("Introduzca una fecha válida");
		return false;
	}
	
	month = matchArray[3];
	day = matchArray[1];
	year = matchArray[5];
	
	if (month < 1 || month > 12) {
		alert("El mes debe estar entre 1 y 12");
		return false;
	}
	
	if (day < 1 || day > 31) {
		alert("El día debe estar entre 1 y 31");
		return false;
	}
	
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		alert("El mes "+month+" no tiene 31 días!")
		return false;
	}
	
	if (month == 2) {
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) {
			alert("Febrero " + year + " no tiene " + day + " dias!");
			return false;
		}
	}
	return true;
}

/** Valida el formato de una dirección email
*
* @param	valor			string con la dirección de correo
* @return	validarEmail	true si el formato es válido. valida dominios con 4 caracteres
							false si no es válido
* @example					validarEmail("pp@pp.com")
*/
function validarEmail(valor) {
  if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(valor)){
    return true;
  } else {
    //alert("La dirección de email es incorrecta.");
    return false;
  }
}

function MuestraOculta(elId,elLink) { 
   // Muestra y oculta un bloque y cambia el contenido del link

   var el = document.getElementById(elId); 
   var link = document.getElementById(elLink); 

   if (el.style.display=="none") { 
      el.style.display="block"; //Muestra el elemento
      link.innerHTML = "[-]"; 
   } 
   else { 
      el.style.display="none"; //Oculta el elemento
      link.innerHTML = "[+]"; 
   } 
   return false; 
}

/** Crea una máscara de fecha para que se introduzcan en formado dd/mm/aaaa
*
* @param	obj				objeto Text con el contenido de la fecha
* @return	MascaraFecha	texto en formato de fecha dd/mm/aaaa
* @example					<input name="Fecha" type="text" onKeyUp="MascaraFecha(this);">
*/
function MascaraFecha(obj){
		var a;
		var b="";
	a= obj.value;
	for (i=0;i<a.length;i++){
		if ((i==2 && a.charAt(i)!='/') || (i==5 && a.charAt(i)!='/')){
			b+='/';
		}
		b+=a.charAt(i);
	}
	obj.value=b;
}

/** Crea una ventana de confirmación para enlaces en los que se va a borrar un registro
*
* @param	argumentos		string con la url de destino
* @return	borrado			redirecciona a la página donde está el scripp de borrado
* @example					<a href="javascript:borrado('borrar.php?')">Eliminar</a>
*/
function borrado(argumentos){
		var rc = window.confirm ("¿Está Seguro de eliminar el registro?") ;
		if (rc == true) {
			window.location.href=argumentos;
		}
}


/** Comprueba si los campos requeridos de un formularios están rellenos
*
* @param	formobj			objeto formulario a evaluar
* @var		fieldRequired	Nombre de los campos requeridos
*			fieldDescription Descripción de los campos que aparecerá en el cuadro de alerta
*			alertMsg		Texto que aparecerá en el cuadro de alerta			
* @return	formCheck		true si los campos están rellenos
*							false si la fecha no es correcta. Muestra un mensaje con los campos que faltan
* @example					<form name="NombreFormulario" onsubmit="return formCheck(this);">
*/
function formCheck(formobj){
	var fieldRequired = Array("FirstName", "LastName");
	var fieldDescription = Array("First Name", "Last Name");
	var alertMsg = "Por favor rellene los siguientes campos:\n";
	
	var l_Msg = alertMsg.length;
	
	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			switch(obj.type){
			case "select-one":
				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "select-multiple":
				if (obj.selectedIndex == -1){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "text":
			case "textarea":
				if (obj.value == "" || obj.value == null){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			default:
			}
			if (obj.type == undefined){
				var blnchecked = false;
				for (var j = 0; j < obj.length; j++){
					if (obj[j].checked){
						blnchecked = true;
					}
				}
				if (!blnchecked){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
			}
		}
	}

	if (alertMsg.length == l_Msg){
		return true;
	}else{
		alert(alertMsg);
		return false;
	}
}


/*****************************************************************************
* BackToTheHtml Command
*///**************************************************************************
function BackToTheHtml(node)
{
	if(node == null)
		this.node = document; 
	else
		this.node = node; 
};
BackToTheHtml.prototype.node = null;

BackToTheHtml.prototype.execute = function()
{
	this.activateObject();
}

BackToTheHtml.prototype.activateObject = function(domObject)
{
	var aDomObject = this.node.getElementsByTagName('object');
	var activationObject;
	for(var i=0; i<aDomObject.length; i++)
		if
		(
			aDomObject[i].getAttributeNode('BackToTheHtml') == null
			&&
			(activationObject = this.getActivationObject(aDomObject[i])) != null
		)
			activationObject.execute();
};

BackToTheHtml.prototype.getActivationObject = function(domObject)
{
	var classid = domObject.classid.toUpperCase().substr('clsid:'.length);
	var mimeType = domObject.type.toLowerCase();

	switch(true)
	{
		case 
			classid == 'D27CDB6E-AE6D-11CF-96B8-444553540000' 
			||
			mimeType == 'application/x-shockwave-flash'
		:
			return new ActivateObjectFlash(domObject);

		default :
			return null;
	}
};

BackToTheHtml.uniqueID = function(prefix)
{
	var sPrefix;
	if(prefix == null)
		sPrefix = 'uniqueId';
	else
		sPrefix = prefix;
		
	var i=0;
	while(document.getElementById(sPrefix + (i++)))
		;
	return sPrefix + (i-1);
};

BackToTheHtml.isParentOf = function(parent,child)
{
	var found = false;
	for(var i=0; i<parent.childNodes.length; i++)
		if(parent.childNodes[i] == child)
			return true;
		else
			found = arguments.callee(parent.childNodes[i],child);

	return found;
}

/*****************************************************************************
* ActivateObject Command
*///**************************************************************************
function ActivateObject(domObject)
{
	this.domObject = domObject;
}

ActivateObject.prototype.domObject = null;
ActivateObject.prototype.classid = null;
ActivateObject.prototype.aHtmlAttribute = ['accessKey','align','alt','archive','border','code','codeBase','codeType','declare','dir','height','hideFocus','hspace','lang','language','name','standby','tabIndex','title','useMap','vspace','width'];
ActivateObject.prototype.aObjectProperty = null;

ActivateObject.prototype.execute = function()
{
	this.xndObjectId = BackToTheHtml.uniqueID();
	this.setTextHtml();
	this.writeObject();

	this.xndObject = document.getElementById(this.xndObjectId);
	this.setSpecialProperties();
	this.removeOriginalObject();
}

ActivateObject.prototype.setTextHtml = function()
{
	var str = '';
	str += '<object BackToTheHtml ' + '\n';
	str += ' classid="clsid:' + this.classid + '" ' + '\n';

	//Add HTML attributes to the <object> tag
	for(var i=0; i<this.aHtmlAttribute.length; i++)
	{
		var name = this.aHtmlAttribute[i];
		if(typeof this.domObject[name] != 'undefined' && this.domObject[name].toString() != '')
			str += '\t' + name + '="' + this.domObject[name].toString() + '" ' + '\n';
	}

	str += 'id="' + this.xndObjectId + '" ' + '\n';
	str += '>';

	for(var i=0; i<this.aObjectProperty.length; i++)
	{
		var name = this.aObjectProperty[i];
		if(typeof this.domObject[name] != 'undefined' && this.domObject[name].toString() != '' )
			str += '\t<param name="' + name + '" value="' + this.domObject[name].toString() + '"></param>' + '\n';
	}
	str += '</object>';

	this.textHtml = str;
};

ActivateObject.prototype.writeObject = function()
{
	this.domObject.insertAdjacentHTML("afterEnd",this.textHtml);
};

ActivateObject.prototype.setSpecialProperties = function()
{
	if(typeof this.domObject.className != 'undefined' && this.domObject.className.toString() != '')
		this.xndObject.className = this.domObject.className

	if(typeof this.domObject.style.cssText != 'undefined' && this.domObject.style.cssText.toString() != '')
		this.xndObject.style.cssText = this.domObject.style.cssText;

	if(typeof this.domObject.SWRemote != 'undefined' && this.domObject.SWRemote.toString() != '')
		this.xndObject.FlashVars = this.domObject.SWRemote;

	if(typeof this.domObject.codebase == 'undefined' || this.domObject.codebase.toString() == '')
		this.xndObject.codebase = 'http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,24,0';

	if(typeof this.domObject.id != 'undefined' && this.domObject.id.toString() != '')
		this.xndObject.id = this.domObject.id;

};

ActivateObject.prototype.removeOriginalObject = function()
{
	this.domObject.parentNode.removeChild(this.domObject);
};

/*****************************************************************************
* ActivateObjectFlash Command
*///**************************************************************************
function ActivateObjectFlash(domObject)
{
	ActivateObject.call(this,domObject);
}
ActivateObjectFlash.prototype = new ActivateObject;
ActivateObjectFlash.prototype.aObjectProperty = ['FrameNum','Playing','Quality','Quality2','Scalemode','Scale','AlignMode','SAlign','BackgroundColor','BGColor','Loop','Movie','WMode','Base','DeviceFont','EmbedMovie','SWRemote','FlashVars','AllowScriptAccess'];
ActivateObjectFlash.prototype.classid = 'D27CDB6E-AE6D-11CF-96B8-444553540000';


/*****************************************************************************
* Script initialisation
*///**************************************************************************
if(typeof ActiveXObject != 'undefined' && typeof Function.call != 'undefined')
{
	var styleId = BackToTheHtml.uniqueID();
	document.write('<style id="' + styleId + '" ></style>');
	var domStyle = document.getElementById(styleId);

	var isHead = false;
	var aHead = document.getElementsByTagName('head');
	for(var i=0; i<aHead.length; i++)
		if(BackToTheHtml.isParentOf(aHead[i],domStyle))
			isHead = true;

	if(isHead)
	{
		document.write('<style type="text/css">OBJECT{visibility:hidden;}</style>');
		document.onreadystatechange = function()
		{
			if(document.readyState == 'complete')
			{
				new BackToTheHtml().execute();
				document.styleSheets[document.styleSheets.length-1].addRule("OBJECT","visibility:visible;");
				//alert('head');
				//alert(document.body.innerHTML);
			}
		}
	}
	else
	{
		new BackToTheHtml().execute();
		//alert('body');
		//alert(document.body.innerHTML);
	}
	
	domStyle.parentNode.removeChild(domStyle);
}