// Funciones javascript varias


// ******************
// * Reloj dinámico *
// ******************
// Variables globales para el reloj
var lang = 'es'; 			// Default: 'es'
var divId= 'dinamic_clock';	// Default: 'dinamic_clock'

function dinamic_clock() {
	var thetime=new Date();
	//var mins=new Date();
	//var secn=new Date();
	var nhours=thetime.getHours();
	var nmins=thetime.getMinutes();
	var nsecn=thetime.getSeconds();
	var nday=thetime.getDay();
	var nmonth=thetime.getMonth();
	var ntoday=thetime.getDate();
	var nyear=thetime.getYear();
	var AorP=" ";
	if (nhours>=12)    AorP="PM";
	else    AorP="AM";
	if (nhours>=13)    nhours-=12;
	if (nhours==0)   nhours=12;
	if (nsecn<10) nsecn="0"+nsecn;
	if (nmins<10) nmins="0"+nmins;
	// Selector de idioma
	if (lang == 'es') {
		if (nday==0)  nday="Domingo";
		if (nday==1)  nday="Lunes";
		if (nday==2)  nday="Martes";
		if (nday==3)  nday="Miercoles";
		if (nday==4)  nday="Jueves";
		if (nday==5)  nday="Viernes";
		if (nday==6)  nday="Sabado";
	}

	if (lang == 'en') {
		if (nday==0)  nday="Sunday";
		if (nday==1)  nday="Monday";
		if (nday==2)  nday="Tuesday";
		if (nday==3)  nday="Wednesday";
		if (nday==4)  nday="Thursday";
		if (nday==5)  nday="Friday";
		if (nday==6)  nday="Saturday";	
		}
		
	nmonth+=1;
	if (nyear<=99)  nyear= "19"+nyear;
	if ((nyear>99) && (nyear<2000)) nyear+=1900;
	//document.getElementById("reloj").innerHTML = nhours+": "+nmins+": "+nsecn+" "+AorP+" "+nday+", "+nmonth+"/"+ntoday+"/"+nyear;
	//document.getElementById(divId).innerHTML = nhours+": "+nmins+": "+nsecn+" "+AorP+" "+nday+", "+ntoday+"/"+nmonth+"/"+nyear;
	document.getElementById(divId).innerHTML = ntoday+"/"+nmonth+"/"+nyear +", "+ nhours+":"+nmins+":"+nsecn+" "+AorP+", "+nday;
	setTimeout("dinamic_clock()",1000);
	} 


// **************************************************************************	
// * toMySql																*
// * Convierte la fecha dada de formato "dd/mm/aaaa" a MySql ("yyyy-mm-dd") *
// * la carga en el 'nombre_campo_destino'									*
// **************************************************************************
function toMySql(nombre_campo,nombre_campo_destino) 
	{
	var elem = document.getElementById(nombre_campo);
	fecha = elem.value;
	//alert(fecha);
	fecha_mysql = fecha.split("/");
	document.getElementById(nombre_campo_destino).value = fecha_mysql[2]+"-"+fecha_mysql[1]+"-"+fecha_mysql[0];
	}
	
// Lo mismo que la anterir pero devuelve el valor para manejarlo dentro de un script	
function toMySqlDate(fecha) 
	{
	fecha_mysql = fecha.split("/");
	var fecha_out = fecha_mysql[2]+"-"+fecha_mysql[1]+"-"+fecha_mysql[0];
	return fecha_out;
	}
	
	
// **************************************************************************	
// * toLayoutDate															*
// **************************************************************************
function toLayoutDate(nombre_campo,nombre_campo_destino) 
	{
	var elem = document.getElementById(nombre_campo);
	fecha = elem.value;
	//alert(fecha);
	fecha_mysql = fecha.split("-");
	document.getElementById(nombre_campo_destino).value = fecha_mysql[0]+"/"+fecha_mysql[1]+"/"+fecha_mysql[2];
	}
	
	
// **************************************************************	
// * CompletarFechaActual										*
// * Rellena el campo pasado como parámetro con la fecha actual *
// **************************************************************
function completarFechaActual(field)
		{
		var elem = document.getElementById(field);
		elem.value = global_fecha_actual;
		elem.focus();
		}
