// FUNCIONES CALENDARIO --------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------

function getDaysInMonth(month,year)
{
	var days;
	if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12) days=31;
		else if(month==4 || month==6 || month==9 || month==11) days=30;
			else if(month==2)
			{
				if (isLeapYear(year)) days=29;
					else days=28;
			}
	return (days);
}

function isLeapYear (Year)
{
	if(((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0))
	{
		return (true);
	}else
		{
			return (false);
		}
}

function DisplayMonthDays(f_ini_m, f_ini_a, where)
{
	var days;
	days = getDaysInMonth(f_ini_m.selectedIndex+1, f_ini_a.value);
	frms=eval("document.buscar_hoteles."+where);

	//Guardamos el dia seleccionado para seleccionarlo si se puede al recargar el select
	old_selected = frms.selectedIndex;

	//Miramos que no sea negativo
	if(old_selected < 0) old_selected = 0;

	//Construimos la cadena de options a parsear en el combo
	var option = "";
	var n;
	frms.length=0;
	for(n=1;n<=days;n++)
	{
		var no = new Option();
		if (n < 10) n = "0" + n;
		no.value = n;
		no.text = n;
		frms[n-1] = no;
	}

	//Seleccionamos si podemos el indice anterior.
	largo = frms.length;
	if(largo > old_selected)
	{
		//Se puede seleccionar
		frms[old_selected].selected=true;
	}else
	{
		//seleccionamos el ultimo ya que no podemos seleccionar el anterior por ser mas grande que el mayor actual.
		frms[largo-1].selected=true;
	}

}

// FUNCIONES FILTRO XML --------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------

// global flag
var isIE = false;

// global request and XML document objects
var req;

// retrieve XML document (reusable generic function);
// parameter is URL string (relative or complete) to
// an .xml file whose Content-Type is a valid XML
// type, such as text/xml; XML source must be from
// same domain as HTML file
function loadXMLDoc(url) {
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send();
        }
    }
}

// handle onreadystatechange event of req object
function processReqChange() {
	// only if req shows "loaded"
//	alert(req.readyState);

    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            buildTopicList();
         } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
         }
    }
}

// invoked by "Category" select element change;
// loads chosen XML document, clears Topics select
// element, loads new items into Topics select element
function loadDoc(evt, id_carac, url, sid, idioma) {
    // equalize W3C/IE event models to get event object
    evt = (evt) ? evt : ((window.event) ? window.event : null);
    if (evt) {
        // equalize W3C/IE models to get event target reference
        elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
        if (elem) {
            try {
					id_caracteristica = id_carac;

					var id_car_tmp = elem.name.split("[");
					var id_car = id_car_tmp[1].split("]");

					dependencias = document.getElementById("dependencias").value;

					var dep = dependencias.split("@");

					if (document.getElementById("filtro"))
					{
						var filtro = document.getElementById("filtro").value;
					}
					else
						var filtro = "";

					var caracteristicas = "";

					for (cont = 0; cont < dep.length; cont++)
					{
						if (document.getElementById("caracteristicas_" + dep[cont]) != null) {
							if (document.getElementById("caracteristicas_" + dep[cont]).value != 0)
							{
								caracteristicas += "caracteristicas[" + dep[cont] + "]="
								caracteristicas += document.getElementById("caracteristicas_" + dep[cont]).value + "&"
								if (id_car[0] == dep[cont])
									break;
							}

						}
					}

					var action_car = document.getElementById('action_xml_carac');
					if (action_car == null) {
						action = "xml_carac";
					}
					else {
						action = action_car.value;
					}

//					document.write(url + "?sid=" + sid + "&action=xml_carac&id_carac_dep=" + id_caracteristica + "&id_carac_valor=" + elem.options[elem.selectedIndex].value + "&id_carac=" + id_car[0] + "&idioma=" + idioma + "&" + caracteristicas);
					//alert(url + "?sid=" + sid + "&action="+action+"&id_carac_dep=" + id_caracteristica + "&id_carac_valor=" + elem.options[elem.selectedIndex].value + "&id_carac=" + id_car[0] + "&idioma=" + idioma + "&" + caracteristicas + "filtro="+filtro);
					
					loadXMLDoc(url + "?sid=" + sid + "&action="+action+"&id_carac_dep=" + id_caracteristica + "&id_carac_valor=" + elem.options[elem.selectedIndex].value + "&id_carac=" + id_car[0] + "&idioma=" + idioma + "&" + caracteristicas + "filtro="+filtro);
            }
            catch(e) {
                var msg = (typeof e == "string") ? e : ((e.message) ? e.message : "Unknown Error");
                alert("Unable to get XML data:\n" + msg);
                return;
            }
        }
    }
}

