//===============================================================//
//					Funciones con arreglos
//===============================================================//
//===============================================================//
//BUSCAR EN UN ARREGLO [A PARTIR DE UNA POSICION] Y DEVOLVER INDICE
//===============================================================//
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
//===============================================================//

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
//===============================================================//
//BUSCAR EN UN ARREGLO [A PARTIR DE UNA POSICION] Y DEVOLVER INDICE (EMPEZANDO POR EL ULTIMO ELEMENTO)
//===============================================================//
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
//===============================================================//

if (!Array.prototype.lastIndexOf) {
  Array.prototype.lastIndexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]);
    if (isNaN(from)) {
      from = len - 1;
    }else{
		from = (from < 0)
				? Math.ceil(from)
				: Math.floor(from);
		if (from < 0) {
			from += len;
		}else if (from >= len) {
			from = len - 1;
		}
    }

    for (; from > -1; from--) {
		if (from in this && this[from] === elt) {
			return from;
		}
    }
    return -1;
  };
}

//=======================================================
// 		  		Funciones de fechas
//=======================================================

//adicionar dias a una fecha
Date.prototype.addDays = function(value) {
	return this.addMilliseconds(value*86400000);
}

//adcionando milisegundos a un objeto fecha
Date.prototype.addMilliseconds = function(value) {
	this.setMilliseconds(this.getMilliseconds()+value);
	return this;
}

//se obtiene la fecha en formato 'dmY' a partir de un objeto fecha
Date.prototype.date2String = function() {
	dia = formatNumber(this.getDate());			//dia del mes
	mes = formatNumber(this.getMonth() + 1);	//el mes lo devuelve en el rango de 0-11, es por eso que sumamos 1 al resultado
	ano = this.getFullYear();					//ano completo (ej. 2010)
	
	return dia + "-" + mes + "-" + ano;
}

//adicionar '0' al inicio de los numeros del '0' al '9'
function formatNumber(num) {
	if (num < 10) {
		return "0" + num;
	}else{
		return num;
	} 
}

//adicionamos 'n' dias a una fecha string de formato 'dmY'
function adicionaDias (fecha, dias) {
	date_fecha = getRealDate(fecha);			//convertimos nuestra fecha string de formato 'dmY' a un objeto date
	date_fecha.addDays(dias);					//le adicionamos los dias
	nuevaFecha = date_fecha.date2String();		//lo convertimos de vuelta al string de formato 'dmY'
	
	return nuevaFecha;
}

//Se obtiene el objeto date de una fecha en string con el formato dmY, (ej 25-11-2009)
function getRealDate (strfecha) {
	parsedFecha = strfecha.split('-');
	fecha = new Date(Number(parsedFecha[2]), Number(parsedFecha[1]-1), Number(parsedFecha[0]));
	return fecha;
}

//Resto Fecha2 a Fecha1, (ej return Fecha1 - Fecha2)
function getDaysBetween(date1, date2){
  date1 = date1.split("-");
  date2 = date2.split("-");
  var sDate = new Date(date1[1]+"/"+date1[0]+"/"+date1[2]);
  var eDate = new Date(date2[1]+"/"+date2[0]+"/"+date2[2]);
  var daysApart = Math.abs(Math.round((sDate-eDate)/86400000));
  
  return daysApart;
}

/*function getDaysBetween (fecha1, fecha2) {
	date1 = getRealDate (fecha1);
	date2 = getRealDate (fecha2);
	daysBetween = Math.floor((date1 - date2)/86400/1000);
	return daysBetween;
}*/
//dias = getDaysBetween ("05-12-2009", "01-12-2009");

//retorna 'true' si fecha1 > fecha2, de lo contrario 'false'
function getLeftIsGreaTer (fecha1, fecha2, igual) {
	date1 = getRealDate (fecha1);
	date2 = getRealDate (fecha2);
	
	if (igual) {
		return date1 >= date2;
	}else{
		return date1 > date2;
	}
}


//=======================================================
// 		  Funciones para Ajax
//=======================================================
var mySelect = 'paises';
var imgLoad = '';

function Listado(Objeto, _sub, seleccion, imgCargar) {
	if (imgCargar != '') {
		$("#"+imgCargar)[0].src = '../images/cargar.gif';
		imgLoad = imgCargar;
	}
	mySelect = Objeto;
	_url = "getListado.php";

	$.ajax({
		type: 'GET',
		url: _url,
		data: {alcance: Objeto, sub: escape(_sub), sel: escape(seleccion), _SELECCIONE: _SELECCIONE},
		async: false,
		success: procesaRespuestaCallback
	});
}

function procesaRespuestaCallback( data, status ){
	if (imgLoad != '') {
		$("#"+imgLoad)[0].src = '../images/blank.gif';
	}
	objCombo = document.getElementById(mySelect);
	if (objCombo == null) return;
	delAllOptions(objCombo);
	cadena = unescape(data);
	if (cadena.substring(0, 2)=="\r\n") cadena = cadena.substring(2, cadena.length-1);
	temp = cadena.split(',');

	for (i = 0; i < temp.length; i = i + 4) {
		appendOptionLast(objCombo, temp[i], temp[i+1], temp[i+2], temp[i+3]);
	}
}

/*function getPais(id) {
	$.ajax({
		type: 'post',
		url: "getPais.php",
		data: {id:id},
		success: function (pais) {
			return pais;
		}
	});
}*/