// Vacia el campo pasado como parámetro		
function vaciarCampo(field)
		{
		var elem = document.getElementById(field);
		elem.value = '';
		}		

// **********************************************
// * confirmarBaja								*
// * Función especifica para confirmar bajas	*
// **********************************************
function confirmarBaja(theLink)
	{
	if ( confirm("¿Esta seguro que desea dar de baja el registro?") ) { document.location = theLink; }
	}

// ******************************************************
// * confirmarReactivar									*
// * Función especifica para confirmar reactivaciones	*
// ******************************************************
function confirmarReactivar(theLink)
	{
	if ( confirm("¿Esta seguro que desea reactivar el registro?") ) { document.location = theLink; }
	}
	
// **********************************************************************
// * confirmLink														*
// * Función especifica para confirmar links con mensaje personalizable	*
// **********************************************************************
function confirmLink(theLink,msj)	
	{
	if ( confirm(msj) ) { document.location = theLink; } 
	}



function confirmarFunction(fn,params,accion) {	
	if ( confirm("¿Confirma que desea "+accion+"?") ) { 
		if (params.length>0) {
			if (params.length==1) fn(params[0]);
			if (params.length==2) fn(params[0],params[1]);
			if (params.length==3) fn(params[0],params[1],params[2]);
			if (params.length==4) fn(params[0],params[1],params[2],params[3]);
			if (params.length==5) fn(params[0],params[1],params[2],params[3],params[4]);
		} else {
			fn();
		}
	}
	
}

function confirmarAccion(theLink,accion) {	
	if ( confirm("¿Confirma que desea "+accion+"?") ) { 
		window.document.location = theLink;
	}
	
}

function confirmarAccionSubmit(formName,theLink,accion) {
	if ( confirm("¿Confirma que desea "+accion+"?") ) { 
	document.getElementById(formName).action = theLink;
	document.getElementById(formName).submit();
	}
}


//***********************
//* checkNavigator		*
//* Detecta navegador 	*
//***********************
function checkNavigator(string)
	{
	var detect = navigator.userAgent.toLowerCase();
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
	}


// Formatea una serie de numeros al formato de fecha dd/mm/aaaa
function formatDate(elem)
	{
	var value = elem.value;
	if (value != '') {
		var tmp_value = "";
		value = value.replace(/[\/]/g,"");
		
		for (i=0; i<8; i++)
			{
			sChar = value.charAt(i);
			tmp_value = tmp_value + sChar;
			if (i == 1) { tmp_value = tmp_value + "/"; }
			if (i == 3) { tmp_value = tmp_value + "/"; }
			}
			elem.value = tmp_value;
		}else {
		elem.value = '';	
		}
	}

// Función alias de jquery $ para evitar conflicto de nombres al usar la original
function $$() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

// Arma los parametros para los ajax en base a un array de datos
function setParams(data,first) {
	
	if (first == null) first = false;
	var params = "";
	
	if (data != null) {		
		for (i in data) 
			{
			
			// Objeto
			if (typeof(data[i]) == "object" ) {
				for (x in data[i])
				 	{
					if (typeof(data[i][x]) != "function" ) 
						{
						if (first) { params = params + "?"; first = false; }
						else { params = params + "&"; }
						params = params +i+"["+x+"]="+data[i][x];
						}
					}
				}
			// Item común
			else {
				if (typeof(data[i]) != "function" ) {
					if (first) { params = params + "?"; first = false; }
					else { params = params + "&"; }
					 params = params + i + "=" + data[i];
					}
				}
			}
		
		return params;
		}
	else{
		return false;
		}
}

/*
var data = { 
id:8,
texto: "porota"
};
*/
// /*DEBUG*/ alert(params(data,true));


// Obtiene todos los elementos de un formulario en base a su id
function getElementsByGroup(group) {

	var form = document.getElementById('abm_form');
	var elements = new Array();
	
	if (typeof(group)!= "undefined" && group != null) 
		{
		for (i=0; i <= form.elements.length-1; i++)
			{
			nombre_campo = form.elements[i].id;			
			if (nombre_campo.indexOf(group) != -1 ) { 
				elements[nombre_campo] = form.elements[i];
				}
			}		
		return elements;
		}
	else
		{
		return false;
		}
}