// fill Topics select list with items from
// the current XML document
function buildTopicList() {


	//alert(req.responseXML.getElementsByTagName("employee")[0].childNodes[0].nodeValue)
	//alert("caracteristicas_" + id_caracteristica);


    // loop through <item> elements, and add each nested
    // <title> element to Topics select element
	// 16.09.2008 -- Cesc -------------------------------------
	var action_car = document.getElementById('action_xml_carac');
	if (action_car == null) {

		var items = req.responseXML.getElementsByTagName("opcion");
		var carac = document.getElementById("caracteristicas_" + id_caracteristica);

		for (var cont = carac.length; cont > 0; cont--)
		{
			carac.remove(cont);
		}

		var strHTML = "";


		cont = 1;
	    for (var i = 0; i < items.length; i++) {
	       valores = items[i].childNodes[0].nodeValue.split("@");
		   carac.options[cont] = new Option(valores[1], valores[0]);
		   cont++;
	    }
	}
	else {
		// En un cas concret. 16-09-2008
		if (action_car.value == 'xml_carac_2') {
			var car = req.responseXML.getElementsByTagName("caract");
			if (car.length > 0) {
				// Correm com tantes caracteristiques tinguem.
				for (var i=0; i < car.length; i++) {
					var carac = document.getElementById("caracteristicas_" + car[i].getAttribute('id'));
					if (carac != null) {
						clearSelect(carac);
						var opt = car[i].getElementsByTagName("opcio");
						if (opt.length > 0) {
							// Correm com tantes opcions tinguem.
							var cont = 2;
							for (var i2 = 0; i2 < opt.length; i2++) {
								carac.options[cont] = new Option(opt[i2].childNodes[0].nodeValue,opt[i2].getAttribute('id'));
								if (opt[i2].getAttribute('sel') != null) carac.selectedIndex = cont;
								cont++;
							}
						}
					}

				}
			}
		}
	}
	// -------------------------------------------------------
    // clear detail display
    // loop through <item> elements, and add each nested
    // <title> element to Topics select element
}

function clearSelect(objSelect)
{
	for (var cont = objSelect.length; cont > 1; cont--) objSelect.remove(cont);
}

function popup(url, ample, alt)
{
	var winl = (screen.width-ample)/2;
	var wint = (screen.height-alt)/2;
	var opcions=('top='+wint+',left='+winl+',width='+ample+',height='+alt+',toolbar='+0+',menubar='+0+',status='+0+',scrollbars='+1+',resizable='+0);
	var finestra = 'freetibet';
	window.open(url, finestra, opcions);
}

function MM_openBrWindow(theURL,winName,features)
{ //v2.0
	var error;

	if (!comprueva_obligatorias(false))
	{
		window.open(theURL,winName,features);
		document.getElementById("buscar_hoteles").target = winName;
		document.getElementById("buscar_hoteles").submit();
	}
}

function reserva_ya()
{
	if (document.getElementById("location")) doc_location = document.getElementById("location").value;
	else doc_location = false;

	document.reserva.submit();

	if (doc_location) document.location = doc_location;
}

function minisite(url)
{
        win=window.open(url,"minisite","width=750,height=550,top=100,left=100,scrollbars=yes,resizable=yes");
        win.focus();
}


function comprueva_obligatorias(submit)
{
	error = false;

	f = document.buscar_hoteles;
	for (i=0; f.elements.length > i; i++ )
	{
		str = f.elements[i].name;
		if (str.indexOf("obligatoria[") > -1 )
		{
			if (document.getElementById("caracteristicas_" + f.elements[i].value).value == 0) error = true;
		}
	}

	if (error)
	{
		if (!document.getElementById("error_obligatoria")) alert('ERROR');
		else alert(document.getElementById("error_obligatoria").value);
	}
	else
	{
		if (submit) document.buscar_hoteles.submit();
	}

	return error;
}

function valida_max(objeto, nombre, max, total)
{
	var cont;
	var sels = 0;

//	alert (objeto.name);
	for (cont = 0; cont < total; cont++)
	{
		if (document.getElementById(nombre + "_" + cont).checked)
		{
			sels++;
		}
	}

	if (sels > max)
	{
		if (objeto.checked)
		{
			alert(document.getElementById("error_max_sel").value);
			objeto.checked = false;

		}
	}
	// hay que comprobar que no haya mas caracteristicas del maximo
//	alert (nombre + " / " +  sels + " / " + max + " / " + total);
//	alert(document.getElementById(nombre).length);
}