//=======================================================
// 					Funciones de combos		
//=======================================================
function appendOptionLast(objSelect, texto, valor, seleccionado, grupo1) {
	if (grupo1== null) return;
	newOption = document.createElement('option');	//Crear un <OPTION>
	grupo = grupo1.replace(/^\s*|\s*$/g,"");

	if (grupo.indexOf("&&&") == -1) {
		try {
			newOptgroup = document.getElementById(grupo);
			tmp = newOptgroup.label;
		} catch(ex) {
			newOptgroup = document.createElement('optgroup');	//Crear un <OPTGROUP>
			newOptgroup.label = grupo;
			newOptgroup.id = grupo;
			objSelect.appendChild(newOptgroup);
		}
		newOptgroup.appendChild(newOption);
	}else{
		try {
			objSelect.add(newOption, null); // No trabaja en IE
		} catch(ex) {
			objSelect.add(newOption); 		// Solo IE
		}
	}

	//if (texto=='eleccionado...') texto='Seleccionado...';
	newOption.text = texto;										//Ponerle el TEXT
	newOption.value = valor;									//Ponerle el VALUE
	newOption.selected = (seleccionado=="1")?(true):(false);	//Ponerle el SELECTED
}

//Las listas listTextos y listValores deben usar como separador la coma
function addOptions(objCombo, listTextos, listValores) {
	arrTextos = listTextos.split(",");
	arrValores = listValores.split(",");
	
	for(i=0; i<arrTextos.length; i++) {
		newOption = new Option(arrTextos[i], arrValores[i]);
		objCombo.options[objCombo.options.length] = newOption;
	}
}

function addOption(objCombo, text, value) {
	newOption = new Option(text, value);
	objCombo.options[objCombo.options.length] = newOption;
}

function delOption(objCombo) {
	if (objCombo.options.length > 0) {
		objCombo.options[objCombo.options.selectedIndex] = null;
	}
}

function delAllOptions(objCombo) {
	if (objCombo == null) return;
	//objCombo.empty();
	if (objCombo.options.length > 0) {
		objCombo.options.length = 0;
	}
	opt = objCombo.getElementsByTagName('optgroup');
	if (opt.length>0) {for (i=opt.length-1; i>=0; i--) objCombo.removeChild(opt[i])};
}

function showFlags (pais) {
	imagen = 'images/flags/'+pais+'.gif';
	document.reserva1.flag.src = imagen;			//<img src="pepe.gif" onerror="this.onerror=null;this.src='blanco.gif';" >
}

function Submit(form) {
	result = false;
	if (checkea_formulario(form)) {
		form.submit();
		result = true;
	}
	
	return result;
}

function botMonedasEfecto(id, Xpositio, area, pressed){
	//Esta Funcion mueve a la Xpositio la imagen de fondo
	//id -- es el ID del objeto al cual queremos cambiarle la posicion de la imagen de fondo
	//Xpositio -- numero negativo de pixeles que se desea desplazar la la imagen de fondo
	boton = $('#'+id);
	if (selMoneda != id) {
		if (boton.data("status") != "pressed") boton.css({"background-position": Xpositio+"px"});
		if (pressed) {
			boton.data("status", "pressed");

			//Restauramos el boton anteriormente presionado al estado normal
			botlastPressed = $('#'+selMoneda);
			botlastPressed.data("status", "normal");
			botlastPressed.css({"background-position": "0px"});
			botlastPressed.css({"cursor": "default"});
		}
		
		if (area=='in') {
			boton.css({"cursor": "pointer"});
		}else{
			boton.css({"cursor": "default"});
		}
	}else{
		boton.css({"cursor": "default"});
	}
}

function PosicionFondo(id, Xpositio, area){
	//Esta Funcion mueve a la Xpositio la imagen de fondo
	//id -- es el ID del objeto al cual queremos cambiarle la posicion de la imagen de fondo
	//Xpositio -- numero negativo de pixeles que se desea desplazar la la imagen de fondo
	boton = $('#'+id);
	boton.css({"background-position": Xpositio+"px"});
	if (area=='in') {
		boton.css({"cursor": "pointer"});
	}else{
		boton.css({"cursor": "default"});
	}
}

function chkRadio(B_and_B) {
	if (B_and_B) {
		document.getElementById('Desayuno incluido').checked = B_and_B;
	}
}

function buscarHostal() {
	paises = document.frmBuscar.paises;
	ciudades = document.frmBuscar.ciudades;
	
	//if (((paises.value != "") && (paises.value != "Seleccione...")) && ((ciudades.value != "") && (ciudades.value != "Seleccione..."))) {
	if ((paises.selectedIndex > 0) && (ciudades.selectedIndex > 0)) {
		//alert("?detalles=Hospedajes en " + ciudades.value+", "+paises.options[paises.selectedIndex].text);
		document.frmBuscar.action += "?detalles=Hospedajes en " + UTF8.encode(ciudades.value) + ", " + UTF8.encode(paises.options[paises.selectedIndex].text);
		document.frmBuscar.submit();
	}
}

function moneda_winpop (enlace){
	pageopen;
	pageopen = "faq_popup.php";
	if(enlace){pageopen = "faq_popup.php"+enlace;}
	window.open(pageopen, "Moneda", "width=540,height=500,scrollbars=yes");
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}










