//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;

	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs)
{
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();

    switch (currArg){
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace":
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}
/** fin AC_RunActiveContent.js **/

/** comienzo functions.js **/
var no_digito = /\D/g;
var optionActivate = 0;
var noValidar = new Array(	'id',
							'facturacion[cuenta][0]','facturacion[cuenta][1]','facturacion[cuenta][2]','facturacion[cuenta][3]', 'gendata[telefono2]', 'gendata[email2]',
							'contacto[1][nombre]','contacto[1][cargo]','contacto[1][telefono]', 'contacto[1][movil]', 'contacto[1][email]',
							'contacto[2][nombre]','contacto[2][cargo]','contacto[2][telefono]', 'contacto[2][movil]', 'contacto[2][email]',
							'allAirlines', 'notAirlines[]', 'aer_sf_value',
							'gendata[codiata]', 'gendata[logo]', 'gendata[central]'
						);
Array.prototype.in_array=function(elem){
    if( !this.convertido ) {
        this.convertido = new Array();
        for(var j in this)
            this.convertido[ this[j] ] = true;
    }
    return new Boolean(elem in this.convertido);
}
var noComprobar = 0;

var versiones = new Array('b2b', 'b2c', 'xml');

function cargarComssProvider(indice){
	var url = 'comisionDestino.php';
	var htmlCode = $.post(url, {provider: indice},
			function (data){
				document.getElementById('comisionDestinoDiv_'+indice).innerHTML = data;
			}
	);
}
function sendComssProvider(indice){
	var pais = document.getElementById('pais_'+indice).value;
	var destino = document.getElementById('destino_'+indice).value;
	var valor = document.getElementById('valor_'+indice).value;
	if (valor == '') return false;
	var tipo = document.getElementById('tipo_'+indice).value;

	var url = 'comisionDestino.php';

	var htmlCode = $.post(url, {pais: pais, destino: destino, valor: valor, tipo: tipo, provider: indice, action: 'up'},
			function (data){
				document.getElementById('comisionDestinoDiv_'+indice).innerHTML = data;
			}
	);
}

function delComssProvider(pais, destino, provider){
	var url = 'comisionDestino.php';

	var htmlCode = $.post(url, {pais: pais, destino: destino, provider: provider, action: 'down'},
			function (data){
				document.getElementById('comisionDestinoDiv_'+provider).innerHTML = data;
			}
	);
}

function almacenaComision(provider){
	var cmss_general_value = document.getElementById('comission['+provider+'][general]').value;
	var cmss_general_tipo = document.getElementById('comission['+provider+'][generaltipo]').value;
	var cmss_iva = getCheckedValue(document.getElementById('comission['+provider+'][iva]'));
/*	var mrk_sino = getCheckedValue(document.getElementById('comission['+provider+'][mrk]'));
	var mrk_b2b = document.getElementById('comission['+provider+'][1][mrkValue]').value;
	var mrk_b2c = document.getElementById('comission['+provider+'][2][mrkValue]').value;
	var mrk_xml = document.getElementById('comission['+provider+'][3][mrkValue]').value;
	var mrk_b2b_tipo = document.getElementById('comission['+provider+'][1][mrkTipo]').value;
	var mrk_b2c_tipo = document.getElementById('comission['+provider+'][2][mrkTipo]').value;
	var mrk_xml_tipo = document.getElementById('comission['+provider+'][3][mrkTipo]').value;*/
/*mrk: mrk_sino, mrk_b2b: mrk_b2b, mrk_b2c: mrk_b2c, mrk_xml: mrk_xml, mrk_b2b_tipo: mrk_b2b_tipo, mrk_b2c_tipo: mrk_b2c_tipo, mrk_xml_tipo: mrk_xml_tipo,*/

	var url = 'comisiones.php';

	var htmlCode = $.post(url, {genValue: cmss_general_value, genTipo: cmss_general_tipo, iva: cmss_iva, provider: provider, action: 'xxx'},
			function (data){
				document.getElementById('hola_'+provider).innerHTML = data;
				cargarComssProvider(provider);
			}
	);
}

function almacenaProviders(provider){
	var versiones = new Array();
	for (var i = 1; i <=3; i++){
		if (isset(document.getElementById('comission['+provider+'][version]['+i+']')) && (document.getElementById('comission['+provider+'][version]['+i+']').checked)){
			versiones[i] = 1;
		}
		else versiones[i] = 0;
	}

	var param1 = document.getElementById('comission['+provider+'][param1]').value;
	var param2 = document.getElementById('comission['+provider+'][param2]').value;
	var param3 = document.getElementById('comission['+provider+'][param3]').value;
	var param4 = document.getElementById('comission['+provider+'][param4]').value;
	var param5 = document.getElementById('comission['+provider+'][param5]').value;

	var campo = eval('document.datosCliente.fop'+provider);
	var fop = getCheckedValue(campo);

	var cmss_general_value = document.getElementById('comission['+provider+'][general]').value;
	var cmss_general_tipo = document.getElementById('comission['+provider+'][generaltipo]').value;
	var cmss_iva = getCheckedValue(document.getElementById('comission['+provider+'][iva]'));
	var mrk_sino = getCheckedValue(document.getElementById('comission['+provider+'][mrk]'));
	var mrk_b2b = document.getElementById('comission['+provider+'][1][mrkValue]').value;
	var mrk_b2c = document.getElementById('comission['+provider+'][2][mrkValue]').value;
	var mrk_xml = document.getElementById('comission['+provider+'][3][mrkValue]').value;
	var mrk_b2b_tipo = document.getElementById('comission['+provider+'][1][mrkTipo]').value;
	var mrk_b2c_tipo = document.getElementById('comission['+provider+'][2][mrkTipo]').value;
	var mrk_xml_tipo = document.getElementById('comission['+provider+'][3][mrkTipo]').value;

	var url = 'providers.php';

	var htmlCode = $.post(url, {param1: param1, param2: param2, param3: param3, param4: param4, param5: param5, fop: fop, genValue: cmss_general_value, genTipo: cmss_general_tipo, iva: cmss_iva, mrk: mrk_sino, mrk_b2b: mrk_b2b, mrk_b2c: mrk_b2c, mrk_xml: mrk_xml, mrk_b2b_tipo: mrk_b2b_tipo, mrk_b2c_tipo: mrk_b2c_tipo, mrk_xml_tipo: mrk_xml_tipo, provider: provider, b2b: versiones[1], b2c: versiones[2], xml: versiones[3], action: 'xxx'},
			function (data){
				document.getElementById('hola_'+provider).innerHTML = data;
				cargarComssProvider(provider);
			}
	);
}

function almacenaProvidersAgencia(provider){
	var versiones = new Array();
	for (var i = 1; i <=3; i++){
		if (isset(document.getElementById('comission['+provider+'][version]['+i+']')) && (document.getElementById('comission['+provider+'][version]['+i+']').checked)){
			versiones[i] = 1;
		}
		else versiones[i] = 0;
	}
	var fop = new Array();
	var arrayFops = new Array('credito', 'tarjeta', 'prepago', 'bonotalon');
	for (var i=1; i<=3; i++){
		var auxfop = '';
		for(var j=0; j < 5; j++){
			if (isset(document.getElementById('fop_'+provider+'['+i+']['+arrayFops[j]+']')) && (document.getElementById('fop_'+provider+'['+i+']['+arrayFops[j]+']').checked)){
				auxfop += '1,';
			}
			else auxfop += '0,';
		}
		fop[i] = auxfop;
	}

	var param1 = document.getElementById('comission['+provider+'][param1]').value;
	var param2 = document.getElementById('comission['+provider+'][param2]').value;
	var param3 = document.getElementById('comission['+provider+'][param3]').value;
	var param4 = document.getElementById('comission['+provider+'][param4]').value;
	var param5 = document.getElementById('comission['+provider+'][param5]').value;

	var campo = eval('document.datosCliente.fop'+provider);

	var cmss_general_value = document.getElementById('comission['+provider+'][general]').value;
	var cmss_general_tipo = document.getElementById('comission['+provider+'][generaltipo]').value;
	var cmss_iva = getCheckedValue(document.getElementById('comission['+provider+'][iva]'));
	var mrk_sino = getCheckedValue(document.getElementById('comission['+provider+'][mrk]'));
	var mrk_b2b = document.getElementById('comission['+provider+'][1][mrkValue]').value;
	var mrk_b2c = document.getElementById('comission['+provider+'][2][mrkValue]').value;
	var mrk_xml = document.getElementById('comission['+provider+'][3][mrkValue]').value;
	var mrk_b2b_tipo = document.getElementById('comission['+provider+'][1][mrkTipo]').value;
	var mrk_b2c_tipo = document.getElementById('comission['+provider+'][2][mrkTipo]').value;
	var mrk_xml_tipo = document.getElementById('comission['+provider+'][3][mrkTipo]').value;

	// formas de pago.

	var url = 'providers.php';

	var htmlCode = $.post(url, {param1: param1, param2: param2, param3: param3, param4: param4, param5: param5, fop_b2b: fop[1], fop_b2c: fop[2], fop_xml: fop[3], genValue: cmss_general_value, genTipo: cmss_general_tipo, iva: cmss_iva, mrk: mrk_sino, mrk_b2b: mrk_b2b, mrk_b2c: mrk_b2c, mrk_xml: mrk_xml, mrk_b2b_tipo: mrk_b2b_tipo, mrk_b2c_tipo: mrk_b2c_tipo, mrk_xml_tipo: mrk_xml_tipo, provider: provider, b2b: versiones[1], b2c: versiones[2], xml: versiones[3], action: 'xxx'},
			function (data){
				document.getElementById('hola_'+provider).innerHTML = data;
				cargarComssProvider(provider);
			}
	);
}

function enviaFormularioProveedoresAereo(){
	if (null != document.getElementById('notAirlines')){
    ListBox = document.getElementById('notAirlines');
	if(ListBox.options.length != 0)
	      for(var i=0; i < ListBox.options.length; i++){
	      	ListBox.options[i].selected = true;
	      }
	}

	document.datosCliente.submit();
}

function sendProviders(id)
{
	var form = 'VpProductsForm';
	var formulario = eval('document.'+form);
	var elementos = formulario.elements.length;

	var indice = 0;
	var providers = '';
	//bucle for paso 16 para saber el total campos
	for(i=0; i < elementos; i++)
	{
		if ((formulario.elements[i].type != undefined) && (formulario.elements[i].type != 'button'))
		{
			if (formulario.elements[i].checked == true){
				providers += formulario.elements[i].value+'#';
			}
		}
	}

	if (providers == '') alert('debe selecionar un producto');
	else {
		var selected = getCheckedValue(document.VpVersiones.services);

		var url = 'products_save.php';
		// lanzamos el jpost para recargar la parte del administrador.
		var htmlCode = $.post(url, {id: id, version: selected, providers: providers},
				function (data){
					document.getElementById('saveResult').innerHTML = data;
					actualizaTablaProductos(id);
				}
		);
	}
}

function cargarProductos(id){
	var url = 'products_ajax.php';
	var htmlCode = $.post(url, {id: id},
		function (data){
			document.getElementById('productsV').innerHTML = data;
			document.getElementById('productVContent').style.display = 'block';
			location.hash = 'products';
		}
	);
}

function actualizaTablaProductos(id){
		var url = 'products_table.php';
		// lanzamos el jpost para recargar la parte del administrador.
		var htmlCode = $.post(url, {id: id},
				function (data){
					document.getElementById('VpTable').innerHTML = data;
				}
		);
}



/* validación rápida de los formularios */
function validaRapidoFormAx(form)
{
	var formulario = eval('document.'+form);
	if (isset(formulario.sf_type) && (getCheckedValue(formulario.sf_type) == 2)){
		formulario.submit();return;
	}

	//Defino una variable boleana, si es 0 es false y si es 1 es true
	for (var i = 0; i < 5; i++)
	{
		var campo = eval("document.getElementById('error["+i+"]')");
		if (campo != null)
		{
			var valor = campo.value;
			if (valor == 1)
			{
				alert('Revise los campos marcados antes de continuar');
				return 'false';
			}
		}
	}

	if (null != document.getElementById('Acepto')){
		if (typeof document.getElementById('Acepto') != "undefined")
		{
			if (! document.getElementById('Acepto').checked ){
				alert('Debe aceptar las condiciones del contrato antes de continuar');
				return 'false';
			}
		}
	}

	if (null != document.getElementById('notAirlines')){
	    ListBox = document.getElementById('notAirlines');
		if(ListBox.options.length != 0)
		      for(var i=0; i < ListBox.options.length; i++){
		      	ListBox.options[i].selected = true;
		      }
	}

	var retorno = 1;
	var elementos = formulario.elements.length;

	// control para el sf.
	if (null != document.getElementById('whoage')) {
		if (document.getElementById('whoage').checked){
			elementos = 0;
		}
	};

	var indice = 0;
	var checkprovider = 0;
	var comprobar = true;
	//bucle for paso 16 para saber el total campos
	for(i=0; i < elementos; i++)
	{
		comprobar = true;
//		alert(formulario.elements[i].name);
		if (formulario.elements[i].name.search('provider') != -1) {
			if (formulario.elements[i].checked){
				// obtener el indice del proveedor.
				checkprovider = '-'+formulario.elements[i].name.match(/\d+/)+'-';
				indice++;
			}
		}

		if ((formulario.elements[i].name.substr(0, 6) == 'params')) {
			var indicativo = '-'+formulario.elements[i].name.match(/\d+/)+'-';
			if (indicativo != checkprovider){
				comprobar = false;
				formulario.elements[i].value = '';
			}
		}

		if ((formulario.elements[i].type != undefined) && (formulario.elements[i].type != 'button') && (noValidar.in_array(formulario.elements[i].name) == false) && (comprobar == true))
		{
			formulario.elements[i].style.backgroundColor = '#ffffff';
			formulario.elements[i].style.color = '#000000';

//			alert(formulario.elements[i].type);

			//si el elemento definido en la array formulario esta vacio...
			if(formulario.elements[i].value == "")
			{
				// cambio de color el fondo a rojo y la letra
				//alert(formulario.elements[i].name);
				formulario.elements[i].style.backgroundColor = '#E5F0FF';
				//cambio el valor de la variable boleana porque el campo esta vacio
				retorno = 0;
			}
			else
			{

				if (formulario.elements[i].type == 'select-one')
				{
					if(formulario.elements[i].value == '-')
					{
						formulario.elements[i].style.backgroundColor = '#E5F0FF';
						retorno = 0;
					}
				}
			}
		}
	}
	//En esta condicion: Si retorno es 0 "false" no envio el formulario y alerto al usuario
	if (retorno == 0)
	{
		alert("En algunos campos del formulario hay error o no estan completos");
		return (false);
	}

	//En esta condicion: Si retorno es 1 "true" envio el formulario y alerto al usuario conforme el exito
	if (retorno == 1)
	{
		formulario.submit();
	}
}

function reloadVersion (url, capa){
	var selected = 0;
	var num = 0;
	for (var i=0; i < versiones.length; i++){
		if (document.getElementById('services['+versiones[i]+']').checked){
			selected = document.getElementById('services['+versiones[i]+']').value;
			num ++;
		}
	}

	if (num == 1){
		document.getElementById('notaVersiones').style.display = 'none';
		// lanzamos el jpost para recargar la parte del administrador.
		var htmlCode = $.post(url, {service: selected},
				function (data){
					document.getElementById(capa).innerHTML = data;
				}
		);
	}
	else {
		document.getElementById('notaVersiones').style.display = 'block';
		var htmlCode = $.post(url, {name: 'jj'},
				function (data){
					document.getElementById(capa).innerHTML = data;
				}
		);
	}

}

function muestraTPV(type)
{
	if (type != ''){
		document.getElementById('datosTPV4b').style.display = 'none';
		document.getElementById('datosTPVCaixa').style.display = 'none';
		document.getElementById('datosTPVCeca').style.display = 'none';

		var capa = eval("document.getElementById('datosTPV"+type+"')");
		capa.style.display = 'block';
	}
}

function setVersion (url, capa){
	var selected = getCheckedValue(document.datosCliente.services);

	document.getElementById('notaVersiones').style.display = 'none';
	// lanzamos el jpost para recargar la parte del administrador.
	var htmlCode = $.post(url, {service: selected},
			function (data){
				document.getElementById(capa).innerHTML = data;
			}
	);
}
function setVersionAge (url, capa){
	var selected = getCheckedValue(document.datosCliente.services);

	document.getElementById('notaVersiones').style.display = 'none';
	// lanzamos el jpost para recargar la parte del administrador.
	var htmlCode = $.post(url, {service: selected},
			function (data){
				document.getElementById(capa).innerHTML = data;
				if (url == 'fop.php') {
					getTpvContent(selected);
					getTarjetasAgencia(selected);
				}
				if (url == 'funcionalidades.php'){
					getAssociatedAirports(selected);
				}
			}
	);
}

function getTpvContent(version){
	var url = 'tpv_config.php';
	var htmlCode = $.post(url, {version: version},
		function (data){
			document.getElementById('contenidoTPV').innerHTML = data;
		}
	);
}

function setTpvValue(base){

	var checkedP = getCheckedValue(document.datosCliente.provider);
	var selected = getCheckedValue(document.datosCliente.services);

	switch(checkedP){
		case '4b':
			var provider = '4b';
			var idComercio = document.getElementById('idComercio').value;
			var estado = getCheckedValue(document.datosCliente.entorno);
			var json = {base: base, provider: provider, idComercio: idComercio, entorno: estado};
			break;
		case 'Caixa':
			var provider = 'Caixa';
			var code = document.getElementById('fuc').value;
			var terminal = document.getElementById('terminal').value;
			var moneda = document.getElementById('monedaCx').value;
			var clave =document.getElementById('clave').value;
			var estado = getCheckedValue(document.datosCliente.entornoCaixa);
			var json = {base: base, provider: provider, fuc: code, terminal: terminal, monedaCx: moneda, clave: clave, entornoCaixa: estado};
			break;
		case 'Ceca':
			var provider = 'Ceca';
			var acquirebin = document.getElementById('AcquireBIN').value;
			var merchantid = document.getElementById('MerchantID').value;
			var terminal = document.getElementById('TerminalID').value;
			var password = document.getElementById('Password').value;
			var moneda = document.getElementById('monedaCc').value;
			var estado = getCheckedValue(document.datosCliente.entornoCeca);
			var json = {base: base, provider: provider, AcquireBIN: acquirebin, MerchantID: merchantid, TerminalID: terminal, Password: password, monedaCc: moneda, entornoCeca: estado};
			break;
	}
	// subir los datos de la TPV.
	//var urlPet = 'http://service3.reglowmixer.com/tpvs/setTpvData.php';
	var urlPet = 'tpv/setTpv.php';
	var htmlCode = $.post(urlPet, json,
		function (data){
			document.getElementById('resultTPV').innerHTML = data;
			getTpvContent(selected);
		}
	);
}

function getTarjetasAgencia(version){
	var url = 'tarjetaAgencia_config.php';
	var htmlCode = $.post(url, {version: version},
		function (data){
			document.getElementById('contentTAGe').innerHTML = data;
		}
	);
}

function siguiente2(t,v) {
   var prueba= eval("document.datosCliente.num"+t+v);
   if ((prueba.value.length==4)&&(t==1))
    	eval("document.datosCliente.num2"+v+".focus()");
   else if ((prueba.value.length==4)&&(t==2))
    	eval("document.datosCliente.num3"+v+".focus()");
   else if ((prueba.value.length==4)&&(t==3))
    	eval("document.datosCliente.num4"+v+".focus()");
}

function setTAG(){
	var selected = getCheckedValue(document.datosCliente.services);

	var nombre = document.getElementById('nombreTarjeta').value;
	var tipo = document.getElementById('tipoTarjeta').value;
	var mes = document.getElementById('mesTarjeta').value;
	var anyo = document.getElementById('anyoTarjeta').value;
	var cvv = document.getElementById('cvvTarjeta').value;
	var titular = document.getElementById('titularTarjeta').value;

	var num0 = document.getElementById('num0').value;
	var num1 = document.getElementById('num1').value;
	var num2 = document.getElementById('num2').value;
	var num3 = document.getElementById('num3').value;

	var json = {nombre: nombre, tipo: tipo, mes: mes, anyo: anyo, cvv: cvv, titular: titular, num0: num0, num1: num1, num2: num2, num3: num3};

	var urlPet = 'tag/setTAG.php';
	var htmlCode = $.post(urlPet, json,
		function (data){
			document.getElementById('resultTag').innerHTML = data;
			getTarjetasAgencia(selected);
		}
	);
}

function delTAG(indice){
	var selected = getCheckedValue(document.datosCliente.services);

	var urlPet = 'tag/setTAG.php';
	var htmlCode = $.post(urlPet, {action: 'del', indice: indice},
		function (data){
			document.getElementById('resultTag').innerHTML = data;
			getTarjetasAgencia(selected);
		}
	);
}

function getAssociatedAirports(version){
	var urlPet = 'func/aeropuertos_config.php';
	var htmlCode = $.post(urlPet, {version: version},
		function (data){
			document.getElementById('contentAir').innerHTML = data;
		}
	);
}

function setAirports(){
	var selected = getCheckedValue(document.datosCliente.services);

	var citie = document.getElementById('cityCode').value;
	var airCodes = '';
	for (var i=0; i< 5; i++){
		if (document.getElementById('airCode'+i).value != ''){
			if (i == 0){
				airCodes += document.getElementById('airCode'+i).value
			}
			else {
				airCodes += "#"+document.getElementById('airCode'+i).value
			}
		}
	}
	if (airCodes != ''){
		var urlPet = 'func/setAirport.php';
		var htmlCode = $.post(urlPet, {city:citie, airports: airCodes,version: selected},
			function (data){
				document.getElementById('resultAir').innerHTML = data;
				getAssociatedAirports(selected);
			}
		);
	}
}

function delAirport(city, airport, version){

	var urlPet = 'func/setAirport.php';
	var htmlCode = $.post(urlPet, {city:city, airport: airport, version: version, action: 'del'},
		function (data){
			document.getElementById('resultAir').innerHTML = data;
			getAssociatedAirports(version);
		}
	);
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}


//---------------------------------------------------------------------------------------------
//Funciones para ver si existe una variable
//---------------------------------------------------------------------------------------------
function isset(variable_name) {
    try {
         if (typeof(eval(variable_name)) != 'undefined')
         if (eval(variable_name) != null)
         return true;
     } catch(e) { }
    return false;
}


//---------------------------------------------------------------------------------------------
//Funciones para abrir y cerrar un popup
//---------------------------------------------------------------------------------------------
function abrirPopUp(url, title)
{
	var margenTop = '100';
	var margenLeft = '100';
	var ancho = '650';
	var alto = '400';
	window.open(url, title, "width="+ancho+", height="+alto+", top="+margenTop+", left="+margenLeft+", scrollbars=yes")
}

function abrirPopUpCondiciones(url, title)
{
	var margenTop = '50';
	var margenLeft = '100';
	var ancho = '850';
	var alto = '450';
	window.open(url, title, "width="+ancho+", height="+alto+", top="+margenTop+", left="+margenLeft+", scrollbars=yes")
}

function abrirPopUpBono(idFormulario)
{
	var title='BonoReserva';
	var margenTop = '20';
	var margenLeft = '50';
	var ancho = '870';
	var alto = '600';

	window.open('', title, "width="+ancho+", height="+alto+", top="+margenTop+", left="+margenLeft+", scrollbars=yes");
	if (!isIE) document.getElementById(idFormulario).target='BonoReserva';
	document.getElementById(idFormulario).submit();
}


function cerrarPopUp()
{
	window.close();
}

//---------------------------------------------------------------------------------------------
// Devuelve la posición vertical de un objeto DOM.
//---------------------------------------------------------------------------------------------
function findPosX(obj)
{
	var curleft = 0;
	if(obj.offsetParent)
	    while(1)
	    {
	      curleft += obj.offsetLeft;
	      if(!obj.offsetParent)
	        break;
	      obj = obj.offsetParent;
	    }
	else if(obj.x)
	    curleft += obj.x;
	return curleft;
}
//---------------------------------------------------------------------------------------------
// Devuelve la posición horizontal de un objeto DOM.
//---------------------------------------------------------------------------------------------
function findPosY(obj)
{
	var curtop = 0;
	if(obj.offsetParent)
	    while(1)
	    {
	      curtop += obj.offsetTop;
	      if(!obj.offsetParent)
	        break;
	      obj = obj.offsetParent;
	    }
	else if(obj.y)
	    curtop += obj.y;
	return curtop;
}


//---------------------------------------------------------------------------------------------
//Funcion que muestra un div en la posicion indicada
//---------------------------------------------------------------------------------------------
function posicionarCapa(capa, elementoReferencia, elementoMarco)
{
//	alert(capa+' '+elementoReferencia+' '+elementoMarco)
	var objetoReferencia = document.getElementById(elementoReferencia);
	var elemento_posX = findPosX(objetoReferencia);
	var elemento_posY = findPosY(objetoReferencia);

	if (elementoMarco!='')
	{
		var objetoMarco = document.getElementById(elementoMarco);
		var marco_posX = findPosX(objetoMarco);
		var marco_posY = findPosY(objetoMarco);

		var posX = elemento_posX - marco_posX;
		var posY = elemento_posY - marco_posY;
	}
	else
	{
		var posX = elemento_posX;
		var posY = elemento_posY;
	}

	document.getElementById(capa).style.left = posX + 'px';
	document.getElementById(capa).style.top = (posY) + 'px';
	document.getElementById(capa).style.zIndex = 3;
}

function posicionarCapaExtend(capa, elementoReferencia, elementoMarco, addX, addY, display){
	var objetoReferencia = document.getElementById(elementoReferencia);
	var elemento_posX = findPosX(objetoReferencia);
	var elemento_posY = findPosY(objetoReferencia);

	if (elementoMarco!='')
	{
		var objetoMarco = document.getElementById(elementoMarco);
		var marco_posX = findPosX(objetoMarco);
		var marco_posY = findPosY(objetoMarco);

		var posX = elemento_posX - marco_posX;
		var posY = elemento_posY - marco_posY;
	}
	else
	{
		var posX = elemento_posX;
		var posY = elemento_posY;
	}

	posX = posX + addX;
	posY = posY + addY;

	document.getElementById(capa).style.left = posX + 'px';
	document.getElementById(capa).style.top = (posY) + 'px';
	document.getElementById(capa).style.zIndex = 3;

	if (display == 'si'){
		document.getElementById(capa).style.display = 'block';
	}
}

function pintarAyuda(elementoReferencia, elementoMarco, addX, addY, textos){
	// rellenamos la capa.
	document.getElementById('titleHelp').innerHTML = textos[0];
	document.getElementById('contentHelp').innerHTML = textos[1];

	// la posicionamos.
	posicionarCapaExtend('ayuda', elementoReferencia, elementoMarco, addX, addY, 'si');
}


function pintarDialogo(elementoReferencia, elementoMarco, addX, addY, textos, capaDialogo)
{
	// rellenamos la capa.
	document.getElementById('title').innerHTML = textos[0];
	document.getElementById('contentTexto').innerHTML = textos[1];

	// la posicionamos.
	posicionarCapaExtend(capaDialogo, elementoReferencia, elementoMarco, addX, addY, 'si');
}

function pintarDialogoEscalas(elementoReferencia, elementoMarco, addX, addY, textos, capaDialogo)
{
	// rellenamos la capa.
	document.getElementById('titleEscalas').innerHTML = textos[0];
	document.getElementById('contentTextoEscalas').innerHTML = textos[1];

	// la posicionamos.
	posicionarCapaExtend(capaDialogo, elementoReferencia, elementoMarco, addX, addY, 'si');
}


//---------------------------------------------------------------------------------------------
// Mostrar y ocultar capas
//---------------------------------------------------------------------------------------------
function mostrarCapa(capa)
{
	if (isset(document.getElementById(capa)))
	{
		document.getElementById(capa).style.display = "block";
	}
}
function ocultarCapa(capa)
{
	//	Para evitar errores comprobar si existe la capa nates de ocultarla
	if (isset(document.getElementById(capa)))
	{
		document.getElementById(capa).style.display = "none";
	}
}
function ocultarVariasCapas(capa, inicio, fin)
{
	//Incluir límites por si acaso. Para evitar errores comprobar si existe la capa nates de ocultarla
	for (i=inicio; i<=fin; i++)
	{
		nombreCapa = capa+i;

		if (isset(document.getElementById(nombreCapa)))
		{
			document.getElementById(nombreCapa).style.display = "none";
		}
	}
}
function evaluarMostrarOcultarCapa(indice, i, totalCapas, pathTemplate)
{
	capa = 'capaHabitaciones_'+indice+'_'+i;
	imagen = 'botonMasMenos_'+indice+'_'+i;

	//	Para evitar errores comprobar si existe la capa nates de mostrarla
	if (isset(document.getElementById(capa)))
	{
		if (document.getElementById(capa).style.display == 'none')
		{
			document.getElementById(capa).style.display = 'block';
			document.getElementById(imagen).src = pathTemplate+'less.gif';
		}
		else
		{
			document.getElementById(capa).style.display = 'none';
			document.getElementById(imagen).src = pathTemplate+'more.gif';
		}
	}
}



function comprobarPaxActividades(indice, adultos, menores, bebes, mensajeError, mensajeErrorVacio)
{
	var idFormulario = 'formularioReservarTarifas_'+indice
	var formulario = document.getElementById(idFormulario);

	var totalRangos = formulario.totalRangos.value;

	if (mensajeError != '') //RVM comprobar pasajeros
	{
		//Contar pasajeros
		numeroAdultos = 0;
		numeroMenores = 0;
		numeroBebes = 0;
		for (i=0; i<totalRangos; i++)
		{
			totalTarifas = eval('formulario.totalTarifas_'+i).value;
			for (j=0; j<totalTarifas; j++)
			{
				valorCampo = eval('formulario.tarifa_'+i+'_'+j).value;

				auxTipo = valorCampo.split("==");
				cantidadPax = parseInt(auxTipo[0]);
				tipoPax = auxTipo[2];

				switch(tipoPax)
				{
					case 'ADULTO': numeroAdultos 	= numeroAdultos + cantidadPax; break;
					case 'MENOR': numeroMenores 	= numeroMenores + cantidadPax; break;
					case 'BEBE': 	numeroBebes 	= numeroBebes + cantidadPax; break;
				}
			}
		}

		if ((numeroAdultos == adultos) && (numeroMenores == menores) && (numeroBebes == bebes))
		{
			 formulario.submit();
		}
		else
		{
			//OJO!! Si es una busqueda SOLO INFANTIL ignorar los pax (solo controlar que sean >0)
			// no tienen que coincidir con la busqueda
			var tipoBusqueda = formulario.tipoBusqueda.value;
			if (tipoBusqueda=='infantil')
			{
				//ver que al menos hay uno
				totalPax = numeroAdultos+numeroMenores+numeroBebes;
				if (totalPax>0) formulario.submit();
				else alert(mensajeErrorVacio)
			}
			else alert(mensajeError);
		}
	}
	else //NO es RVM no controlar pasajeros
	{
		formulario.submit();
	}
}



//---------------------------------------------------------------------------------------------
//Modifica el display del objeto recibido
//---------------------------------------------------------------------------------------------
function changeDisplay(obj){
	if (document.getElementById(obj).style.display == 'none'){
		document.getElementById(obj).style.display = 'block';
	}
	else {
		document.getElementById(obj).style.display = 'none';
	}
}




//---------------------------------------------------------------------------------------------
// Mostrar vuelos combinados con el seleccionado
//---------------------------------------------------------------------------------------------

function evaluarTrayecto(valorRadio, i, j, totalTrayectos)
{
	auxCombinaciones = valorRadio.split("#");
	cadenaCombinaciones = auxCombinaciones[2];
	arrayCombinaciones = cadenaCombinaciones.split(",");

//	Ocultar capas anteriores
	capa = 'capaTrayectoVuelta_'+i+'_';
	ocultarVariasCapas(capa, 0, totalTrayectos);

//	Mostrar capas de la combinacion
	totalCombinaciones = arrayCombinaciones.length;
	for (indice=0; indice<totalCombinaciones; indice++)
	{
		capa = 'capaTrayectoVuelta_'+i+'_'+arrayCombinaciones[indice];
		mostrarCapa(capa);
	}

	seleccionarPrimerTrayectoVuelta(i, totalTrayectos);
}


function inicializarEvaluarTrayecto(i, totalTrayectos)
{
	var totalRadios = eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoIda_'+i).length;
//	alert(totalRadios)

	//si hay varios radiobuttons tratarlos como un array
	if (totalRadios != undefined)
	{
		for (k=0; k<totalRadios; k++)
		{
			if (eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoIda_'+i+'[k]').checked == true)
			{
				valorRadio = eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoIda_'+i+'[k]').value;
			}
		}
	}
	else //si hay un solo radiobutton trabajar directamente con el
	{
		valorRadio = eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoIda_'+i).value
	}
//	alert(valorRadio)

	evaluarTrayecto(valorRadio, i, 0, totalTrayectos);
}



function seleccionarPrimerTrayectoVuelta(i, totalTrayectos)
{
	//	Seleccionar el primero visible por defecto

	for (j=1; j<=totalTrayectos; j++)
	{
		capa = 'capaTrayectoVuelta_'+i+'_'+j;

		if ((isset(document.getElementById(capa))) && (document.getElementById(capa).style.display == "block"))
		{
			//Primera capa abierta -> activar su radiobutton correspondiente
			var totalRadios = eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoVuelta_'+i).length;

			//si hay varios radiobuttons tratarlos como un array
			if (totalRadios != undefined)
			{
				//Recorrer cada radio y comprobar su IDtrayecto con el J. Si coinciden marcarlo porque es el primero
				for (k=0; k<totalRadios; k++)
				{
					valorRadio = eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoVuelta_'+i+'[k]').value;
					arrayValorRadio = valorRadio.split("#");
					auxIdTrayectoVuelta = arrayValorRadio[0];

					if (auxIdTrayectoVuelta == j)
					{
						eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoVuelta_'+i+'[k]').checked = true;
						return 1;
					}
				}
			}
			else //si hay un solo radiobutton trabajar directamente con el
			{
				eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoVuelta_'+i).checked = true;
				return 1;
			}
		}
	}
}

	function compruebaTrayectoPuenteAereo()
	{
		var formulario = document.getElementById("formularioTarifasPuenteAereo");

		var usuarioFinal = formulario.usuarioFinal.value;
//		alert(usuarioFinal)

		//HAY varios radiobuttons de TRAYECTOS (no son variables, son siempre 4) tratarlos como un array
		for (i=0; i<4; i++)
		{
			if (eval('document.getElementById("formularioTarifasPuenteAereo").trayectos[i]').checked == true)
			{
				valorTrayectos = eval('document.getElementById("formularioTarifasPuenteAereo").trayectos[i]').value;
			}
		}
//		alert(valorTrayectos)


		//HAY varios radiobuttons de TARIFA (no son variables, son siempre 2) tratarlos como un array
		for (i=0; i<2; i++)
		{
			if (eval('document.getElementById("formularioTarifasPuenteAereo").tarifa[i]').checked == true)
			{
				valorTarifa = eval('document.getElementById("formularioTarifasPuenteAereo").tarifa[i]').value;
			}
		}
//		alert(valorTarifa)


		//Ver tarifas correspondientes a la seleccion
		var precioBase = 0;
		var precioTasas = 0;
		var precioTotalPasajero = 0;
		var serviceFee = 0;
		var serviceFeeEmision = 0;
		var precioTotalPasajeroSF = 0;
		switch(valorTrayectos)
		{
			case 'MADBCN':
			case 'BCNMAD':		if (valorTarifa == 'Y')
								{
									tarifaCodigo			= formulario.tarifa_turista_ida_codigo.value;
									precioBase 				= formulario.tarifa_turista_ida_base.value;
									precioTasas 			= formulario.tarifa_turista_ida_tasas.value;
									precioTotalPasajero 	= formulario.tarifa_turista_ida_total.value;
									serviceFee 				= formulario.tarifa_turista_ida_sf.value;
									serviceFeeEmision 		= formulario.tarifa_turista_ida_sf_emision.value;
									precioTotalPasajeroSF 	= formulario.tarifa_turista_ida_total_mas_sf.value;
								}
								else
								{
									tarifaCodigo 			= formulario.tarifa_business_ida_codigo.value;
									precioBase 				= formulario.tarifa_business_ida_base.value;
									precioTasas 			= formulario.tarifa_business_ida_tasas.value;
									precioTotalPasajero 	= formulario.tarifa_business_ida_total.value;
									serviceFee 				= formulario.tarifa_business_ida_sf.value;
									serviceFeeEmision 		= formulario.tarifa_business_ida_sf_emision.value;
									precioTotalPasajeroSF 	= formulario.tarifa_business_ida_total_mas_sf.value;
								}
								break;


			case 'MADBCNMAD':
			case 'BCNMADBCN':	if (valorTarifa == 'Y')
								{
									tarifaCodigo 			= formulario.tarifa_turista_idavuelta_codigo.value;
									precioBase 				= formulario.tarifa_turista_idavuelta_base.value;
									precioTasas 			= formulario.tarifa_turista_idavuelta_tasas.value;
									precioTotalPasajero 	= formulario.tarifa_turista_idavuelta_total.value;
									serviceFee 				= formulario.tarifa_turista_idavuelta_sf.value;
									serviceFeeEmision 		= formulario.tarifa_turista_idavuelta_sf_emision.value;
									precioTotalPasajeroSF 	= formulario.tarifa_turista_idavuelta_total_mas_sf.value;
								}
								else
								{
									tarifaCodigo 			= formulario.tarifa_business_idavuelta_codigo.value;
									precioBase 				= formulario.tarifa_business_idavuelta_base.value;
									precioTasas 			= formulario.tarifa_business_idavuelta_tasas.value;
									precioTotalPasajero 	= formulario.tarifa_business_idavuelta_total.value;
									serviceFee 				= formulario.tarifa_business_idavuelta_sf.value;
									serviceFeeEmision 		= formulario.tarifa_business_idavuelta_sf_emision.value;
									precioTotalPasajeroSF 	= formulario.tarifa_business_idavuelta_total_mas_sf.value;
								}
								break;
		}


		precioTotalPasajeroSF = parseFloat(precioTotalPasajeroSF)
		numeroPasajeros = parseInt(formulario.numeroPasajeros.value);

		//Calcular total en funcion del numero de personas y SF
		Total = precioTotalPasajeroSF * numeroPasajeros;

		//Controlar si vienen vacios para evitar el NaN
		if (precioBase=='') precioBase=0;
		if (precioTasas=='') precioTasas=0;
		if (precioTotalPasajero=='') precioTotalPasajero=0;
		if (serviceFee=='') serviceFee=0;
		if (serviceFeeEmision=='') serviceFeeEmision=0;
		if (precioTotalPasajeroSF=='') precioTotalPasajeroSF=0;


//		alert(precioBase)
//		alert(precioTasas)
//		alert(precioTotalPasajero)
//		alert(serviceFee)
//		alert(serviceFeeEmision)
//		alert(precioTotalPasajeroSF)

		formulario.tarifaCodigo.value = tarifaCodigo;
		formulario.precioBase.value = parseFloat(precioBase).toFixed(2);
		formulario.precioTasas.value = parseFloat(precioTasas).toFixed(2);

		//Para B2C mostrar los SF juntos en unico campo
		if (usuarioFinal == '1')
		{
			serviceFeeUsuarioFinal = parseFloat(serviceFee) + parseFloat(serviceFeeEmision);
			formulario.serviceFee.value = parseFloat(serviceFeeUsuarioFinal).toFixed(2);
			formulario.serviceFeeEmision.value = 0;
		}
		else
		{
			formulario.serviceFee.value = parseFloat(serviceFee).toFixed(2);
			formulario.serviceFeeEmision.value = parseFloat(serviceFeeEmision).toFixed(2);
		}
		formulario.precioTotalPasajeroSF.value = parseFloat(precioTotalPasajeroSF).toFixed(2);
		formulario.precioTotalSF.value = parseFloat(Total).toFixed(2);

		//Tras cargar tarifas mostrar boton de reservar (solo primera vez, las demas ya estaba visible)
		if (document.getElementById('botonFormularioPuente').style.display=='none')	mostrarCapa('botonFormularioPuente');
	}


//---------------------------------------------------------------------------------------------
// Capas Edades Menores en formulario de Busqueda
//---------------------------------------------------------------------------------------------
function mostrarEdadesMenores(habitacion, numeroMenores, producto)
{
	var nombreCapa = 'edadesMenores_'+habitacion;

	var maximoNumeroMenores = 3;

	if (numeroMenores != 0)
	{
		//oculta todas las edades
		for (i=1; i<=maximoNumeroMenores; i++)
		{
			var aux = 'edadMenor_'+habitacion+'_'+i;
			document.getElementById(aux).style.display = 'none';
		}

		//muestra edades para cada menor seleccionado
		for (i=1; i<=numeroMenores; i++)
		{
			var aux = 'edadMenor_'+habitacion+'_'+i;
			document.getElementById(aux).style.display = 'block';
		}

		//Posicionar capa (si no hay habitaciones la etiqueta simplemente es "menores")
		if (producto == 'hoteles') nombreElementoReferencia = 'menores_'+habitacion;
		else
			if (producto == 'actividades') nombreElementoReferencia = 'menores';

		posicionarCapa(nombreCapa, nombreElementoReferencia, 'formularioBusqueda');

		//Mostrar capa
		document.getElementById(nombreCapa).style.display = "block";
	}
	else
	{
		//Ocultar capa
		ocultarCapa(nombreCapa);
	}
}


//---------------------------------------------------------------------------------------------
//Colorear campos con error
//---------------------------------------------------------------------------------------------
function colorearCampoError(idCampo, color)
{
	document.getElementById(idCampo).style.backgroundColor = color;
}


//---------------------------------------------------------------------------------------------
//Filtros
//---------------------------------------------------------------------------------------------
function filtrar()
{
	$('#dialogoEspera').dialog('open');

	document.getElementById('formularioFiltros').submit();
}

function resetFiltros()
{
	document.getElementById('formularioFiltros').tipoFiltro.value='reset';
	document.getElementById('formularioFiltros').submit();
}

function evaluarFiltrosEstrellas(categoria)
{
	var campo='';

	if (eval('document.getElementById("formularioFiltros").filtroCategoria_'+categoria).checked == true)
	{
//		alert('MARCAR y dejar posteriores '+categoria)

		//desmarcar las anteriores
		for (i=1; i<categoria; i++)
		{
			campo = 'filtroCategoria_'+i;
			eval('document.getElementById("formularioFiltros").'+campo).checked = false;
		}

		//marcar esa opcion y marcar las posteriores
		for (i=categoria; i<=5; i++)
		{
			campo = 'filtroCategoria_'+i;
			eval('document.getElementById("formularioFiltros").'+campo).checked = true;
		}

		document.getElementById('formularioFiltros').filtroCategoria.value = categoria;
	}
	else
	{
//		alert('desmarcar y dejar posteriores' + categoria)

		//desmarcar las anteriores
		for (i=1; i<=categoria; i++)
		{
			campo = 'filtroCategoria_'+i;
			eval('document.getElementById("formularioFiltros").'+campo).checked = false;
		}

		//marcar esa opcion y marcar las posteriores
		var posterior = categoria+1
		for (i=posterior; i<=5; i++)
		{
			campo = 'filtroCategoria_'+i;
			eval('document.getElementById("formularioFiltros").'+campo).checked = true;
		}

		document.getElementById('formularioFiltros').filtroCategoria.value = posterior;
	}
}

function evaluarFiltrosServicios(totalServicios)
{
	var codigoServicio='';
	var cadenaServicios= '';

	for (i=0; i<totalServicios; i++)
	{
		if (eval('document.getElementById("formularioFiltros").filtroServicio_'+i).checked == true)
		{
			//si está marcado almacenar en cadena de servicios
			codigoServicio = eval('document.getElementById("formularioFiltros").filtroServicio_'+i).value;
			cadenaServicios += codigoServicio+','; //SIN espacios
		}
	}
	document.getElementById('formularioFiltros').filtroServicios.value = cadenaServicios;
}


//---------------------------------------------------------------------------------------------
//PAGINACION
//---------------------------------------------------------------------------------------------
function paginar(p)
{
	$('#dialogoEspera').dialog('open');

	document.getElementById('formularioPaginacion').paginaActual.value = p;
	document.getElementById('formularioPaginacion').submit();
}



//---------------------------------------------------------------------------------------------
//SELECCION HABITACIONES - REGIMEN y restricciones
//---------------------------------------------------------------------------------------------
function establecerHabitacionRegimen(indice, i, j, t)
{
	var valorRadio = '';
	var totalTarifas = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_'+j).length;


	//Establecer habitacion

	//si hay varios radiobuttons tratarlos como un array
	if (totalTarifas != undefined)
	{
		for (k=0; k<totalTarifas; k++)
		{
			if (eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_'+j+'[k]').checked == true)
			{
				valorRadio = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_'+j+'[k]').value;
			}
		}
	}
	else //si hay un solo radiobutton trabajar directamente con el
	{
		valorRadio = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_'+j).value
	}
	eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").seleccion_RoomStay_'+j+'_RoomType').value = valorRadio;





	//Establecer regimen correspondiente a esa habitacion

	valorSelect = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").regimen_'+j+'_'+t).value;
	eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").seleccion_RoomStay_'+j+'_RatePlan').value = valorSelect;


	//Establecer precios y comision
	var arrayAux = valorSelect.split("_");
	var AmountBeforeTax = arrayAux[1];
	var AmountAfterTax = arrayAux[2];
	var Commision = arrayAux[3];

	eval('document.getElementById("PC_'+indice+'_'+i+'_'+j+'_'+t+'")').value = AmountBeforeTax;
	eval('document.getElementById("PVP_'+indice+'_'+i+'_'+j+'_'+t+'")').value = AmountAfterTax;
	eval('document.getElementById("Commision_'+indice+'_'+i+'_'+j+'_'+t+'")').value = Commision;
}


function marcarHabitacion(indice, i, j, t)
{
	eval('document.getElementById("idHabitacion_'+indice+'_'+i+'_'+j+'_'+t+'")').checked = true;
}

function restringirRegimenes(indice, i)
{
	//---------- Ver que valor de regimen esta cogido en la primera habitacion (j=0). Las demas seran iguales.
	var totalTarifasPrimerRoomstay = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").seleccion_TotalTarifas_0').value;

	//si hay varios radiobuttons tratarlos como un array
	if (totalTarifasPrimerRoomstay != 1)
	{
		for (t=0; t<totalTarifasPrimerRoomstay; t++)
		{
			if (eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_0[t]').checked == true)
			{
				valorRadioPrimerRoomstay = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_0[t]').value;
				valorSelectPrimerRoomstay = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").regimen_0_'+t).value;
			}
		}
	}
	else //si hay un solo radiobutton trabajar directamente con el
	{
		valorRadioPrimerRoomstay = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_0').value
		valorSelectPrimerRoomstay = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").regimen_0_0').value;
	}
//	alert(valorRadioPrimerRoomstay);
//	alert(valorSelectPrimerRoomstay);

	arrayRegimenPrimerRoomstay = valorSelectPrimerRoomstay.split("_");
	auxRegimenPrimerRoomstay = arrayRegimenPrimerRoomstay[0];
	datosRegimenPrimerRoomstay = auxRegimenPrimerRoomstay.split("#CONCATENADO#");
	RatePlanPrimerRoomstay = datosRegimenPrimerRoomstay[0];




	//---------- Recorrer cada habitacion y cada regimen de habitacion para igualar al seleccionado
	var numeroRoomStays = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").seleccion_TotalRoomStays').value;
//	alert(numeroRoomStays);

	//ignoramos el primer roomstay pues es el que establece los valores
	for(j=1; j<numeroRoomStays; j++)
	{
		var totalTarifasRoomstay = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").seleccion_TotalTarifas_'+j).value;
//		alert(totalTarifasRoomstay)

		for (t=0; t<totalTarifasRoomstay; t++)
		{
			campoRegimen = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").regimen_'+j+'_'+t);
			valorCampoRegimen = campoRegimen.value;
//			alert('Roomstay '+j+' tarifa '+t+' regimen '+valorCampoRegimen)

			arrayRegimen = valorCampoRegimen.split("_");
			auxRegimen = arrayRegimen[0];
			datosRegimen = auxRegimen.split("#CONCATENADO#");
			RatePlan = datosRegimen[0];

			for(o=0; o<campoRegimen.options.length; o++)
			{
				valorOption = campoRegimen.options[o].value;

				auxOptions = valorOption.split("_");
				codigosRegimenOptions = auxOptions[0];
				auxOptions2 = codigosRegimenOptions.split("#CONCATENADO#");
				opcion = auxOptions2[0];

				if (RatePlanPrimerRoomstay == opcion)
				{
					campoRegimen.options[o].selected=true;

					//al cambiar el valor del combo, cambiar tambien el campo oculto con los datos para prereserva
					establecerHabitacionRegimen(indice, i, j, t);
				}
			}
		}
	}
}


function evaluarGoGlobal(indice, i)
{
	//Primero restringir regimenes segun el seleccionado
	restringirRegimenes(indice, i);


//	En GoGlobal [codigoRegimen] => AD#CONCATENADO#74583/6247/594
//	-->la segunda parte: 74583/6247/594 --> activar los radio que tengan un regimen con ese codigo


	//---------- Ver que valor de regimen esta cogido en la primera habitacion (j=0). Las demas seran iguales.
	var totalTarifasPrimerRoomstay = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").seleccion_TotalTarifas_0').value;
//	alert(totalTarifasPrimerRoomstay)

	//si hay varios radiobuttons tratarlos como un array
	if (totalTarifasPrimerRoomstay != 1)
	{
		for (t=0; t<totalTarifasPrimerRoomstay; t++)
		{
			if (eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_0[t]').checked == true)
			{
				valorSelectPrimerRoomstay = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").regimen_0_'+t).value;
			}
		}
	}
	else //si hay un solo radiobutton trabajar directamente con el
	{
		valorSelectPrimerRoomstay = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").regimen_0_0').value;
	}
//	alert(valorSelectPrimerRoomstay);

	arrayRegimenPrimerRoomstay = valorSelectPrimerRoomstay.split("_");
	auxRegimenPrimerRoomstay = arrayRegimenPrimerRoomstay[0];
	datosRegimenPrimerRoomstay = auxRegimenPrimerRoomstay.split("#CONCATENADO#");
	RatePlanTypePrimerRoomstay = datosRegimenPrimerRoomstay[1];



	//---------- Recorrer cada habitacion y deshabilitar las que no tengan el mismo codigo
	var numeroRoomStays = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").seleccion_TotalRoomStays').value;
//	alert(numeroRoomStays);

	//ignoramos el primer roomstay pues es el que establece los valores
	for(j=1; j<numeroRoomStays; j++)
	{
		var totalTarifasRoomstay = eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_'+j).length;
//		alert(totalTarifasRoomstay)

		//si hay varios radiobuttons tratarlos como un array
		if (totalTarifasRoomstay != undefined)
		{
			for (t=0; t<totalTarifasRoomstay; t++)
			{
				valorSelect =  eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").regimen_'+j+'_'+t).value;
				arrayRegimen = valorSelect.split("_");
				auxRegimen = arrayRegimen[0];
				datosRegimen = auxRegimen.split("#CONCATENADO#");
				RatePlanType = datosRegimen[1];


				//Seleccionar para cada habitacion, el mismo tipo que en la primera comparando el codigo del regimen
				if (RatePlanTypePrimerRoomstay == RatePlanType)
				{
					eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_'+j+'[t]').checked=true;
				}
				else
				{
					eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_'+j+'[t]').checked=false;
				}

				//Dejar los radiobuttons y select disabled para no poder cambiarlos
				eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_'+j+'[t]').disabled=true;
				eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").regimen_'+j+'_'+t).disabled=true;
				establecerHabitacionRegimen(indice, i, j, t);
			}
		}
		else //si hay un solo radiobutton trabajar directamente con el
		{
			valorSelect =  eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").regimen_'+j+'_0').value;
			arrayRegimen = valorSelect.split("_");
			auxRegimen = arrayRegimen[0];
			datosRegimen = auxRegimen.split("#CONCATENADO#");
			RatePlanType = datosRegimen[1];

			//Seleccionar para cada habitacion, el mismo tipo que en la primera comparando el codigo del regimen
			if (RatePlanTypePrimerRoomstay == RatePlanType)
			{
				eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_'+j).checked=true;
			}
			else
			{
				eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_'+j).checked=false;
			}

			//Dejar los radiobuttons y select disabled para no poder cambiarlos
			eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").habitacion_'+j).disabled=true;
			eval('document.getElementById("formularioReservarTarifas_'+indice+'_'+i+'").regimen_'+j+'_0').disabled=true;

			establecerHabitacionRegimen(indice, i, j, 0);
		}
	}
}




//**********************************************************************************
//	EVALUAR formas de pago para ocultar o mostrar la capa de tarjeta de crédito
function evaluarPago()
{
	//si hay varios radiobuttons tratarlos como un array
	if (eval('document.getElementById("formularioReserva").pago').length != undefined)
	{
		for (j=0; j<eval('document.getElementById("formularioReserva").pago').length; j++)
		{
			if (eval('document.getElementById("formularioReserva").pago[j]').checked == true)
				modoPago = eval('document.getElementById("formularioReserva").pago[j]').value;
		}
	}
	else //si hay un solo radiobutton trabajar directamente con el
		modoPago = eval('document.getElementById("formularioReserva").pago').value;

	switch (modoPago)
	{
		//tpv pagoPrepago pagoCredito pagoBonoTalon pagoDirectoHotel pagoDirectoHotel pagoDirectoMomento
		case 'tpv':
		case 'transferencia':
		case 'reserva24h':
		case 'prepago':
		case 'credito':
		case 'bonoTalon':
								document.getElementById('creditCard').style.display='none';
								break;

		case 'directoOficina':
		case 'directoHotel':
		case 'directoMomento':
								document.getElementById('creditCard').style.display='block';
								break;
	}
}


function evaluarPagoVuelos()
{
	//si hay varios radiobuttons tratarlos como un array
	if (eval('document.getElementById("formularioReserva").pago').length != undefined)
	{
		for (j=0; j<eval('document.getElementById("formularioReserva").pago').length; j++)
		{
			if (eval('document.getElementById("formularioReserva").pago[j]').checked == true)
				modoPago = eval('document.getElementById("formularioReserva").pago[j]').value;
		}
	}
	else //si hay un solo radiobutton trabajar directamente con el
		modoPago = eval('document.getElementById("formularioReserva").pago').value;

	switch (modoPago)
	{
		//tpv pagoPrepago pagoCredito pagoBonoTalon pagoDirectoHotel pagoDirectoHotel pagoDirectoMomento
		case 'efectivo':
		case 'tpv':
								document.getElementById('creditCard').style.display='none';
								document.getElementById('creditCardCorporativas').style.display='none';
								break;

		case 'tarjetaCorporativa':
								document.getElementById('creditCard').style.display='none';
								document.getElementById('creditCardCorporativas').style.display='block';
								break;

		case 'tarjetaCliente':
								document.getElementById('creditCard').style.display='block';
								document.getElementById('creditCardCorporativas').style.display='none';
								break;
	}
}




function imprimirBonos(capa, printCSS)
{
	var ventana = window.open('', '', 'width=850, height=400, top=50, left=100, menubar=0');
	var contenido = '<html>'
				+		'<head>'
				+			'<link type="text/css" href="'+printCSS+'css/mailer.css" rel="stylesheet" />'
				+		'</head>'
				+		'<body onload="window.print(); window.close();">'
				+ 			document.getElementById(capa).innerHTML
				+ 		'</body>'
				+	'</html>';
	ventana.document.open();
	ventana.document.write(contenido);
	ventana.document.close();
}

//---------------------------------------------------------------------------------------------
// Actualizar los datos del formulario a partir del calendario de vuelos
//---------------------------------------------------------------------------------------------

function datosCalendarioVuelosAux(x, i)
{
	var campoOrigen = 'campoOrigen_'+x+'_'+i;
	var campoDestino = 'campoDestino_'+x+'_'+i;
	var campoOrigenIATA = 'campoOrigenIATA_'+x+'_'+i;
	var campoDestinoIATA = 'campoDestinoIATA_'+x+'_'+i;
	var campoFecha = 'campoFecha_'+x+'_'+i;
	var campoFechaVuelta = 'campoFechaVuelta_'+x+'_'+i;
	var campoTipo = 'campoTipo_'+x+'_'+i;

	//	Con estos indices coger datos de los campos ocultos
	origen = document.getElementById(campoOrigen).value;
	destino = document.getElementById(campoDestino).value;
	origenIATA = document.getElementById(campoOrigenIATA).value;
	destinoIATA = document.getElementById(campoDestinoIATA).value;
	fecha = document.getElementById(campoFecha).value;
	fechaVuelta = document.getElementById(campoFechaVuelta).value;
	tipo = document.getElementById(campoTipo).value;

	//con esos datos llamar a la funcion real
	datosCalendarioVuelos(origen,destino,origenIATA,destinoIATA,fecha,fechaVuelta,tipo);
}

function datosCalendarioVuelos(origen,destino,origenIATA,destinoIATA,fecha,fechaVuelta,tipo)
{
	if (origenIATA != ''){
		document.getElementById('aer_origen').value = origen + ' ('+origenIATA+')';
		document.getElementById('aux_origen').value = origen + ' ('+origenIATA+')';
	}
	else{
		document.getElementById('aer_origen').value = origen;
		document.getElementById('aux_origen').value = origen;
	}

	if (destinoIATA != ''){
		document.getElementById('aer_destino').value=destino + ' ('+destinoIATA+')';
		document.getElementById('aux_destino').value = destino + ' ('+destinoIATA+')';
	}
	else{
		document.getElementById('aer_destino').value=destino;
		document.getElementById('aux_destino').value = destino;
	}

	document.getElementById('aer_origen_value').value=origenIATA;
	document.getElementById('aer_destino_value').value=destinoIATA;
	document.getElementById('FechaInicio2').value=fecha;
	if (tipo=="ida") {
		document.getElementById('oneway').checked=true;
		document.getElementById('rowFechaVuelta').style.display = 'none';
	}
	else {
		document.getElementById('FechaFin2').value=fechaVuelta;
		document.getElementById('oneway').checked=false;
		document.getElementById('rowFechaVuelta').style.display = 'block';

	}
	document.getElementById('aer_origen').focus();

	ocultarCapa('dialogoGeneral');
}

//---------------------------------------------------------------------------------------------
// Actualizar los datos del formulario a partir del calendario de hoteles
//---------------------------------------------------------------------------------------------

function datosCalendarioHotelesAux(x, i)
{
	var campoDestino = 'campoDestino_'+x+'_'+i;
	var campoDestinoId = 'campoDestinoId_'+x+'_'+i;
	var campoFechaEntrada = 'campoFechaEntrada_'+x+'_'+i;
	var campoFechaSalida = 'campoFechaSalida_'+x+'_'+i;

	//	Con estos indices coger datos de los campos ocultos
	destino = document.getElementById(campoDestino).value;
	destinoId = document.getElementById(campoDestinoId).value;
	fechaEntrada = document.getElementById(campoFechaEntrada).value;
	fechaSalida = document.getElementById(campoFechaSalida).value;

	//con esos datos llamar a la funcion real
	datosCalendarioHoteles(destino,destinoId,fechaEntrada,fechaSalida);
}

function datosCalendarioHoteles(destino,destinoId,fechaEntrada,fechaSalida)
{
	document.getElementById('destino').value=destino;
	document.getElementById('aux_destino').value=destino;
	document.getElementById('destino_value').value=destinoId;
	document.getElementById('FechaInicio').value=fechaEntrada;
	document.getElementById('FechaFin').value=fechaSalida;

	document.getElementById('destino').focus();

	ocultarCapa('dialogoGeneral');
}

//---------------------------------------------------------------------------------------------
// Posiciona capa de opciones de calendario
//---------------------------------------------------------------------------------------------
function posicionarCapaCalendario(capa, elementoReferencia, tipoProducto)
{
	var objetoReferencia = document.getElementById(elementoReferencia);
	var elemento_posX = findPosX(objetoReferencia);
	var elemento_posY = findPosY(objetoReferencia);

	if (tipoProducto=="vuelos") {
		var posX = elemento_posX-18;
		var posY = elemento_posY-615;
	}
	else {
		var posX = elemento_posX-23;
		var posY = elemento_posY-398;
	}

	document.getElementById(capa).style.left = posX + 'px';
	document.getElementById(capa).style.top = (posY) + 'px';
	document.getElementById(capa).style.zIndex = 3;
}



//---------------------------------------------------------------------------------------------
// Sumar días a una fecha dd/mm/AAAA
//---------------------------------------------------------------------------------------------
var aFinMes = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

function finMes(nMes, nAno){
	return aFinMes[nMes - 1] + (((nMes == 2) && (nAno % 4) == 0)? 1: 0);
}

function padNmb(nStr, nLen, sChr){
	var sRes = String(nStr);
	for (var i = 0; i < nLen - String(nStr).length; i++)
	sRes = sChr + sRes;
	return sRes;
}

function makeDateFormat(nDay, nMonth, nYear){
	var sRes;
	sRes = padNmb(nDay, 2, "0") + "/" + padNmb(nMonth, 2, "0") + "/" + padNmb(nYear, 4, "0");
	return sRes;
}

function incDate(sFec0){
	var nDia = parseInt(sFec0.substr(0, 2), 10);
	var nMes = parseInt(sFec0.substr(3, 2), 10);
	var nAno = parseInt(sFec0.substr(6, 4), 10);
	nDia += 1;
	if (nDia > finMes(nMes, nAno)){
		nDia = 1;
		nMes += 1;
		if (nMes == 13){
			nMes = 1;
			nAno += 1;
		}
	}
	return makeDateFormat(nDia, nMes, nAno);
}

function decDate(sFec0){
	var nDia = Number(sFec0.substr(0, 2));
	var nMes = Number(sFec0.substr(3, 2));
	var nAno = Number(sFec0.substr(6, 4));
	nDia -= 1;
	if (nDia == 0){
		nMes -= 1;
		if (nMes == 0){
			nMes = 12;
			nAno -= 1;
		}
		nDia = finMes(nMes, nAno);
	}
	return makeDateFormat(nDia, nMes, nAno);
}

function addToDate(sFec0, sInc){
	var nInc = Math.abs(parseInt(sInc));
	var sRes = sFec0;
	if (parseInt(sInc) >= 0)
		for (var i = 0; i < nInc; i++) sRes = incDate(sRes);
	else
		for (var i = 0; i < nInc; i++) sRes = decDate(sRes);
	return sRes;
}


function mostrarOfertas(imagen)
{
    urlImagenPortada = "images/"+imagen;
    document.getElementById('capaImagen').style.backgroundImage = "url(\""+urlImagenPortada+"\")";


    switch(imagen) {

	case 'estambul.jpg': document.getElementById('textoOfertaBanner').innerHTML = 'Estambul desde 120 &euro;';
		break;
	case 'paris.jpg': document.getElementById('textoOfertaBanner').innerHTML = 'Paris desde 22 &euro;';
		break;
	case 'florencia.jpg': document.getElementById('textoOfertaBanner').innerHTML = 'Florencia desde 50 &euro;';
		break;
	case 'egipto.jpg': document.getElementById('textoOfertaBanner').innerHTML = 'El Cairo desde 150 &euro;';
		break;
	case 'rio.jpg': document.getElementById('textoOfertaBanner').innerHTML = 'Rio de Janeiro desde 120 &euro;';
		break;
	case 'habana.jpg': document.getElementById('textoOfertaBanner').innerHTML = 'La Habana desde 340 &euro;';
		break;

    }

}

function playVisor()
{
    mostrarOfertas(arrayOfertas[indOferta]);
    indOferta++ ;
    if (indOferta == arrayOfertas.length) indOferta = 0;

    switch(indOferta) {

	case 1: document.getElementById('textoOfertaBanner').innerHTML = 'Estambul desde 120 &euro;';
		break;
	case 2: document.getElementById('textoOfertaBanner').innerHTML = 'Paris desde 22 &euro;';
		break;
	case 3: document.getElementById('textoOfertaBanner').innerHTML = 'Florencia desde 50 &euro;';
		break;
	case 4: document.getElementById('textoOfertaBanner').innerHTML = 'El Cairo desde 150 &euro;';
		break;
	case 5: document.getElementById('textoOfertaBanner').innerHTML = 'Rio de Janeiro desde 120 &euro;';
		break;
	case 0: document.getElementById('textoOfertaBanner').innerHTML = 'La Habana desde 340 &euro;';
		break;

    }

    t=setTimeout("playVisor()",5000);
}

function pauseVisor()
{
    clearTimeout(t);
}


function visorOfertas(path)
{
    var accion = document.getElementById('accion').value;

    if (accion == 'play')
    {
        playVisor();

        //Cambiar accion a pause
        document.getElementById('accion').value = 'pause';
        document.getElementById('imagenSlide').src ='images/pause.jpg';
        document.getElementById('accionBanner').innerHTML = 'Pause';


    }
    else
    {
        pauseVisor()

        //Cambiar accion a play
        document.getElementById('accion').value = 'play';
        document.getElementById('imagenSlide').src ='images/pause.jpg';
        document.getElementById('accionBanner').innerHTML = 'Play';
    }
}


function playProveedores()
{

    indProveedores++ ;
    if (indProveedores == 4) indProveedores = 0;
    var aux = indProveedores%3;
    if (aux==0) {

	document.getElementById('carrusel_tres').style.display='block';
	document.getElementById('carrusel_dos').style.display='none';
	document.getElementById('carrusel_uno').style.display='none';

    }
    if (aux==1) {

	document.getElementById('carrusel_dos').style.display='block';
	document.getElementById('carrusel_tres').style.display='none';
	document.getElementById('carrusel_uno').style.display='none';

    }

    if (aux==2) {
	document.getElementById('carrusel_tres').style.display='none';
	document.getElementById('carrusel_dos').style.display='none';
	document.getElementById('carrusel_uno').style.display='block';

    }

    t=setTimeout("playProveedores()",3000);
}



function fechasFlexiblesVuelos(variacion, trayecto)
{
//	alert('variacion '+trayecto+' de '+variacion+' dias')

	document.getElementById('formularioPaginacion').paginaActual.value='1';
	if (trayecto=='ida')
	{
		document.getElementById('formularioPaginacion').variacionFechaIda.value = variacion;
	}
	else
	{
		document.getElementById('formularioPaginacion').variacionFechaVuelta.value = variacion;
	}
	document.getElementById('formularioPaginacion').submit();
}

/***********************************************************************************************************************************************************/



	// Inicialización de variables.
    var map      = null;
    var geocoder = null;

    function load() {                                      // Abre LLAVE 1.
      if (GBrowserIsCompatible()) {			   // Abre LLAVE 2.
        map = new GMap2(document.getElementById("map"));

        map.setCenter(new GLatLng(37.567236,-1.803499), 15);
        map.addControl(new GSmallMapControl());


        geocoder = new GClientGeocoder();


      } // Cierra LLAVE 1.
    }   // Cierra LLAVE 2.

   	 //---------------------------------//
    	//           GEOCODER
	//---------------------------------//
/***********************************************************************************************************************************************************/

    function showAddress(address, zoom) {
    	if (geocoder) {
        	geocoder.getLatLng(address,
          		function(point) {
            		if (!point) {
            			alert(address + " not found");
            		} else {
            			map.setCenter(point, zoom);
            			var marker = new GMarker(point);
            			map.addOverlay(marker);
            			if (isset(document.getElementById("latitud")))
            				document.getElementById("latitud").value = point.x;
            			if (isset(document.getElementById("longitud")))
       			        	document.getElementById("longitud").value = point.y;
               		}
               	}
        	);
      	}
     }
    	//---------------------------------//
     	//     FIN DE GEOCODER
	//---------------------------------//






//---------------------------------------------------------------------------------------------
// Residentes - vuelos
//---------------------------------------------------------------------------------------------
function addOpt(oCntrl, iPos, sTxt, sVal){
 	var selOpcion=new Option(sTxt, sVal);
 	eval(oCntrl.options[iPos]=selOpcion);
}
function Select_Resi(mezcla)
{
	var formulario = 'formularioBusqueda';

	var campo_residentes = eval('document.getElementById("'+formulario+'").residentes');

	if (isset(campo_residentes))
	{
		while (campo_residentes.length) campo_residentes.remove(0);
		addOpt(campo_residentes,  0, "No soy residente", "no");

		switch (mezcla)
		{
			case 'a':
			case 'aa':
						campo_residentes.length=2;
						addOpt(campo_residentes,  1, "Baleares", "BL");
						break;
			case 'b':
			case 'bb':
						campo_residentes.length=2;
						addOpt(campo_residentes,  1, "Canarias", "CA");
						break;
			case 'c':
			case 'cc':
						campo_residentes.length=2;
						addOpt(campo_residentes,  1, "Ceuta", "CE");
						break;
			case 'd':
			case 'dd':
						campo_residentes.length=2;
						addOpt(campo_residentes,  1, "Melilla", "ME");
						break;
			case 'ab':
			case 'ba':
						campo_residentes.length=3;
						addOpt(campo_residentes,  1, "Baleares", "BL");
						addOpt(campo_residentes,  2, "Canarias", "CA");
						break;
			case 'ac':
			case 'ca':
						campo_residentes.length=3;
						addOpt(campo_residentes,  1, "Baleares", "BL");
						addOpt(campo_residentes,  2, "Ceuta", "CE");
						break;
			case 'ad':
			case 'da':
						campo_residentes.length=3;
						addOpt(campo_residentes,  1, "Baleares", "BL");
						addOpt(campo_residentes,  2, "Melilla", "ME");
						break;
			case 'bc':
			case 'cb':
						campo_residentes.length=3;
						addOpt(campo_residentes,  1, "Canarias", "CA");
						addOpt(campo_residentes,  2, "Ceuta", "CE");
						break;
			case 'bd':
			case 'db':
						campo_residentes.length=3;
						addOpt(campo_residentes,  1, "Canarias", "CA");
						addOpt(campo_residentes,  2, "Melilla", "ME");
						break;
			case 'cd':
			case 'dc':
						campo_residentes.length=3;
						addOpt(campo_residentes,  1, "Ceuta", "CE");
						addOpt(campo_residentes,  2, "Melilla", "ME");
						break;
			default:
						break;
		}
	}
}


function comprobarAeropuertoResidente(aeropuerto)
{
	var valor='';
	var codigo=0;

	if (   (aeropuerto=='MENORCA, MENORCA, ESPAÑA, (MAH)')
		|| (aeropuerto=='IBIZA, IBIZA, ESPAÑA, (IBZ)')
		|| (aeropuerto=='PALMA MALLORCA, PALMA MALLORCA, ESPAÑA, (PMI)')
		|| (aeropuerto=='IBZ')
		|| (aeropuerto=='MAH')
		|| (aeropuerto=='PMI')
		|| (aeropuerto=='menorca')
		|| (aeropuerto=='ibiza')
		|| (aeropuerto=='palma mallorca')
		|| (aeropuerto=='ibz')
		|| (aeropuerto=='mah')
		|| (aeropuerto=='pmi'))
	{
		valor='a';
		codigo=1;
   	}
   	else
   		if (   (aeropuerto=='LOS RODEOS, TENERIFE, ESPAÑA, (TFN)')
   			|| (aeropuerto=='REINA SOFIA, TENERIFE, ESPAÑA, (TFS)')
   			|| (aeropuerto=='TENERIFE (TODOS), TENERIFE, ESPAÑA, (TCI)')
   			|| (aeropuerto=='TENERIFE (TODOS)')
   			|| (aeropuerto=='HIERRO VALVERDE, VALVERDE, ESPAÑA, (VDE)')
   			|| (aeropuerto=='LA PALMA, SANTA CRUZ PALMA, ESPAÑA, (SPC)')
   			|| (aeropuerto=='LANZAROTE, LANZAROTE, ESPAÑA, (ACE)')
   			|| (aeropuerto=='GRAN CANARIA, GRAN CANARIA, ESPAÑA, (LPA)')
   			|| (aeropuerto=='FUERTEVENTURA, FUERTEVENTURA, ESPAÑA, (FUE)')
   			|| (aeropuerto=='ACE')
   			|| (aeropuerto=='FUE')
   			|| (aeropuerto=='SPC')
   			|| (aeropuerto=='TFN')
   			|| (aeropuerto=='TFS')
   			|| (aeropuerto=='TCI')
   			|| (aeropuerto=='VDE')
   			|| (aeropuerto=='GMZ')
   			|| (aeropuerto=='LPA')
   			|| (aeropuerto=='los rodeos')
   			|| (aeropuerto=='reina sofia')
   			|| (aeropuerto=='tenerife (all)')
   			|| (aeropuerto=='tenerife (todos)')
   			|| (aeropuerto=='hierro valverde')
   			|| (aeropuerto=='la palma')
   			|| (aeropuerto=='lanzarote')
   			|| (aeropuerto=='gran canaria')
   			|| (aeropuerto=='fuerteventura')
   			|| (aeropuerto=='ace')
   			|| (aeropuerto=='fue')
   			|| (aeropuerto=='spc')
   			|| (aeropuerto=='tfn')
   			|| (aeropuerto=='tfs')
   			|| (aeropuerto=='tci')
   			|| (aeropuerto=='vde')
   			|| (aeropuerto=='gmz')
   			|| (aeropuerto=='lpa'))
   		{
			valor='b';
			codigo=1;
   		}
   		else
   			if (   (aeropuerto=='HELIPUERTO')
   				|| (aeropuerto=='JCU')
   				|| (aeropuerto=='helipuerto')
   				|| (aeropuerto=='jcu')
   				|| (aeropuerto=='CEUTA')
   				|| (aeropuerto=='ceuta'))
   			{
				valor='c';
				codigo=1;
   			}
   			else
   				if (   (aeropuerto=='MELILLA')
   					|| (aeropuerto=='MLN')
   					|| (aeropuerto=='melilla')
   					|| (aeropuerto=='mln'))
   				{
					valor='d';
					codigo=1;
   				}

   	arrayResultados = new Array();
   	arrayResultados['valor'] = valor;
   	arrayResultados['codigo'] = codigo;

   	return arrayResultados
}


function comprobarAeropuertoResidentes()
{
	var formulario = 'formularioBusqueda';
//	alert(formulario)

	var campo_origen = eval('document.getElementById("'+formulario+'").aer_origen_value').value;
	var campo_destino = eval('document.getElementById("'+formulario+'").aer_destino_value').value;

	var capaResidentes = document.getElementById("capaResidentes");
	var campo_residentes = eval('document.getElementById("'+formulario+'").residentes');

	var mezcla='';

	auxOrigen = comprobarAeropuertoResidente(campo_origen);
	origen = auxOrigen['valor']
	codigoOrigen = auxOrigen['codigo']


	auxDestino = comprobarAeropuertoResidente(campo_destino);
	destino = auxDestino['valor']
	codigoDestino = auxDestino['codigo']

	mezcla=origen+destino;

   	if (isset(campo_residentes))
   	{
		Select_Resi(mezcla);

	   	if ((codigoOrigen==1) || (codigoDestino==1))
	   	{
			capaResidentes.style.display='block';
	   	}
	   	else
	   	{
		    capaResidentes.style.display='none';
		}
	}
}
//---------------------------------------------------------------------------------------------
// Fin - Residentes - vuelos
//---------------------------------------------------------------------------------------------


function vueloAplicarIncrementosPrecio(totalPasajeros)
{
	// Precio original del vuelo
	precioVuelo = parseFloat(document.getElementById('formularioReserva').precioOriginal.value);

	//SF total Individual que tenemos inicialmente (SF + SF emision)
	serviceFeeIndividualInicial = parseFloat(document.getElementById('formularioReserva').serviceFeeIndividualInicial.value);

	// Aplicar incremento según número de maletas
	var precioMaletas = 0;
	var totalMaletas = 0;
	for (i=0; i<totalPasajeros; i++)
	{
		numeroBultos = eval("document.getElementById('formularioReserva').numeroBultos_"+i);
		if (isset(numeroBultos))
		{
			valorCampo = numeroBultos.value;
			auxDatos = valorCampo.split("#");
			unidades = parseInt(auxDatos[0]);
			precio = parseFloat(auxDatos[1]);

			if (unidades>0)
			{
				precioMaletas += precio;
				totalMaletas += unidades;
			}
		}
	}
	document.getElementById('formularioReserva').precioMaletas.value = precioMaletas.toFixed(2);
	document.getElementById('formularioReserva').totalMaletas.value = parseInt(totalMaletas);


	// Aplicar incremento según SF var
	precioServiceFeeAgencia = parseFloat(document.getElementById('formularioReserva').precioServiceFeeAgencia.value);
	precioServiceFeeAgencia = parseInt(totalPasajeros) * precioServiceFeeAgencia;
	//Restar el SF que teniamos inicialmente
	precioServiceFeeAgencia -= totalPasajeros * serviceFeeIndividualInicial;


	// Aplicar incremento según SF TPV o Tarjeta de Cliente

	//si hay varios radiobuttons tratarlos como un array
	if (eval('document.getElementById("formularioReserva").pago').length != undefined)
	{
		for (j=0; j<eval('document.getElementById("formularioReserva").pago').length; j++)
		{
			if (eval('document.getElementById("formularioReserva").pago[j]').checked == true)
				modoPago = eval('document.getElementById("formularioReserva").pago[j]').value;
		}
	}
	else //si hay un solo radiobutton trabajar directamente con el
		modoPago = eval('document.getElementById("formularioReserva").pago').value;



	precioServiceFeeTPV= 0;
	document.getElementById('etiquetaIncrementoTPV').style.display = 'none';
	document.getElementById('incrementoTPV').style.display = 'none';

	precioTarjeta = 0;
	document.getElementById('etiquetaIncrementoTarjeta').style.display = 'none';
	document.getElementById('incrementoTarjeta').style.display = 'none';

	if (modoPago=='tpv')
	{
		precioServiceFeeTPV= parseFloat(document.getElementById('precioServiceFeeTPV').value);
		//mostrar capa incremento TPV
		document.getElementById('etiquetaIncrementoTPV').style.display = 'block';
		document.getElementById('incrementoTPV').style.display = 'block';
	}
	else
	{
		if (modoPago=='tarjetaCliente')
		{
			valorRadio = document.getElementById('ccTipo').value;
//			alert(valorRadio);

			auxRadio = valorRadio.split("#");
			importePorcentaje = auxRadio[1]; //SI o NO
			valorImporte = parseFloat(auxRadio[2]);
			importeMinimo = auxRadio[3];
			importeMaximo = auxRadio[4];

			if (importePorcentaje == 'SI')
			{
				//Aplicar el porcentaje de la tarjeta sobre el total del vuelo (con SF, maletas, etc)
				totalSinTarjeta = precioVuelo + precioMaletas + precioServiceFeeTPV + precioServiceFeeAgencia;
				totalSinTarjeta = parseFloat(totalSinTarjeta);

				porcentajeVuelo = (totalSinTarjeta * valorImporte) / 100;

				//Ver si es superior al minimo e inferior al maximo si los hay
				if ((importeMinimo != '') && (porcentajeVuelo < importeMinimo))  porcentajeVuelo = importeMinimo;
				if ((importeMaximo != '') && (porcentajeVuelo > importeMaximo))  porcentajeVuelo = importeMaximo;

				precioTarjeta = parseFloat(porcentajeVuelo);
			}
			else
			{
				precioTarjeta = parseFloat(valorImporte);
			}
			document.getElementById('precioTarjetaCredito').value = precioTarjeta;

			//mostrar capa incremento Tarjeta
			document.getElementById('etiquetaIncrementoTarjeta').style.display = 'block';
			document.getElementById('incrementoTarjeta').style.display = 'block';
		}
		else
		{
			if (modoPago=='tarjetaCorporativa')
			{
				valorRadio = document.getElementById('tarjetaCorporativa').value;

				auxRadio = valorRadio.split("#");
				importePorcentaje = auxRadio[1]; //SI o NO
				valorImporte = parseFloat(auxRadio[2]);
				importeMinimo = auxRadio[3];
				importeMaximo = auxRadio[4];

				if (importePorcentaje == 'SI')
				{
					//Aplicar el porcentaje de la tarjeta sobre el total del vuelo (con SF, maletas, etc)
					totalSinTarjeta = precioVuelo + precioMaletas + precioServiceFeeTPV + precioServiceFeeAgencia;
					totalSinTarjeta = parseFloat(totalSinTarjeta);

					porcentajeVuelo = (totalSinTarjeta * valorImporte) / 100;

					//Ver si es superior al minimo e inferior al maximo si los hay
					if ((importeMinimo != '') && (porcentajeVuelo < importeMinimo))  porcentajeVuelo = importeMinimo;
					if ((importeMaximo != '') && (porcentajeVuelo > importeMaximo))  porcentajeVuelo = importeMaximo;

					precioTarjeta = parseFloat(porcentajeVuelo);
				}
				else
				{
					precioTarjeta = parseFloat(valorImporte);
				}

				document.getElementById('precioTarjetaCredito').value = precioTarjeta.toFixed(2);

				//mostrar capa incremento Tarjeta
				document.getElementById('etiquetaIncrementoTarjeta').style.display = 'block';
				document.getElementById('incrementoTarjeta').style.display = 'block';
			}
		}
	}




	total = precioVuelo + precioMaletas + precioTarjeta + precioServiceFeeTPV + precioServiceFeeAgencia;
	document.getElementById('formularioReserva').precioTotal.value = total.toFixed(2);
}




function vueloAplicarIncrementosPrecioSurface(totalPasajeros)
{
	// Precio original del vuelo
	precioVuelo = parseFloat(document.getElementById('formularioReserva').precioOriginal.value);

	//SF total Individual que tenemos inicialmente (SF + SF emision)
	serviceFeeIndividualInicial = parseFloat(document.getElementById('formularioReserva').serviceFeeIndividualInicial.value);


	// Aplicar incremento según SF var
	precioServiceFeeAgencia = parseFloat(document.getElementById('formularioReserva').precioServiceFeeAgencia.value);
	precioServiceFeeAgencia = parseInt(totalPasajeros) * precioServiceFeeAgencia;

	//Restar el SF que teniamos inicialmente
	precioServiceFeeAgencia -= totalPasajeros * serviceFeeIndividualInicial;

	total = precioVuelo + precioServiceFeeAgencia;
	document.getElementById('formularioReserva').precioTotal.value = total.toFixed(2);
}


function limpiarItinerario(i)
{
	eval("document.getElementById('aer_origenSurface_"+i+"').value = '';");
	eval("document.getElementById('aer_origenSurface_value_"+i+"').value = '';");
	eval("document.getElementById('aux_origenSurface_"+i+"').value = '';");

	eval("document.getElementById('aer_destinoSurface_"+i+"').value = '';");
	eval("document.getElementById('aer_destinoSurface_value_"+i+"').value = '';");
	eval("document.getElementById('aux_destinoSurface_"+i+"').value = '';");
}



/** fin functions.js **/

/** comienzo ajax.js **/
/**
 * Creacion objeto Ajax para cargar paginas
 *
 */
function ObjetoAjax()
{
	try
	{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e)
	{
		try
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (E)
		{
			xmlhttp = false;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined')
	{
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp
}


/**
 * Función AJAX para cargar paginas enviando parametros por POST o por GET
 *
 * Ejemplo envío parámetros por POST
 *
 * 			<form id="FormularioAjax" method="post" onsubmit="return false" action="#">
 *				<input type="hidden" id="campoParametro1" value="valor1" />
 *				<input type="hidden" id="campoParametro2" value="valor2" />
 *
 *				<a href="javascript: cargarPaginaAjax('ruta.php','capaDestino','parametro1='+document.getElementById('campoParametro1').value+'&amp;parametro2='+document.getElementById('campoParametro2').value, 'POST', 'Cargando', '../images/', 'initCapas()');">
 *					{MOSTRAR_MAPA}
 *				</a>
 *			</form>
 *
 * Ejemplo envío parámetros por GET
 *
 *			<a href: javascript: cargarPaginaAjax('ruta.php?parametro1=valor1&parametro2=valor2', 'capaDestino', '', 'get', 'Cargando...', '../images/', 'initCapas()');">ENLACE</a>
 *
 *
 *	initCapas(): funcion que vuelve a lanzar funciones que utilizaban capas cargadas mediante AJAX cuando aun no existían
 *
 *	lanzarDeNuevo: controlar si existe la capa para no lanzar el ajax de nuevo, salvo que se indique lo contrario [0/1]
 */
function cargarPaginaAjax(Url,CapaDestino,CapaDestinoInterior,Parametros,Metodo,TextoCargando,PathImages,functionFin, lanzarDeNuevo)
{
//	alert(Url);
//	alert(CapaDestino);
//	alert(CapaDestinoInterior);
//	alert(Parametros);
//	alert(Metodo);
//	alert(TextoCargando);
//	alert(PathImages);
//	alert(functionFin);

	//Controlar si existe ya la capa que vamos a cargar, y sino lanzar ajax
	if ((!(isset(document.getElementById(CapaDestinoInterior)))) || (lanzarDeNuevo==1))
	{
		var ajax=ObjetoAjax();
		var Objetivo = document.getElementById(CapaDestino);

		/*Creamos y ejecutamos la instancia si el metodo elegido es POST*/
		if(Metodo.toUpperCase()=='POST')
		{
			ajax.open ('POST', Url, true);
			ajax.onreadystatechange = function() {
				if (ajax.readyState==1)
				{
					Objetivo.innerHTML = '<br /><br /><img src="'+PathImages+'loading_small.gif" alt="'+TextoCargando+'" /> '+TextoCargando;
				}
				else
					if (ajax.readyState==4)
					{
						if(ajax.status==200)
						{
//							alert(ajax.responseText)
							Objetivo.innerHTML=ajax.responseText;
							//si indicamos functionFin llamar a esa funcion tras ejecutar el Ajax
							if (functionFin != '')
							{
								eval(functionFin);
							}
						}
						else
							if(ajax.status==404)
							{
								Objetivo.innerHTML = "La direccion no existe";
							}
							else
							{
								Objetivo.innerHTML = "Error: ".ajax.status;
							}
					}
			}
			ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			ajax.send(Parametros);
			return;
		}


		/*Creamos y ejecutamos la instancia si el metodo elegido es GET*/
		if (Metodo.toUpperCase()=='GET')
		{
			ajax.open ('GET', Url, true);
			ajax.onreadystatechange = function() {
				if (ajax.readyState==1)
				{
					Objetivo.innerHTML = '<br /><br /><img src="'+PathImages+'loading_small.gif" alt="'+TextoCargando+'" /> '+TextoCargando;
				}
				else
					if (ajax.readyState==4)
					{
						if(ajax.status==200)
						{
							Objetivo.innerHTML=ajax.responseText;
							//si indicamos functionFin llamar a esa funcion tras ejecutar el Ajax
							if (functionFin != '')
							{
								eval(functionFin);
							}
						}
						else
							if(ajax.status==404)
							{
								Objetivo.innerHTML = "La direccion no existe";
							}
							else
							{
								Objetivo.innerHTML = "Error: ".ajax.status;
							}
					}
			}
			ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			ajax.send(null);
			return
		}
	}
}


function cargarPaginaAjaxVuelos(i,CapaDestino,CapaDestinoInterior,Parametros,Metodo,TextoCargando,PathImages,functionFin)
{
	var Url = 'masInfo.php?i='+i;
//alert(Url)
	//ID trayecto de Ida
	var totalRadiosIda = eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoIda_'+i).length;

	//si hay varios radiobuttons tratarlos como un array
	if (totalRadiosIda != undefined)
	{
		for (k=0; k<totalRadiosIda; k++)
		{
			if (eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoIda_'+i+'[k]').checked == true)
			{
				valorRadioIda = eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoIda_'+i+'[k]').value;
			}
		}
	}
	else //si hay un solo radiobutton trabajar directamente con el
	{
		valorRadioIda = eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoIda_'+i).value
	}
//	alert(valorRadioIda)
	auxIda = valorRadioIda.split("#");
	idTrayectoIda = auxIda[0];
//	alert(idTrayectoIda);


	//ID trayecto de Vuelta
	idTrayectoVuelta = '';
	if (isset(eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoVuelta_'+i)))
	{
		var totalRadiosVuelta = eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoVuelta_'+i).length;

		//si hay varios radiobuttons tratarlos como un array
		if (totalRadiosVuelta != undefined)
		{
			for (k=0; k<totalRadiosVuelta; k++)
			{
				if (eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoVuelta_'+i+'[k]').checked == true)
				{
					valorRadioVuelta = eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoVuelta_'+i+'[k]').value;
				}
			}
		}
		else //si hay un solo radiobutton trabajar directamente con el
		{
			valorRadioVuelta = eval('document.getElementById("formularioElemento_'+i+'").radioTrayectoVuelta_'+i).value
		}
	//	alert(valorRadioVuelta)
		auxVuelta = valorRadioVuelta.split("#");
		idTrayectoVuelta = auxVuelta[0];
	//	alert(idTrayectoVuelta);
	}

	Url += '&idTrayectoIda='+idTrayectoIda+'&idTrayectoVuelta='+idTrayectoVuelta+'&';

	cargarPaginaAjax(Url,CapaDestino,CapaDestinoInterior,Parametros,Metodo,TextoCargando,PathImages,functionFin, 1)
}

function PintaCalendario ()
{
	var ajax=ObjetoAjax();

	fecha_inicio = document.calendario.fecha_inicio.value;
	fecha_fin = document.calendario.fecha_fin.value;
	destino = document.calendario.destinoCalendario.value;

	if (isset(document.calendario.fecha_in)) fecha_in=document.calendario.fecha_in.value;
	else fecha_in = '';
//alert(fecha_in)
//alert(fecha_inicio)

	origen="";
	destino="";
	var duracion="";
	var tipo_vuelo="";
	var inicio_calendario="";

	if (fecha_inicio.length>10)
	{
		fecha_inicio=fecha_inicio.substr(4,10);
		fecha_fin=fecha_fin.substr(4,10);
		document.calendario.fecha_inicio.value=fecha_inicio;
		document.calendario.fecha_fin.value=fecha_fin;

	}

	switch(document.calendario.producto.value)
	{
		case 'vuelos':		origen = document.getElementById('aer_origen_cal_value').value;
							destino	= document.getElementById('aer_destino_cal_value').value;
							duracion = document.getElementById('duracion').value;
							tipo_vuelo = document.getElementById('tipo_vuelo').value;
							inicio_calendario = document.getElementById('inicioCalendario').value;
							break;

		case 'hoteles':		destino=document.getElementById('destino_calendario_value').value;
							duracion=document.getElementById('duracion').value;
	}


	ajax.open("GET", "calendarioOfertas.php?fecha_inicio="+fecha_inicio+"&fecha_fin="+fecha_fin+"&duracion="+duracion+"&fecha_in="+fecha_in+"&origen="+origen+"&destino="+destino+"&tipo_vuelo="+tipo_vuelo+"&inicio="+inicio_calendario, true);

	Objetivo = document.getElementById("capaMuestraCalendario");

	ajax.onreadystatechange = function()
	{
		if (ajax.readyState==1)
		{
			Objetivo.value="";
			Objetivo.innerHTML="&nbsp;&nbsp;Cargando calendario...";


		}
			else if(ajax.readyState==4)
			{
				if(ajax.status==200)
				{

					Objetivo.innerHTML = ajax.responseText;
				}
				else
				{
					Objetivo.innerHTML = "Error: ".ajax.status;

				}
			}
	}
	ajax.send(null);
	return

}
/** fin ajax.js **/

/** comienzo nifty.js **/
function NiftyCheck(){
if(!document.getElementById || !document.createElement)
    return(false);
isXHTML=/html\:/.test(document.getElementsByTagName('body')[0].nodeName);
if(Array.prototype.push==null){Array.prototype.push=function(){
      this[this.length]=arguments[0]; return(this.length);}}
return(true);
}

function Rounded(selector,wich,bk,color,opt){
var i,prefixt,prefixb,cn="r",ecolor="",edges=false,eclass="",b=false,t=false;

if(color=="transparent"){
    cn=cn+"x";
    ecolor=bk;
    bk="transparent";
    }
else if(opt && opt.indexOf("border")>=0){
    var optar=opt.split(" ");
    for(i=0;i<optar.length;i++)
        if(optar[i].indexOf("#")>=0) ecolor=optar[i];
    if(ecolor=="") ecolor="#666";
    cn+="e";
    edges=true;
    }
else if(opt && opt.indexOf("smooth")>=0){
    cn+="a";
    ecolor=Mix(bk,color);
    }
if(opt && opt.indexOf("small")>=0) cn+="s";
prefixt=cn;
prefixb=cn;
if(wich.indexOf("all")>=0){t=true;b=true}
else if(wich.indexOf("top")>=0) t="true";
else if(wich.indexOf("tl")>=0){
    t="true";
    if(wich.indexOf("tr")<0) prefixt+="l";
    }
else if(wich.indexOf("tr")>=0){
    t="true";
    prefixt+="r";
    }
if(wich.indexOf("bottom")>=0) b=true;
else if(wich.indexOf("bl")>=0){
    b="true";
    if(wich.indexOf("br")<0) prefixb+="l";
    }
else if(wich.indexOf("br")>=0){
    b="true";
    prefixb+="r";
    }
var v=getElementsBySelector(selector);
var l=v.length;
for(i=0;i<l;i++){
    if(edges) AddBorder(v[i],ecolor);
    if(t) AddTop(v[i],bk,color,ecolor,prefixt);
    if(b) AddBottom(v[i],bk,color,ecolor,prefixb);
    }
}

function AddBorder(el,bc){
var i;
if(!el.passed){
    if(el.childNodes.length==1 && el.childNodes[0].nodeType==3){
        var t=el.firstChild.nodeValue;
        el.removeChild(el.lastChild);
        var d=CreateEl("span");
        d.style.display="block";
        d.appendChild(document.createTextNode(t));
        el.appendChild(d);
        }
    for(i=0;i<el.childNodes.length;i++){
        if(el.childNodes[i].nodeType==1){
            el.childNodes[i].style.borderLeft="1px solid "+bc;
            el.childNodes[i].style.borderRight="1px solid "+bc;
            }
        }
    }
el.passed=true;
}

function AddTop(el,bk,color,bc,cn){
var i,lim=4,d=CreateEl("b");

if(cn.indexOf("s")>=0) lim=2;
if(bc) d.className="artop";
else d.className="rtop";
d.style.backgroundColor=bk;
for(i=1;i<=lim;i++){
    var x=CreateEl("b");
    x.className=cn + i;
    x.style.backgroundColor=color;
    if(bc) x.style.borderColor=bc;
    d.appendChild(x);
    }
el.style.paddingTop=0;
el.insertBefore(d,el.firstChild);
}

function AddBottom(el,bk,color,bc,cn){
var i,lim=4,d=CreateEl("b");

if(cn.indexOf("s")>=0) lim=2;
if(bc) d.className="artop";
else d.className="rtop";
d.style.backgroundColor=bk;
for(i=lim;i>0;i--){
    var x=CreateEl("b");
    x.className=cn + i;
    x.style.backgroundColor=color;
    if(bc) x.style.borderColor=bc;
    d.appendChild(x);
    }
el.style.paddingBottom=0;
el.appendChild(d);
}

function CreateEl(x){
if(isXHTML) return(document.createElementNS('http://www.w3.org/1999/xhtml',x));
else return(document.createElement(x));
}

function getElementsBySelector(selector){
var i,selid="",selclass="",tag=selector,f,s=[],objlist=[];

if(selector.indexOf(" ")>0){  //descendant selector like "tag#id tag"
    s=selector.split(" ");
    var fs=s[0].split("#");
    if(fs.length==1) return(objlist);
    f=document.getElementById(fs[1]);
    if(f) return(f.getElementsByTagName(s[1]));
    return(objlist);
    }
if(selector.indexOf("#")>0){ //id selector like "tag#id"
    s=selector.split("#");
    tag=s[0];
    selid=s[1];
    }
if(selid!=""){
    f=document.getElementById(selid);
    if(f) objlist.push(f);
    return(objlist);
    }
if(selector.indexOf(".")>0){  //class selector like "tag.class"
    s=selector.split(".");
    tag=s[0];
    selclass=s[1];
    }
var v=document.getElementsByTagName(tag);  // tag selector like "tag"
if(selclass=="")
    return(v);
for(i=0;i<v.length;i++){
    if(v[i].className.indexOf(selclass)>=0){
        objlist.push(v[i]);
        }
    }
return(objlist);
}

function Mix(c1,c2){
var i,step1,step2,x,y,r=new Array(3);
if(c1.length==4)step1=1;
else step1=2;
if(c2.length==4) step2=1;
else step2=2;
for(i=0;i<3;i++){
    x=parseInt(c1.substr(1+step1*i,step1),16);
    if(step1==1) x=16*x+x;
    y=parseInt(c2.substr(1+step2*i,step2),16);
    if(step2==1) y=16*y+y;
    r[i]=Math.floor((x*50+y*50)/100);
    }
return("#"+r[0].toString(16)+r[1].toString(16)+r[2].toString(16));
}
/** fin nifty.js **/

/** carrusel de imagenes **/
var t;
function cambiaOferta(id, stop, path)
{
	var arrayOferta = eval('arrayImagenes'+id);

	var urlImagenPortada = arrayOferta[0];
//	alert(path+"includes/muestraImagenContent.php?img="+urlImagenPortada);
	document.getElementById('capaImagen').style.backgroundImage = "url(\""+path+"includes/muestraImagenContent.php?img="+urlImagenPortada+"\")";
    document.getElementById('idOferta').value = id;
	document.getElementById('textoOfertaBanner').innerHTML = arrayOferta[1];

	if (stop == 'true') pauseCarrusel(path);
}

function playCarrusel(path)
{
    cambiaOferta(idOferta, 'false', path);
    idOferta++ ;
    if (idOferta == 7) idOferta = 1;

    t = setTimeout("playCarrusel('"+path+"')", 5000);
}

function pauseCarrusel(path){
    clearTimeout(t);

    //Cambiar accion a play
    document.getElementById('accion').value = 'play';
    document.getElementById('imagenSlide').src = path+'images/iconos/play.jpg';
    document.getElementById('accionBanner').innerHTML = 'Play';
}

function carruselOfertas(path){
    var accion = document.getElementById('accion').value;

    if (accion == 'play')
    {
        playCarrusel(path);

        //Cambiar accion a pause
        document.getElementById('accion').value = 'pause';
        document.getElementById('imagenSlide').src = path+'images/iconos/pause.jpg';
        document.getElementById('accionBanner').innerHTML = 'Pause';
    }
    else
    {
        pauseCarrusel(path);
    }
}

function OfertaToForm(){
	var id = document.getElementById('idOferta').value;
	var arrayOferta = eval('arrayImagenes'+id);
	datosCalendarioVuelos(arrayOferta[2], arrayOferta[3], arrayOferta[4], arrayOferta[5], arrayOferta[6], arrayOferta[7], arrayOferta[8]);
}
/**     fin carrusel imagenes     **/