function completeForm(form_fields) {
	
	// Recorro el array de campos y busco elementos en el DOM con el mismo id
	for (x in form_fields)
		{
		if( typeof(form_fields[x]) != "function" && typeof(form_fields[x]) != "undefined" )
			{ 
		
			nombre_campo = x;
			//alert(x+" -> "+form_fields[x])
			// *** PARCHE *** para problema de arrays (Si no es un array lo transforma para que pueda ser tratado con la misma funcion)
			if (nombre_campo.indexOf('[0]') != -1 && form_fields[nombre_campo] == "undefined" && form_fields[nombre_campo.substr(0,nombre_campo.indexOf('['))] != "undefined")
				{
				form_fields[nombre_campo] = form_fields[nombre_campo.substr(0,nombre_campo.indexOf('['))];
				}
			
			if (nombre_campo.indexOf('[') != -1 && form_fields[nombre_campo] == "undefined")
				{
				fin = nombre_campo.indexOf('[');
				tmp = nombre_campo.substr(0,fin);
				form_fields[nombre_campo] = form_fields[nombre_campo];
				}		
			
			// Completa datos según el tipo de campo
			if ( nombre_campo != '' && form_fields[nombre_campo] != '' && form_fields[nombre_campo] != 'undefined' && typeof(nombre_campo) != 'undefined') 
				{
				elem = document.getElementById(nombre_campo);
				
				// Distingo entre tipos de datos
				if (typeof(elem) != "undefined") 
					{

					// Checkbox 
					if (elem.type == 'checkbox') 
						{  
						if ( form_fields[nombre_campo] != 0 && form_fields[nombre_campo] != '' && typeof(form_fields[nombre_campo]) != 'undefined' ) { elem.checked = true; }
						} // Fin tipo checkbox
						
					
					// Selects
					if (elem.type == 'select-one' )
							{	
														
								for (j=0;j < elem.options.length ; j++)
									{
									if (elem.options[j].value == form_fields[nombre_campo] )
										{										
										elem.options[j].selected = true;
										}
									}								
								
								
								// Llama a la funcion q rellena los select dependientes	
								if ( typeof(mostrar_provincias) != 'undefined' && typeof(mostrar_localidades) != 'undefined') 
									{
									switch (elem.name) 
										{
										case 'id_pais':
											mostrar_provincias(form_fields[elem.name],'id_provincia');
											break;
										case 'id_pais_crp':
											mostrar_provincias(form_fields[elem.name],'id_provincia_crp');
											break;
										case 'id_provincia':
											mostrar_localidades(form_fields[elem.name],'id_localidad');
											break;
										case 'id_provincia_crp':
											mostrar_localidades(form_fields[elem.name],'id_localidad_crp');
											break;
										}//switch
									}//if
									
							}
					
					
					// Radiobuttons
					if (elem.type == 'radio')
						{
						elem_rb = document.getElementsByName(nombre_campo);
			
						if (elem_rb.length) 
							{
							for (j=0;j< elem_rb.length ; j++)
								{ 
								if (elem_rb[j].value == form_fields[nombre_campo]) { elem_rb[j].checked = true; }
								} 
							}
						}
					
					
					// Textboxes
					if (elem.type == 'textarea' || elem.type == 'text' || elem.type == 'hidden' ) { elem.value = form_fields[nombre_campo]; }
					}
				}
			}
		}// fir for

} // Fin completeForm()

function addslashes(str) 
{
	if (typeof(str)=="string" && str!="")
	{
		str=str.replace(/\'/g,'\\\'');
		str=str.replace(/\"/g,'\\"');
		str=str.replace(/\\/g,'\\\\');
		str=str.replace(/\0/g,'\\0');
		return str;
	}
}

function stripslashes(str) 	
{
	if (typeof(str)=="string" && str!="")
	{
		str=str.replace(/\\'/g,'\'');
		str=str.replace(/\\"/g,'"');
		str=str.replace(/\\\\/g,'\\');
		str=str.replace(/\\0/g,'\0');
		return str;
	}
}


// Mostrar u ocultar el formulario de búsqueda
function showHideSearchBox(){ 
	var searchBox = document.getElementById('searchBox');
	if (searchBox.style.display != "none") { searchBox.style.display = "none"; } else { searchBox.style.display = "";  }
}

/**
	Muestra u oculta una capa
**/
function showHideObj(id,ac)
	{
	var obj = document.getElementById(id);
	if(ac == "show")
		{
		obj.style.display = "";
		}
	else if(ac == "hidden")
		{
		obj.style.display = "none";
		}
	}
	
/*
	Funcion especifica que muestra y oculta el panel de busqueda y cambia el icono de la lupa
*/
function searchPanel(tabNumber){
	var searchDivId = 'searchDiv'+tabNumber;
	searchDiv = document.getElementById(searchDivId);
	if(searchDiv.style.display == "none")
		{
		document.getElementById('ico_lupa_'+tabNumber).src = "images/ico_lupa_sel.gif";
		showHideObj(searchDivId,'show');
		}
	else
		{
		document.getElementById('ico_lupa_'+tabNumber).src = "images/ico_lupa.gif";
		showHideObj(searchDivId,'hidden');
		}
}


/*
	Copia el formulario de las listas en el documento principal main
*/
function dynSearch(searchDivNumber, cloneDivName){
	//Extraemos el codigo del formulario del frame
/*	var form = '';
	form += '<table>';
	form += document.getElementById('searchBox').innerHTML;
	form += '</table>';
	//Escribimos el codigo
	parent.document.getElementById('searchDiv'+searchDivNumber).innerHTML = form;
*/	
	searchFrom = document.getElementById(cloneDivName).cloneNode(true);

	parent.document.getElementById('searchDiv'+searchDivNumber).appendChild(searchFrom);
	parent.document.getElementById(cloneDivName).style.display = '';
	
	/* PARCHE PARA IE */
	selects = document.getElementsByTagName('select');
	for(i=0; i<selects.length; i++) {
		parent.document.getElementById(selects[i].id).selectedIndex = selects[i].selectedIndex;
	}
}



/*
*	Parsea el string con el siguiente formato 
*
*	Recibe:
*	string 	= 	"key1=valor1;key2=valor2;key3=valor3"
*
*	Devuelve:
*	array	= 	fields['key1'] = "valor1" 
*				fields['key2'] = "valor2" 
*				fields['key3'] = "valor3" 
*
*/
function splitDataIntoArray(data){ 
	datos_array = data.split(separador);
	var campos_array 	= new Array(datos_array.length);
	for(x=0; x<datos_array.length; x++) 
		{
		if ( datos_array[x].indexOf("=") != -1 ) 
			{							
			tmp = datos_array[x].split("=");
			campos_array[tmp[0]] = tmp[1];	
			}
		} 	
	return campos_array;
}

function addEvent(elmId, evType, fn, useCapture) {
	var elm = document.getElementById(elmId);
	
	if ( elm != null ) {
	
		if (elm.addEventListener) {
			elm.addEventListener(evType, fn, useCapture);
			return true;
		}
		else if (elm.attachEvent) {
			var r = elm.attachEvent('on' + evType, fn);
			return r;
		}
		else {
			elm['on' + evType] = fn;
		}
	}
}

function removeEvent(elmId, evType, fn, useCapture) {
	var elm = document.getElementById(elmId);
	
	if ( elm != null ) {
		if (elm.removeEventListener) 
			{
			elm.removeEventListener(evType, fn, useCapture);
			return true;
			}
	}
}


function getValorCampo(campo) {
			
	var valor = "";
	
	if (campo != null) {
	
	// CheckBoxes
		if (campo.type=='checkbox')
			{
			if (campo.checked==true) 
				{
				if (campo.value!="") 
					{
					valor=campo.value;					
					}
				else
					{
					valor=1;
					}
				}
			}
	// Selects
		if (campo.type=='select-one')
			{
			for (j=0;j < campo.options.length ; j++)
				{
				if (campo.options[j].selected==true) valor = campo.options[j].value;		
				}		
			}					
	// Radiobuttons
		if (campo.type == 'radio')
			{
			valor = getValorRadioBtn(campo.name);
			}
	// Demas elementos...
		if (campo.type == 'textarea' || campo.type == 'text' || campo.type == 'hidden' ) 
			{
			if (campo.value && campo.value!="") 
				{
				// Si es un campo con nombre "fecha" y el valor coincide con un formato de fecha..
				// Formatos posibles: "21/10/2007" ; "10-21-2007" ; "10.21.2007"
				var dateformat = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
				if  ( campo.name.indexOf("fecha")!=-1 && dateformat.test(campo.value) )
					{
					// Cambia el formato de "21/10/2007" a "2007-10-21"
					var fecha = campo.value;
					valor = fecha.substr(6,4)+"-"+fecha.substr(3,2)+"-"+fecha.substr(0,2);
					}
				else
					{
					valor = campo.value;
					}
				}
			}
	
	}
	return valor;
}


function getValorRadioBtn(nombre_campo) {
	var rbtn = document.getElementsByName(nombre_campo);
	var valor = "";
	for (i=0;i<rbtn.length;i++)
		{
		if (rbtn[i].checked==true) valor = rbtn[i].value;
		}
	
	return valor;
}



function getOptionTags(campo_select) {
	var tags = [];
	tags.value = [];
	tags.text = [];
	
	if (campo_select.type=='select-one')
		{
		for (j=0;j<campo_select.options.length;j++)
			{
			if (campo_select.options[j].selected==true) 
				{
				tags.value.push(campo_select.options[j].value);		
				tags.text.push(campo_select.options[j].text);	
				}
			}	
		return tags;	
		}		
}


function poner_en_mayusculas(elemento)
	{	
	if (elemento.value) 
		{
		elemento.value = elemento.value.toUpperCase();
		}
	}



function getDiasMes(mes, anio){ 
	//regresa la cantidad de días del mes del año que pasamos como parametro 
	switch (mes){ 
	case 0: return 31; break; 
	case 1: 
	if (anio % 4 == 0){ 
	if (anio % 400 == 0){ 
	return 29; 
	} 
	else { 
	if (anio % 100 == 0){ 
	return 28; 
	} 
	else { 
	return 29; 
	} 
	} 
	} 
	else { 
	return 28; 
	}; 
	break; 
	case 2: return 31; break; 
	case 3: return 30; break; 
	case 4: return 31; break; 
	case 5: return 30; break; 
	case 6: return 31; break; 
	case 7: return 31; break; 
	case 8: return 30; break; 
	case 9: return 31; break; 
	case 10: return 30; break; 
	case 11: return 31; break; 
	
	} 
} 

// Devuelve 1 si dateA > dateB; -1 si dateA < dateB y 0 si las dos fechas son iguales
function compareDate(dateA, dateB) 
	{ 
	   timeDifference = dateA - dateB; 
	   if (timeDifference > 0) 
		  return 1; 
	   else if (timeDifference < 0) 
		  return -1; 
	   else 
		  return 0; 
	}

// Compara fechas pasadas en formato 
// Format 1 => dd/mm/aaaa
// Format 2 => aaaa-mm-dd
// Devuelve 1 si dateA > dateB; -1 si dateA < dateB y 0 si las dos fechas son iguales
function compareDateStrings(dateA,dateB,format) {

	if (typeof('format') == 'undefined') { format=1; }
	
	if (dateA != '' && dateB != '') {
		var ar = [];
		
		// Format 1 => dd/mm/aaaa
		if (format == 1) {
			// Parsea las fechas
			ar = dateA.split('/');
			dateA = new Date(ar[2],(ar[1])-1,ar[0]);
			ar = dateB.split('/');
			dateB = new Date(ar[2],(ar[1])-1,ar[0]);
		}
		
		// Format 2 => aaaa-mm-dd
		if (format == 2 ) {
			// Parsea las fechas
			ar = dateA.split('-');
			dateA = new Date(ar[0],(ar[1])-1,ar[0]);
			ar = dateB.split('-');
			dateB = new Date(ar[0],(ar[1])-1,ar[0]);
		}
		
		timeDifference = dateA - dateB; 
	   if (timeDifference > 0) 
		  return 1; 
	   else if (timeDifference < 0) 
		  return -1; 
	   else 
		  return 0; 
		
	}else {
	return false;	
	}

}

function completar_checkboxes(form_name) 
	{
	form = document.getElementById(form_name);
	
	for (i=0; i <= form.elements.length-1 ; i++) {
		nombre_campo = form.elements[i].name;
		if (nombre_campo!='') {
			elem = document.getElementById(nombre_campo);
			if (elem != null) {
				// Checkbox		
				if (elem.type == 'checkbox') 
					{ 	
					if (elem.checked == false) { elem.checked = true; elem.value=0; }
					} // Fin tipo checkbox
				}
			}
		}
	}

/*
*	Invierte el valor style.display de 1 elemento
*
*	elem 			string		nombre del elemento 
*/
function switchDisplay(elem)
	{	
		if (document.getElementById(elem))
			{				
				document.getElementById(elem).style.display = (document.getElementById(elem).style.display=="none") ? "" : "none";
			}
	}


/*
*	Intercambia el valor style.display de 2 o mas elementos
*	Se activa el elemento pasado como elem_mostrar
*
*	elems 			array		Array de nombres de elementos 
*	elem_mostrar	int			indice del elemento a activar
*/
function switch_elements_display(elems,elem_mostrar,nombre_campo)
	{	
		var valor = "";		
		for (x in elems)
			{				
				valor = (x==elem_mostrar) ? "" : "none";
				if ( document.getElementById(elems[x]) && (!nombre_campo || (nombre_campo && x.indexOf(nombre_campo)!=-1)) ) document.getElementById(elems[x]).style.display = valor; 
			}
	}


/*
*	Intercambia el valor style.display de 2 o mas elementos
*	Se activa el elemento pasado como elem_mostrar
*
*	elems 			array		Array de nombres de elementos 
*	elem_mostrar	int			indice del elemento a activar
*/
function activar_fondo(elems,elem_mostrar,nombre_campo)
	{	
		var valor = "";
		for (x in elems)
			{
				valor = (x==elem_mostrar) ? "tdCeldaActiva" : "tdCeldaInActiva";
				if ( document.getElementById(elems[x]) && (!nombre_campo || (nombre_campo && x.indexOf(nombre_campo)!=-1)) ) document.getElementById(elems[x]).className = valor;
			}
	}

// Agrega una opcion a un select-one
function addOption(objSelec,value,text) {
		
	var option=document.createElement('option');
	option.text=text;
	option.value=value;

	try
		{
		objSelec.add(option,null); // standards compliant
		return true;
		}
	catch(ex)
		{
		objSelec.add(option); // IE only
		return true;
		}

		
	return false;
}

// Inserción de una opción en un select-one crossBrowser
// Resuleve el problema
function insertOption(idSelect,text,value,before) {
	
 var option=document.createElement('option');
 option.text	= text;
 option.value  	= value;
 if (before == '') { before = null; } // Solo válido para Exploradores estándar
 var x=document.getElementById(idSelect);
  try {
    x.add(option,before); // Standards compliant
    }
  catch(ex) {
    x.add(option); // IE only
    }
}


function redondeo2decimales(numero)
{
	var original=parseFloat(numero);
	var result=Math.round(original*100)/100 ;
	return result;
}

/*
*	Normaliza los campos Fecha 
*	(prepara para guardar en la base)
*/
function normalizarCamposFecha()
	{	
	var elems = getElementsByGroup("fecha");
	var valor = "";
	var elemName = "";
	for (x in elems) 
		{			
		if (elems[x].name.indexOf("_temp")!=-1)
			{
			valor = getValorCampo(elems[x]);
			if (valor!="undefined") 
				{ 
				elemName = elems[x].name.replace("_temp","");
				if (document.getElementById(elemName))  { document.getElementById(elemName).value = valor; }
				
				}
			}
		}
	return true;
	}

/*
*	Convierte un string de Fecha a un Date Object(js) 
*  	Param:  fecha 	(string)	fecha con formato dd/mm/aaaa 
*	Return: date() Object
*/
function parsearFecha(fecha) 
{
	// si esta cargado el validador, lo utilizo para validar la fecha
	if ( (formValidator && formValidator.isDate(fecha)) || !formValidator)
		{
		var temp = [];
		temp = fecha.split("/");
		//  for (x in temp) alert("parseado: "+temp[x])
		if (temp[2] && temp[1] && temp[0]) 
			{
			fechaObj = new Date();
			fechaObj.setFullYear(parseFloat(temp[2]),parseFloat(temp[1])-1,parseFloat(temp[0]));
			if (fechaObj && !isNaN(fechaObj)) return fechaObj;
			}
		}
	return false;
}


// Comprueba si un valor es null o vacio
function isNull(value) {
	var isNull = false;
	if( value == null ) {  isNull = true; }
	if( value == '') { isNull = true; }
	return isNull;

}


function inArray(array,value) {
	
  for (x in array) {
        if (array[x] == value) {
            return true;
        }
		
    }
    return false;

}

function textCounter(field, countDiv, maxlimit) {
	var field = document.getElementById(field);
	var countDiv = document.getElementById(countDiv);
	
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
	} else { 
		countfield.innerHTML = maxlimit - field.value.length;
	}

}

function toPHPcalendar(fecha) {
	var fechaCalendar = '';
	var temp = []; temp = fecha.split("-");
	if (temp[2] && temp[1] && temp[0]) { 
		fechaCalendar = temp[2]+'/'+temp[1]+'/'+temp[0];
	}
	return fechaCalendar;
}

// Recibe fechas en formato sql aaaa-mm-dd
function diasEntreFechas(fecha1,fecha2) {
	// Parsea las fechas
	// Fecha1
	var temp = []; temp = fecha1.split("-");
	if (temp[2] && temp[1] && temp[0]) { var fecha1 = new Date(parseInt(temp[0],10),(parseInt(temp[1],10)-1),parseInt(temp[2],10)); }

	// Fecha2
	var temp = []; temp = fecha2.split("-");
	if (temp[2] && temp[1] && temp[0]) { var fecha2 = new Date(parseInt(temp[0],10),(parseInt(temp[1],10)-1),parseInt(temp[2],10)); }

	var fecha1_sec = fecha1.getTime();
	var fecha2_sec = fecha2.getTime();
	var tiempo = parseInt(fecha2_sec,10) - parseInt(fecha1_sec,10);
	dias = Math.floor(tiempo/(1000 * 60 * 60 * 24));
	return dias;
}


// Event types
// click
function simulateEvent(obj,eventType) {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent(eventType, true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
  obj.dispatchEvent(evt);
}

// Transforma un string común a un formato válido para códigos del sistema 
// Filtra los espacios de iz y de y luego reemplaza los intemedios por _ y finalmente pasa todo a mayusculas
function stringToCode(string) {
	string = string.replace(/(^\s*)|(\s*$)/g,"");
	string = string.replace(/[ \t\r\n]/g,'_');
	string = string.replace(/[^A-Za-z0-9_\-]/g,'');
	string = string.toUpperCase();
	return string;
}



// Función que funciona como un proxy comunicando el iframe contenido en tpvbooking con el sitio anfitrion (hotel o portal) que lo contenga
// Crea un iframe dinamicamente y le envia parametros por url.
// El contenido del iframe está alojado en el servidor anfritrion por lo cual tiene comunicación habilitada con el contenido principal de la página saltándose así la restricción de seguridad crossDomain de javascript
function proxyCompletion(newHeight,iframeName,baseDomain) {

    // The name of the frame
    var id = "crossdomainProxy";

    // Look for existing frame with name "proxyframe"
    var proxy = frames[id];

    // Set URL and querystring
    var url = baseDomain+"/tpvbooking/utils/crossDomainProxy.html?newHeight="+newHeight+"&iframeName="+iframeName;


    // If the proxy iframe has already been created
    if (proxy){
		
        // Redirect to the new URL
        proxy.location.href = url;

    } else {

        // Create the proxy iframe element.
        var iframe = document.createElement("iframe");
        iframe.id = id;
        iframe.name = id;
        iframe.src = url;
        iframe.style.display = "none";
        document.body.appendChild(iframe);

    }

}


