﻿var Muchoviaje = { TransportHotel: { Temp: {}, UI: {} }, Utils: {CurrencyConverter: {}} };

//=====================================================================================//
//------------------------------------- FECHAS ----------------------------------------//
//=====================================================================================//

function dateParse(datestr) {
    if(datestr == null) {
        return null;
    }
    var match = new RegExp("(\\d{2})/(\\d{2})/(\\d{4})", "g").exec(datestr);
    var date = new Date(match[3], (match[2]-1), match[1], 0, 0, 0);
    return date;
}//dateParse

function dateToString(datestr) {
    var match = new RegExp("(\\d{2})/(\\d{2})/(\\d{4})", "g").exec(datestr);
    
    if(match == null) {
		matchISO = new RegExp("(\\d{4})(/|-)(\\d{2})(/|-)(\\d{2})", "g").exec(datestr);
		if(matchISO == null) {
			return datestr;
		} else {
			match = {3: matchISO[1], 2: matchISO[3], 1: matchISO[5]};
		}
    }
    
    var date = new Date(match[3], (match[2]-1), match[1], 0, 0, 0);
    return formatDates.replace("_DAYWEEK_", dayNames[date.getDay()]).replace("_DAY_", match[1]).replace("_MONTH_", monthNames[match[2]-1]).replace("_YEAR_", match[3])
}//dateToString

//=====================================================================================//
//----------------------------------- FIN FECHAS --------------------------------------//
//=====================================================================================//


//=====================================================================================//
//------------------------------------- ARRAYS ----------------------------------------//
//=====================================================================================//

/**
 * Utilidad para comprobar si una clave se encuentra dentro de un array
 * @param array array Array desde el que se comprobara si existe una clave dentro de el
 * @param string key Clave a comprobar dentro del array
 * @return bool true cuando se encuentre la clave, false cuando no
 */
function inArray(array, key) {
	for(var i in array) {
		if(i == key) {
			return true;
		}
	}
	return false;
}//inArray

//=====================================================================================//
//----------------------------------- FIN ARRAYS --------------------------------------//
//=====================================================================================//


//=====================================================================================//
//-------------------------------------- AJAX -----------------------------------------//
//=====================================================================================//

/**
 * La ya clasica funcion de MrProper, para utilizar ajax al mas bajo nivel para operaciones rapidas
 * sin la necesidad de usar frameworks que ralentizan el proceso.
 */
function DonLimpioMrProper() {
	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;
}

//=====================================================================================//
//------------------------------------ END AJAX ---------------------------------------//
//=====================================================================================//


//=====================================================================================//
//--------------------------------- AUTOCOMPLETADO ------------------------------------//
//=====================================================================================//

/**
 * Carga los aeropuertos en el autocompleta en base al texto introducido en el input con id pasado por parametro
 * @param string name Id del elemento, generalmente input, desde el que se va a activar el suggest o autocompleta.
 */
function LoadAirports(name) {
	data = document.getElementById(name).value;

	if (data.length > 2) {
	
		DonLimpio = DonLimpioMrProper();
		path = "/vuelos/controles/aeropuertosAutocompleta.aspx?name=" + data;
		DonLimpio.open("GET", path, true);
		 
		DonLimpio.onreadystatechange = function() {
			if (DonLimpio.readyState == 1){}
			else if(DonLimpio.readyState == 4) {
				if(DonLimpio.status == 200){
					 if(!inArray(__AutoComplete, name)) {
						if(name == "departure" || name == "arrival") {
							autoWidth = "260";
						} else {
							autoWidth = "549";
						}
						
						AutoComplete_Create(name, eval(DonLimpio.responseText), {"keypress":"LoadAirports(\"" + name + "\");", "layerName":"layerAutocomplete_" + name, "layerWidth":autoWidth});
						
					} else {
						__AutoComplete[name]["data"] = eval(DonLimpio.responseText);
					}
				}
			}
		}
		DonLimpio.send(null);
	}
}




function LoadAutocompleteItems(name) {
	data = document.getElementById(name).value;

	if (data.length > 2) {
	
		DonLimpio = DonLimpioMrProper();
		path = "/vuelos/engine/service.aspx?type=autocomplete&name=" + data;
		DonLimpio.open("GET", path, true);
		 
		DonLimpio.onreadystatechange = function() {
			if (DonLimpio.readyState == 1){}
			else if(DonLimpio.readyState == 4) {
				if(DonLimpio.status == 200){
					 if(!inArray(__AutoComplete, name)) {
						AutoComplete_Create(name, eval(DonLimpio.responseText), {"keypress":"LoadAutocompleteItems(\"" + name + "\");", "layerName":"layerAutocomplete_" + name, "layerWidth":"230"});
					} else {
						__AutoComplete[name]["data"] = eval(DonLimpio.responseText);
					}
				}
			}
		}
		DonLimpio.send(null);
	}
}
//=====================================================================================//
//------------------------------- FIN AUTOCOMPLETADO ----------------------------------//
//=====================================================================================//



//=====================================================================================//
//----------------------------------- BUSCADORES --------------------------------------//
//=====================================================================================//

/**
 * Muestra u oculta los combos de edades de los niños en base al numero de niños seleccionado en el
 * combo de niños
 */
function drawChildAgesCombos() {

	var i;
	var trace;
	var childs = document.getElementById("formChilds").value;

	for(i = 1; i <= childs; i++) {
		document.getElementById("formChildAge" + i).style.display = "inline-block";
		//document.getElementById("formChildAge" + i).style.visibility = "visible";
	}
	
	for(i = parseInt(childs) + 1; i <= 9; i++) {
		document.getElementById("formChildAge" + i).style.display = "none";
		//document.getElementById("formChildAge" + i).style.visibility = "hidden";
	}
	
	if(childs == 0) {
		document.getElementById("labelChildsAge").style.display = "none";
		//document.getElementById("labelChildsAge").style.visibility = "hidden";
	} else {
		document.getElementById("labelChildsAge").style.display = "block";
		//document.getElementById("labelChildsAge").style.visibility = "visible";
	}
}//drawChildAgesCombos


function showFrecuentAirports(airport) {
	LayerAirportsName = airport;
	elementOrigin = document.getElementById(airport);
	
    var position = $('#departure').position();
	var left = position.left;
	var tope = position.top;

	var layer = document.getElementById('layerCities');
	layer.style.top = tope + "px";
	layer.style.left = left + "px";
	layer.style.display = "block";
}//showFrecuentAirports

function loadAirportsList(type, code) {
	switch (type) {
		case "PS": //Listar aeropuertos del pais
			params = "country=" + code;
		break;
		case "CT": //Listar paises del continente
			params = "continent=" + code;
		break;
		case "WL": //Listar continentes del mundo
			params = "";
		break;
		case "CL": //Cerramos la capa
			document.getElementById("layerListAirports").style.display = "none";
			return;
		break;
		case "AP":
			document.getElementById(LayerAirportsName).value = code;
			loadAirportsList("CL", "");
			return;
		break;
		default:
			//alert("No implementado");
			return;
	}


	url = "/vuelos/controles/aeropuertosAjax.aspx?" + params;
	objetivo = "layerListAirportsData"
	
	DonLimpio = DonLimpioMrProper();
	DonLimpio.open("GET", url, true);
		 
	DonLimpio.onreadystatechange = function() {
		if (DonLimpio.readyState == 1){}
		else if(DonLimpio.readyState == 4) {
			if(DonLimpio.status == 200){
				document.getElementById(objetivo).innerHTML = DonLimpio.responseText;
				
                var position = $('#departure').position();
	            var left = position.left;
	            var tope = position.top;
				

				var layer = document.getElementById('layerListAirports');
				layer.style.top = tope + "px";
				layer.style.left = left + "px";
				layer.style.display = "block";
				
				//document.getElementById("layerListAirports").style.display = "block"
				document.getElementById("layerCities").style.display = "none"
			}
		}
	}
	DonLimpio.send(null);
}

//=====================================================================================//
//--------------------------------- FIN BUSCADORES ------------------------------------//
//=====================================================================================//



//=====================================================================================//
//------------------------------------- ESPERA ----------------------------------------//
//=====================================================================================//

function showWaiter (name) {
	$('#content').hide();
	
    var widthTotal=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth); 
    var heightTotal=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight); 
    document.getElementById(name).style.width = widthTotal + "px";
    document.getElementById(name).style.height = heightTotal + "px";
    
    //Ocultamos la publicidad
    $('#topBanner').hide();
    $('.bloquePubli').hide();
    $('.PubliBottom').hide();
    
    $('#PubTop2').hide();
    
    
    
    //document.getElementById("loading").style.top = ($(window).height() - $('#loading').outerHeight())/2 + "px";
    //document.getElementById("loading").style.top = "150px";
    
    changeDisplayDiv(name);
}//showWaiter

//=====================================================================================//
//----------------------------------- FIN ESPERA --------------------------------------//
//=====================================================================================//



//=====================================================================================//
//----------------------------------- GENERALES ---------------------------------------//
//=====================================================================================//

function openObj (obj) {
    if (!obj.is(':visible')) {
        obj.slideDown(500);
    }
}//openObj

function closeObj (obj) {
    if (obj.is(':visible')) {
        obj.slideUp(500);
    }
}//openObj

function changeDisplayByObj (obj) {
    if (!obj.is(':visible')) {
        obj.slideDown(500);
    } else {
        obj.slideUp(500);
    }
}//changeDisplayDiv

function changeDisplayDiv (name) {
    if (!$('#' + name).is(':visible')) {
        $('#' + name).slideDown(500);
    } else {
        $('#' + name).slideUp(500);
    }
}//changeDisplayDiv

function changeTextInput (name, text1, text2) {
    if (!$('#' + name).value == text1) {
        $('#' + name).value = text2;
    } else {
        $('#' + name).value = text1;
    }
}//changeTextInput

function changeTextInner (name, text1, text2) {
    if ($('#' + name).html() == text1) {
        $('#' + name).html(text2);
    } else {
        $('#' + name).html(text1);
    }
}//changeTextInner

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
	        curleft += obj.offsetLeft;
	        curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return [curleft,curtop];
    }
}//findPos
//=====================================================================================//
//--------------------------------- FIN GENERALES -------------------------------------//
//=====================================================================================//


//=====================================================================================//
//--------------------------- VALIDACIÓN DE FORMULARIOS -------------------------------//
//=====================================================================================//

function validate (branch) {    
    if (document.getElementById("departure")) return validateSearch(branch);
}//validate

function validateSearch (branch) {
    var msgs = new Array();
    var i = 0;
    var now = new Date();
    now.setHours(0, 0, 0);
    var tripType = $("input[name='tripType']:checked").val();
    
    if ($('#departure').val() < 3)  {msgs[i] = messages['01010004']; i++;}
    if ($('#arrival').val() < 3 && $("#ctl00_cphPrincipal_Buscador_DropDownParks").val())    {msgs[i] = messages['01010005']; i++;}
    var dt1 = dateParse($('#dateGo').val());
    dt1.setHours(0, 0, 1);
    if (dt1 < now) {msgs[i] = messages['01010006']; i++;}
    if (tripType == 'RoundTrip') {
        var dt2 = dateParse($('#dateReturn').val());
        if (dt2 < now) {msgs[i] = messages['01010008']; i++;}
    }
    if ($('#formAdults').val() < 1) {msgs[i] = messages['01010010']; i++;}
    
    if(branch == "CO")
    {
        if(!$("#chkSearch").is(':checked')) 
        {
            msgs[i] = messages['01010015']; 
            i++;
        }
    }    
    
    var isValid = (msgs.length == 0);
    
    if (isValid) {showWaiter('esperaBusqueda2');}
    else {
        var txt = "<ul>";
        for (var i=0; i<msgs.length; i++) {txt += "<li>" + msgs[i] + "</li>";}//for i
        txt += "</ul>";
        $("#errortext").html(txt);
        openObj($("#errortext"));
        var targetOffset = findPos(document.getElementById("errortext"))[1];
        $('html,body').animate({scrollTop:0}, 'slow');        
    }
    return isValid;

}//validateSearch

//=====================================================================================//
//------------------------- FIN VALIDACIÓN DE FORMULARIOS -----------------------------//
//=====================================================================================//



function searchTransporHotel() {
	var element;
	var isValid;
	
	isValid = validateSearch();
	
	if(isValid) {
		element = document.getElementById("formBuscador");
		element.action = "http://vuelomashotel.muchoviaje.com/engine/searchconverter.ashx"
		element.submit();
	}
}


function validateColorField(element, isValid) {
    if(!isValid) {
        element.css('background-color', '#e8e8e8');
        element.focus();
    } else {
        element.css('background-color', '#ffffff');
    }
}


function validateField(id, type, invalidCounter, extra, extra2) {
    var element = $('#' + id);
    var validation = true;
    
    if(type == 'empty') {
        validation = !(jQuery.trim(element.val()) == '');
    } else if(type == 'mail') {
        validation = mailValidator(element.val());
    } else if(type == 'compare') {
        validation = (element.val() == $('#' + extra).val());
    } else if(type == 'numberlength') {
        validation = (numberValidator(element.val()) && jQuery.trim(element.val()).length >= extra);
        if(validation && extra2){
            validation = (jQuery.trim(element.val()).length <= extra2);    
        } 
    } else if(type == 'stringlength') {
        validation = (jQuery.trim(element.val()).length > extra);
        if(validation && extra2){
            validation = (jQuery.trim(element.val()).length <= extra2);    
        }    
    } else if(type == 'nif') {
        validation = (nifValidator(element.val(), extra));
    }
    
    validateColorField(element, validation);

    if(!validation) {
        invalidCounter++;
    }
    
    writeLog(id, element.val(), validation);
    
    element = null;
    validation = null;
    
    return invalidCounter;
}


var logger = '';

function writeLog(id, value, validation) {
    if(validation == true) {
        validation = 'true';
    } else {
        validation = 'false';
    }

    logger += '&' + id + '=' + value + '||' + validation;
}


function sendLog(sid, token) {
    $.get('../engine/logger.ashx?sid=' + sid + '&token=' + token + logger);
}

function validateCustomer (branch, invalidCounter) {

    var notValid = 0;

    if($('#ddblTratamiento').val() == 'XX')
    {
        notValid++;
        $("#ddblTratamiento").css("background-color","#e8e8e8");
        $("#ddblTratamiento").focus();
        
        writeLog('ddblTratamiento', $('#ddblTratamiento').val(), false);
    }
    else
    {
        $("#ddblTratamiento").css("background-color","#ffffff");
                
        writeLog('ddblTratamiento', $('#ddblTratamiento').val(), true);
    }
    notValid = validateField('txtNombre', 'empty', notValid);
    notValid = validateField('txtApellidos', 'empty', notValid);
    notValid = validateField('txtDireccionCorreo', 'mail', notValid);
    notValid = validateField('txtDireccionCorreo2', 'mail', notValid);
    notValid = validateField('txtDireccionCorreo2', 'compare', notValid, 'txtDireccionCorreo');
    
    writeLog('ddlbTipoDoc', $('#ddlbTipoDoc').val(), true);
    if(branch != "CO")
    {
        if($('#ddlbTipoDoc').val() == 'DNI') {
            notValid = validateField('txtNroDocCliente', 'nif', notValid, branch);
        } else {  
            notValid = validateField('txtNroDocCliente', 'stringlength', notValid, '6');
        }
    }
    else
    {
        if($('#ddlbTipoDoc').val() == 'NIT' || $('#ddlbTipoDoc').val() == 'PAS')
        {
            notValid = validateField('txtNroDocCliente', 'stringlength', notValid, '6', '11');
        }
        else if($('#ddlbTipoDoc').val() == 'RC')
        {
            notValid = validateField('txtNroDocCliente', 'numberlength', notValid, '10', '11');
        }
        else
        {
            notValid = validateField('txtNroDocCliente', 'numberlength', notValid, '11', '11');
        }
    }

    if($('#goProvider').val() != "AM" && $('#goProvider').val() != "RN" && $('#goProvider').val() != "AL"){
        notValid = validateField('txtDireccion', 'empty', notValid, 'txtDireccion');
        notValid = validateField('txtCiudad', 'empty', notValid, 'txtCiudad');
        notValid = validateField('txtCiudad', 'stringlength', notValid, '2', '22');        
    }

    
    
//    if($('#ddlbTipoDoc').val() == 'DNI') {
//        notValid = validateField('txtNroDocCliente', 'DNI', notValid, branch); 
//    } else {  
//        notValid = validateField('txtNroDocCliente', 'stringlength', notValid, '6');         
//    }

    if(branch != "CO") {
        notValid = validateField('txtCP', 'numberlength', notValid, '4');
        //notValid = validateField('txtObserv', 'stringlength', notValid, '2', '199');
    }
    
    notValid = validateField('txtNroTelefono', 'numberlength', notValid, '6');

    return invalidCounter + notValid;

}



function validatePassengers (pasajeros, branch, invalidCounter) {

    var notValid = 0;
    var haveAdults = false;
    var fecha = new Date();

    for(var i = 0; i < pasajeros; i++) 
    {
        if($('#ddblTratamientoPasajero_' + i).val() == 'XX')
        {
            notValid++;
            $("#ddblTratamientoPasajero_" + i).css("background-color","#e8e8e8");
            $("#ddblTratamientoPasajero_" + i).focus();
            
            writeLog('ddblTratamientoPasajero_' + i, $('#ddblTratamientoPasajero_' + i).val(), false);
        }
        else
        {
            $("#ddblTratamientoPasajero_" + i).css("background-color","#ffffff");
                    
            writeLog('ddblTratamientoPasajero_' + i, $('#ddblTratamientoPasajero_' + i).val(), true);
        }
        notValid = validateField('txtNombrePasajero_' + i, 'empty', notValid);
        notValid = validateField('txtApellido1_' + i, 'empty', notValid);

        writeLog('ddlbTipoDocPasajero_' + i, $('#ddlbTipoDocPasajero_' + i).val(), true);
        if (branch != "CO")
        {
            if($('#ddlbTipoDocPasajero_' + i).val() == 'DNI') {
                notValid = validateField('txtNroDoc_' + i, 'nif', notValid, branch); 
            } else {
                notValid = validateField('txtNroDoc_' + i, 'stringlength', notValid, '6');
            }
        }
        else
        {
            if ($('#ddlbTipoDocPasajero_' + i).val() == "NIT" || $('#ddlbTipoDocPasajero_' + i).val() == "PAS")
            {
                notValid = validateField('txtNroDoc_' + i, 'stringlength', notValid, '6', '10');
            }
            else if ($('#ddlbTipoDocPasajero_' + i).val() == "RC")
            {
                notValid = validateField('txtNroDoc_' + i, 'numberlength', notValid, '10', '11');
            }
            else
            {
                notValid = validateField('txtNroDoc_' + i, 'numberlength', notValid, '11', '11');
            }
        }
        
        if($("#ddlbFechaNacDia_" + i).val() != 99 && $("#ddlbFechaNacMes_" + i).val() != 99 && $("#ddlbFechaNacAnio_" + i).val() != 99) {
            if(!dateValidator(parseInt($("#ddlbFechaNacDia_" + i).val()), parseInt($("#ddlbFechaNacMes_" + i).val()), parseInt($("#ddlbFechaNacAnio_" + i).val()))) {
                notValid++;
                $("#ddlbFechaNacMes_" + i).css("background-color","#e8e8e8");
                $("#ddlbFechaNacDia_" + i).css("background-color","#e8e8e8");
                $("#ddlbFechaNacAnio_" + i).css("background-color","#e8e8e8");
                $("#ddlbFechaNacDia_" + i).focus();
                
                writeLog('ddlbFechaNacDia_' + i, $('#ddlbFechaNacDia_' + i).val(), false);
                writeLog('ddlbFechaNacMes_' + i, $('#ddlbFechaNacMes_' + i).val(), false);
                writeLog('ddlbFechaNacAnio_' + i, $('#ddlbFechaNacAnio_' + i).val(), false);
            } else {
                //COMPROBAR EDAD NIÑOS Y BEBES
                if($("#tipoPass_" + i).val() == "ADT")
                {
                    $("#ddlbFechaNacMes_" + i).css("background-color","#ffffff");
                    $("#ddlbFechaNacDia_" + i).css("background-color","#ffffff");
                    $("#ddlbFechaNacAnio_" + i).css("background-color","#ffffff");
                    
                    writeLog('ddlbFechaNacDia_' + i, $('#ddlbFechaNacDia_' + i).val(), true);
                    writeLog('ddlbFechaNacMes_' + i, $('#ddlbFechaNacMes_' + i).val(), true);
                    writeLog('ddlbFechaNacAnio_' + i, $('#ddlbFechaNacAnio_' + i).val(), true);
                }
                else if($("#tipoPass_" + i).val() == "CHD")//ES NIÑO
                {
                    var fecReturn = getTimestamp($("#dayReturn_" + i).val(), $("#monthReturn_" + i).val(), $("#yearReturn_" + i).val()); 
                    var fecNac = getTimestamp($("#ddlbFechaNacDia_" + i).val(), $("#ddlbFechaNacMes_" + i).val(), $("#ddlbFechaNacAnio_" + i).val());
                    var dateDif = fecReturn - fecNac;
                    var limit = 0;
                    if($("#goProvider").val() == "RN")
                    {
                        limit = 1000 * 14;
                    }
                    else
                    {
                        limit = 1000 * 12;
                    }
                    if(dateDif / 31536000 >= limit)//YA NO ES NIÑO
                    {
                        notValid++;
                        $("#ddlbFechaNacMes_" + i).css("background-color","#e8e8e8");
                        $("#ddlbFechaNacDia_" + i).css("background-color","#e8e8e8");
                        $("#ddlbFechaNacAnio_" + i).css("background-color","#e8e8e8");
                        $("#ddlbFechaNacDia_" + i).focus();
                        
                        writeLog('ddlbFechaNacDia_' + i, $('#ddlbFechaNacDia_' + i).val(), false);
                        writeLog('ddlbFechaNacMes_' + i, $('#ddlbFechaNacMes_' + i).val(), false);
                        writeLog('ddlbFechaNacAnio_' + i, $('#ddlbFechaNacAnio_' + i).val(), false);
                    }
                    else
                    {
                        $("#ddlbFechaNacMes_" + i).css("background-color","#ffffff");
                        $("#ddlbFechaNacDia_" + i).css("background-color","#ffffff");
                        $("#ddlbFechaNacAnio_" + i).css("background-color","#ffffff");
                        
                        writeLog('ddlbFechaNacDia_' + i, $('#ddlbFechaNacDia_' + i).val(), true);
                        writeLog('ddlbFechaNacMes_' + i, $('#ddlbFechaNacMes_' + i).val(), true);
                        writeLog('ddlbFechaNacAnio_' + i, $('#ddlbFechaNacAnio_' + i).val(), true);   
                    }  
                }
                else//ES BEBE
                {
                    var fecReturn = getTimestamp($("#dayReturn_" + i).val(), $("#monthReturn_" + i).val(), $("#yearReturn_" + i).val()); 
                    var fecNac = getTimestamp($("#ddlbFechaNacDia_" + i).val(), $("#ddlbFechaNacMes_" + i).val(), $("#ddlbFechaNacAnio_" + i).val());
                    var dateDif = fecReturn - fecNac;
                    var limit = 0;
                    if($("#goProvider").val() == "RN")
                    {
                        limit = 1000 * 4;
                    }
                    else
                    {
                        limit = 1000 * 2;
                    }
                    
                    if(dateDif / 31536000 >= limit)//YA NO ES BEBE
                    {
                        notValid++;
                        $("#ddlbFechaNacMes_" + i).css("background-color","#e8e8e8");
                        $("#ddlbFechaNacDia_" + i).css("background-color","#e8e8e8");
                        $("#ddlbFechaNacAnio_" + i).css("background-color","#e8e8e8");
                        $("#ddlbFechaNacDia_" + i).focus();
                        
                        writeLog('ddlbFechaNacDia_' + i, $('#ddlbFechaNacDia_' + i).val(), false);
                        writeLog('ddlbFechaNacMes_' + i, $('#ddlbFechaNacMes_' + i).val(), false);
                        writeLog('ddlbFechaNacAnio_' + i, $('#ddlbFechaNacAnio_' + i).val(), false);
                    }
                    else
                    {
                        $("#ddlbFechaNacMes_" + i).css("background-color","#ffffff");
                        $("#ddlbFechaNacDia_" + i).css("background-color","#ffffff");
                        $("#ddlbFechaNacAnio_" + i).css("background-color","#ffffff");
                        
                        writeLog('ddlbFechaNacDia_' + i, $('#ddlbFechaNacDia_' + i).val(), true);
                        writeLog('ddlbFechaNacMes_' + i, $('#ddlbFechaNacMes_' + i).val(), true);
                        writeLog('ddlbFechaNacAnio_' + i, $('#ddlbFechaNacAnio_' + i).val(), true);   
                    }  
                }
            }
            
            if(fecha.getFullYear() - parseInt($("#ddlbFechaNacAnio_" + i).val()) >= 18) {
                haveAdults = true;
            }
        } else {
            notValid++;
            $("#ddlbFechaNacMes_" + i).css("background-color","#e8e8e8");
            $("#ddlbFechaNacDia_" + i).css("background-color","#e8e8e8");
            $("#ddlbFechaNacAnio_" + i).css("background-color","#e8e8e8");
            $("#ddlbFechaNacDia_" + i).focus();
            
            writeLog('ddlbFechaNacDia_' + i, $('#ddlbFechaNacDia_' + i).val(), false);
            writeLog('ddlbFechaNacMes_' + i, $('#ddlbFechaNacDia_' + i).val(), false);
            writeLog('ddlbFechaNacAnio_' + i, $('#ddlbFechaNacAnio_' + i).val(), false);
        }
        
        //VALIDACION APIS
        writeLog('apis', $('#apis').val(), false);
        if($("#apis").val() == "True") {
            var fecha = new Date();
            var mes = fecha.getMonth();
            mes = mes + 1;
            if($("#ddlbMesCadPass_" + i).val() != 99 && $("#ddlbAnioCadPass_" + i).val() != 99 && $("#ddlbDiaCadPass_" + i).val() != 99) {
                if($("#ddlbAnioCadPass_" + i).val() < fecha.getFullYear()) {
                    notValid++;
                    $("#ddlbAnioCadPass_" + i).css("background-color","#e8e8e8");
                    $("#ddlbAnioCadPass_" + i).focus();
                    
                    writeLog('ddlbAnioCadPass_' + i, $('#ddlbAnioCadPass_' + i).val(), false);
                } else {
                    writeLog('ddlbAnioCadPass_' + i, $('#ddlbAnioCadPass_' + i).val(), true);
                    $("#ddlbAnioCadPass_" + i).css("background-color","white");
                    if(($("#ddlbAnioCadPass_" + i).val() == fecha.getFullYear()) && ($("#ddlbMesCadPass_" + i).val() < mes)) {
                        notValid++;
                        $("#ddlbMesCadPass_" + i).css("background-color","#e8e8e8");
                        $("#ddlbMesCadPass_" + i).focus();
                        writeLog('ddlbMesCadPass_' + i, $('#ddlbMesCadPass_' + i).val(), false);
                    } else {
                        writeLog('ddlbMesCadPass_' + i, $('#ddlbMesCadPass_' + i).val(), true);
                        $("#ddlbMesCadPass_" + i).css("background-color","white");
                        if(($("#ddlbAnioCadPass_" + i).val() == fecha.getFullYear()) && ($("#ddlbMesCadPass_" + i).val() == mes) && ($("#ddlbDiaCadPass_" + i).val() < fecha.getDate())) {
                            $("#ddlbDiaCadPass_" + i).css("background-color","#e8e8e8");
                            $("#ddlbDiaCadPass_" + i).focus();
                            writeLog('ddlbDiaCadPass_' + i, $('#ddlbDiaCadPass_' + i).val(), false);
                        } else {
                            $("#ddlbDiaCadPass_" + i).css("background-color","#ffffff");
                            writeLog('ddlbDiaCadPass_' + i, $('#ddlbDiaCadPass_' + i).val(), true);
                        }
                    }    
                }          
            } else {
                notValid++;
                $("#ddlbMesCadPass_" + i).css("background-color","#e8e8e8");
                $("#ddlbDiaCadPass_" + i).css("background-color","#e8e8e8");
                $("#ddlbAnioCadPass_" + i).css("background-color","#e8e8e8");
                $("#ddlbDiaCadPass_" + i).focus();
                
                writeLog('ddlbDiaCadPass_' + i, $('#ddlbDiaCadPass_' + i).val(), false);
                writeLog('ddlbMesCadPass_' + i, $('#ddlbMesCadPass_' + i).val(), false);
                writeLog('ddlbAnioCadPass_' + i, $('#ddlbAnioCadPass_' + i).val(), false);
            }
        }
        
//        if($("#ddlbTipoDocResidente_" + i).val() != 'undefined')
//        {
//            if($("#ddlbTipoDocResidente_" + i).val() != 99)
//            {
//                $("#ddlbTipoDocResidente_" + i).css("background-color","#ffffff");
//                
//                if (branch != "CO")
//                {
//                    if($('#ddlbTipoDocResidente_' + i).val() == 'DNI') {
//                        notValid = validateField('txtNroDocResidente_' + i, 'nif', notValid, branch); 
//                    } else {
//                        notValid = validateField('txtNroDocResidente_' + i, 'stringlength', notValid, '6');
//                    }
//                }
//                else
//                {
//                    if ($('#ddlbTipoDocResidente_' + i).val() == "NIT" || $('#ddlbTipoDocPasajero_' + i).val() == "PAS")
//                    {
//                        notValid = validateField('txtNroDocResidente_' + i, 'stringlength', notValid, '6', '10');
//                    }
//                    else if ($('#ddlbTipoDocResidente_' + i).val() == "RC")
//                    {
//                        notValid = validateField('txtNroDocResidente_' + i, 'numberlength', notValid, '10', '11');
//                    }
//                    else
//                    {
//                        notValid = validateField('txtNroDocResidente_' + i, 'numberlength', notValid, '11', '11');
//                    }
//                }
//            }
//            else
//            {
//                notValid++;
//                $("#ddlbTipoDocResidente_" + i).css("background-color","#e8e8e8");
//            }
//            
//            if($("#ddlbMunicipioResidente_" + i).val() == 99)
//            {
//                notValid++;
//                $("#ddlbMunicipioResidente_" + i).css("background-color","#e8e8e8");
//            }
//            else
//            {
//                $("#ddlbMunicipioResidente_" + i).css("background-color","#ffffff");
//            }
//        }
    }
    
    if($("#goProvider").val() == "TF" || $("#goProvider").val() == "VY" )
    {
        if(!haveAdults) {
            alert("Al menos un pasajero debe ser mayor de edad");
            notValid++;
            
            writeLog('haveAdults', 'false', false);
        } else {
            writeLog('haveAdults', 'true', true);
        }
    }   
    
    return invalidCounter + notValid;

}//validatePassengers

function validatePayment(branch, invalidCounter) {

    var notValid = 0;
    var fecha = new Date();


    //if($("#rdPdebito").is(':checked'))
	if (false)
    {
        if($("#ddlbEntidadBancaria").val() != "XX") 
        {
            writeLog('ddlbEntidadBancaria', $('#ddlbEntidadBancaria').val(), true);
            $("#ddlbEntidadBancaria").css("background-color","white");
            
            notValid = validateField('txtTitTarjetaPago', 'empty', notValid);
        }
        else 
        {
            writeLog('ddlbEntidadBancaria', $('#ddlbEntidadBancaria').val(), false);
            notValid++;
            $("#ddlbEntidadBancaria").css("background-color","#CAF0F4");
            $("#ddlbEntidadBancaria").focus();
        }
    }
    else
    {
        if($("#ddlbTipoTarjeta").val() != "XX_0") {
            writeLog('ddlbTipoTarjeta', $('#ddlbTipoTarjeta').val(), true);
            $("#ddlbTipoTarjeta").css("background-color","white");
            if(creditCardValidator($("#txt_NTarjeta").val(), $("#ddlbTipoTarjeta").val(), branch)) {
                writeLog('txt_NTarjeta', $('#txt_NTarjeta').val(), true);
                $("#txt_NTarjeta").css("background-color","white");            
            } else {
                notValid++;
                $("#txt_NTarjeta").css("background-color","#e8e8e8");
                $("#txt_NTarjeta").focus();   
                writeLog('txt_NTarjeta', $('#txt_NTarjeta').val(), false);
            }
            
            notValid = validateField('txtCVV', 'numberlength', notValid, '3');
        } else {
            writeLog('ddlbTipoTarjeta', $('#ddlbTipoTarjeta').val(), false);
            notValid++;
            $("#ddlbTipoTarjeta").css("background-color","#e8e8e8");
            $("#ddlbTipoTarjeta").focus();
        }

        
        notValid = validateField('txtTitTarjeta', 'empty', notValid);    

        if($("#ddlbCadTarjetaMes").val() != 99 && $("#ddlbCadTarjetaAnio").val() != 99) {
            if($("#ddlbCadTarjetaAnio").val() < fecha.getFullYear()) {
                notValid++;
                $("#ddlbCadTarjetaAnio").css("background-color","#e8e8e8");
                $("#ddlbCadTarjetaAnio").focus();
                writeLog('ddlbCadTarjetaAnio', $('#ddlbCadTarjetaAnio').val(), false);
            } else {
                writeLog('ddlbCadTarjetaAnio', $('#ddlbCadTarjetaAnio').val(), true);
                if(($("#ddlbCadTarjetaAnio").val() == fecha.getFullYear()) && ($("#ddlbCadTarjetaMes").val() < fecha.getMonth())) {
                    $("#ddlbCadTarjetaAnio").css("background-color","white");
                    notValid++;
                    $("#ddlbCadTarjetaMes").css("background-color","#e8e8e8");
                    $("#ddlbCadTarjetaMes").focus();
                    
                    writeLog('ddlbCadTarjetaMes', $('#ddlbCadTarjetaMes').val(), false);
                } else {
                    writeLog('ddlbCadTarjetaMes', $('#ddlbCadTarjetaMes').val(), true);
                    $("#ddlbCadTarjetaMes").css("background-color","white");
                }    
            }
        } else {
            notValid++;
            $("#ddlbCadTarjetaMes").css("background-color","#e8e8e8");
            $("#ddlbCadTarjetaAnio").css("background-color","#e8e8e8");
            $("#ddlbCadTarjetaMes").focus();
            
            writeLog('ddlbCadTarjetaMes', $('#ddlbCadTarjetaMes').val(), false);
            writeLog('ddlbCadTarjetaAnio', $('#ddlbCadTarjetaAnio').val(), false);
        }
    }    
    
    //nuevos campos de la tarjeta
    if(branch == "CO")
    {
        
        if ($("#ddlbTipoDocHolder").val() == "NIT" || $("#ddlbTipoDocHolder").val() == "PAS")
        {
            notValid = validateField('txtTlfHolder', 'stringlength', notValid, '6', '10');
        }
        else if ($("#ddlbTipoDocHolder").val() == "RC")
        {
            notValid = validateField('txtTlfHolder', 'numberlength', notValid, '10', '11');
        }
        else
        {
            notValid = validateField('txtTlfHolder', 'numberlength', notValid, '11', '11');
        }
        
        notValid = validateField('txtTlfHolder', 'numberlength', notValid, '6');
        
        notValid = validateField('txtMailHolder', 'mail', notValid, '6');
        
        notValid = validateField('txtDireccionHolder', 'empty', notValid);
        
        notValid = validateField('txtCiudadHolder', 'empty', notValid);
    }

    return invalidCounter + notValid;

}//validatePayment

function validateBill(branch, invalidCounter) {

    var notValid = 0;
    
    if ($("#divFactura").is(":visible")) {
        writeLog('factura', 'true', true);
        notValid = validateField('nombrefactura', 'empty', notValid);
        
        
        if(branch != "CO")
        {
            notValid = validateField('niffactura', 'stringlength', notValid, '6');
            /*if($('#ddlbtipodocfactura').val() == 'DNI') {
                notValid = validateField('niffactura', 'nif', notValid, branch);
            } else {  
                notValid = validateField('niffactura', 'stringlength', notValid, '6');
            }*/
        }
        else
        {
            if($('#ddlbtipodocfactura').val() == 'NIT' || $('#ddlbtipodocfactura').val() == 'PAS')
            {
                notValid = validateField('niffactura', 'stringlength', notValid, '6', '10');
            }
            else if($('#ddlbtipodocfactura').val() == 'RC')
            {
                notValid = validateField('niffactura', 'numberlength', notValid, '10', '11');
            }
            else
            {
                notValid = validateField('niffactura', 'numberlength', notValid, '11', '11');
            }
        }
        
        
        notValid = validateField('direccionfactura', 'empty', notValid);

        
        if($("#provinciafactura").val() != 99) {
            writeLog('provinciafactura', $('#provinciafactura').val(), true);
            if($("#ciudadfactura").val() != '') {
                writeLog('ciudadfactura', $('#ciudadfactura').val(), true);
                $("#ciudadfactura").css("background-color","white");        
                
                if(sid != "CO") {
                    if(numberValidator($("#codposfactura").val())) {
                        var tar = jQuery.trim($("#codposfactura").val()).toString();
                        if(tar.length > 4) {
                            writeLog('codposfactura', $('#codposfactura').val(), true);
                            $("#codposfactura").css("background-color","white");
                        } else {
                            writeLog('codposfactura', $('#codposfactura').val(), false);
                            notValid++;
                            $("#codposfactura").css("background-color","#e8e8e8");
                            $("#codposfactura").focus();
                        }
                    } else {
                        writeLog('codposfactura', $('#codposfactura').val(), false);
                        notValid++;
                        $("#codposfactura").css("background-color","#e8e8e8");
                        $("#codposfactura").focus();
                    }
                }
            } else {
                writeLog('ciudadfactura', $('#ciudadfactura').val(), false);
                notValid++;
                $("#ciudadfactura").css("background-color","#e8e8e8");
                $("#ciudadfactura").focus();
            }
        } else {
            writeLog('provinciafactura', $('#provinciafactura').val(), false);
            notValid++;
            $("#provinciafactura").css("background-color","#e8e8e8");
            $("#provinciafactura").focus();
        }
        
        
        notValid = validateField('telefonofactura', 'numberlength', notValid, '6');
        notValid = validateField('_mailfactura', 'mail', notValid, '6');
        
    } else {
        writeLog('factura', 'false', false);
    }    
    
    return invalidCounter + notValid;

}



function ValidateBooking(pasajeros, branch, page) {
    logger = '';
    var notValid = 0;
    var haveAdults = false;
    var fecha = new Date();
    
    //var page = 'process1';
    
    if (page == 'process' || page == 'process1') {
    
        notValid = validateCustomer(branch, notValid);
        notValid = validatePassengers(pasajeros, branch, notValid);    
    
    }
        
    if (page == 'process' || page == 'process2') {

        notValid = validatePayment(branch, notValid);
        notValid = validateBill(branch, notValid);    
    
    }

    if (page == 'process' || page == 'process2') {
    
        if(!$("#chkAcepto").is(':checked')) {
            writeLog('chkAcepto', $('#chkAcepto').val(), false);
           notValid++;
           alert('Debe aceptar las condiciones de compra');
           $("#chkAcepto").focus();
        } else {
            writeLog('chkAcepto', $('#chkAcepto').val(), true);
        }    
    
    }
    
    writeLog('notValid', notValid, true);
    
    sendLog(sid, token);
    
    
    if(notValid != 0) {
        alert('No todos los datos son correctos, revise los campos resaltados.');
        return false;
    } else {
		showWaiter("genericWaiterLayer");
        return true;
    }
}

function mailValidator(mail)
{
    if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail))
    {
        return true;
    }
    else
    {
        return false;
    }
}

function replaceAll( text, busca, reemplaza )
{
    while (text.toString().indexOf(busca) != -1)
    text = text.toString().replace(busca,reemplaza);
    return text;
}

function nifValidator(nif, branch)
{
    nif = replaceAll(nif, " ", "");
    nif = replaceAll(nif, "-", "");
    if(branch == "MV")
    {
        if(/^([0-9]{6,9})*[a-zA-Z]+$/.test(nif))
        {
            var numero = nif.substr(0,nif.length-1);
            var let = nif.substr(nif.length-1,1);
            numero = numero % 23;
            var letra='TRWAGMYFPDXBNJZSQVHLCKET';
            letra=letra.substring(numero,numero+1);
            let = let.toUpperCase();
            
            if (letra==let)
            {
                return true;
            }
            return false;
        } else {
            return false;
        }
    }
    else
    {
        if(nif.toString().length > 5)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}


function cifValidator(cif, branch)
{
    var letra = cif.charAt(0);
    var letras = 'ABCDEFGHKLMNPQS';
    var par = 0;
    var non = 0;

    if(branch == "MV")
    {
        if (isNaN(letra))
        {
            if (cif.length!=9)
            {
                //alert('El Cif debe tener 9 dígitos');
                return false;
            }
            if (letras.indexOf(letra.toUpperCase())==-1)
            {
                //alert('El comienzo del Cif no es válido');
                return false;
            }
            for (var i=2; i<8; i+=2)
            {
                par = par + parseInt(cif.charAt(i));
            }

            for (var j=1; j<9; j+=2)
            {
                var nn = 2 * parseInt(cif.charAt(j));
                if (nn > 9)
                {
                    nn = 1+(nn-10);
                }    
                
                non = non + nn;
            }
            
            var parcial = par + non;
            var control = (10 - ( parcial % 10));

            if (control != cif.charAt(8))
            {
                //alert("El Cif no es válido");
                return false;
            }
            else
            {
                return true;
            }
        }
        else
        {
            return false;
        }
     }
     else
     {
        if(cif.toString().length > 5)
        {
            return true;
        }
        else
        {
            return false;
        }
     }  
     
     return false;
}

function numberValidator(value)
{
    var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
    if(numberRegex.test(value)) 
    {
        return true;
    }
    else
    {
        return false;
    }
}

function creditCardValidator(value, codes, branch)
{
    value = replaceAll(value, " ", "");
    value = replaceAll(value, "-", "");
    
    var encontrado = false;
    var colombiaCards = new Array("9955555555555501", "9955555555555504", "9955555555555515");    
    
    if(branch == "CO")
    {
        for(var i = 0; i < colombiaCards.length && encontrado == false; i++)
        {
            if(value == colombiaCards[i])
            {
                encontrado = true;
            }
        }
    }
    
    if(!encontrado)
    {
        if(numberValidator(value))
        {        
            var tar = value.toString();
            var tam = tar.length;
            var codd = codes.split('_');
            
    //        if(tam != codd[1] || tar.substr(0, 1) != codd[0])
    //        {
    //            return false;
    //        }
            //comparo los codigos de las tarjetas VI, DD... para que cada una empiece con un digto
            //visa
            //cod = V
            //inicio = 4 
            //longitud = 16
            if(codd[0].substr(0, 1) == "V")
            {
                if(tar.substr(0, 1) != 4)
                {
                    return false;
                }
                else
                {
                    if(tam != 16)
                    {
                        return false
                    }
                    else
                    {
                        if(validaNumTarjeta(tam, tar))
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    } 
                }
            }
            //master
            //cod = C
            //inicio = 5 
            //longitud = 16  
            else if(codd[0].substr(0, 1) == "C")
            {
                if(tar.substr(0, 1) != 5)
                {
                    return false;
                }
                else
                {
                    if(tam != 16)
                    {
                        return false
                    }
                    else
                    {
                        return true;
                    } 
                }
            } 
            //American
            //cod = A
            //inicio = 3 
            //longitud = 15  
            else if(codd[0].substr(0, 1) == "A")
            {
                if(tar.substr(0, 1) != 3)
                {
                    return false;
                }
                else
                {
                    if(tam != 15)
                    {
                        return false
                    }
                    else
                    {
                        return true;
                    } 
                }
            }
            //todas las demas
            else
            {
                if(tam < 14 || tam > 16)
                {
                    return false
                }
                else
                {
                    return true;
                }
            }
        }
    }
    else
    {
        return true;
    }
}

function validaNumTarjeta(tam, nTar)
{
    var suma = 0;
    var total = "";
    for(var i = 1; i < tam + 1; i++)
    {
        var num = nTar.substr(i-1, 1);
        if(i % 2 != 0)
        {
            num = num * 2;
            if(num > 9)
            {
                num = num - 9;
            }                 
        }
        total = total + num;
    }
    
    for(var i = 0; i < tam; i++)
    {
        suma = parseInt(suma) + parseInt(total.substr(i,1));
    }
    if(suma % 10 == 0 && suma < 150)
    {
        return true;
    }
    else
    {
        return false;
    }
}

function cvvValidator(cvv, codes)
{
    var codd = codes.split('_');
    var num = cvv.toString();
    
    if(num.length == codd[2])
    {
        return true;
    }
    else
    {
        return false;
    }
}

function dateValidator(day, month, year)
{
    if(month == 4 || month == 6 || month == 9 || month == 11)
    {
        if(day == 31)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    
    else if(month == 2)
    {
        if(day == 29)
        {
            //compruebo bisiesto
            if(year % 4 == 0)
            {
                if(year % 100 == 0 && year % 400 != 0)
                {
                    return false;
                }
                return true;
            }
            return false;
        }
        else if(day > 29)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    
    else
    {
        return true;
    }
}

function abreFactura()
{
    if (!$("#divFactura").is(":visible"))
    {
        $("#divFactura").slideDown(500);
    }
    else
    {
        $("#divFactura").slideUp(500);
    }
}

function abreFrecuente(i)
{
    if (!$("#divFrecuente_" + i).is(":visible"))
    {
        $("#divFrecuente_" + i).slideDown(500);
    }
    else
    {
        $("#divFrecuente_" + i).slideUp(500);
    }
}

function codeZipValidator(prov, cod)
{
    var cp = prov.split('_');
    
    if(cod.substr(0, 2) == cp[0])
    {
        return true;
    }
    else
    {
        return false;
    }
}

function actualizaCombosBuscador()
{
    $("#rooms option").eq(0).attr("selected", true);
    for(var i=1; i<=4; i++)
    {
        $("#room" + i + " option").eq(4).attr("selected", true);
        for(var j=1; j<=3; j++)
        {            
            $("#room" + i + "ChildAge" + j + " option").eq(0).attr("selected", true);
        }
    }
}

function abreCVV()
{
    if (!$("#divCvv").is(":visible"))
    {
        $("#divCvv").slideDown(500);
    }
    else
    {
        $("#divCvv").slideUp(500);
    }
}

function cargosS(pasajeros, precio, currency, position)
{    
    var totalPersona = 0;
    var total = precio.toString().replace(",",".");
    for(var i=0; i<pasajeros; i++)
    {
        if($("#ddlbmaletas_" + i).val())
        {        
            var price = $("#ddlbmaletas_" + i).val();
            var priceSplit = new Array;
            priceSplit = price.split('_');
            
            priceSplit[1] = priceSplit[1].replace(",",".");
            total = (parseFloat(total)) + parseFloat(priceSplit[1]);
        }    
    }
    if ($("#ddlbTipoTarjeta").length) {
        var priceTarjeta = $("#ddlbTipoTarjeta").val();
        var priceTarjetaSplit = new Array;
        priceTarjetaSplit = priceTarjeta.split('_');
        priceTarjetaSplit[1] = priceTarjetaSplit[1].replace(",",".");
        
        total = (parseFloat(total)) + parseFloat(priceTarjetaSplit[1]);    
    }
    
//    var seguro = jQuery.trim($("#precioSeguro").html()).replace(",",".");
//    
//    if ($("#chkSeguroSi").attr("checked"))
//    {        
//        total = parseFloat(total) + parseFloat(seguro);
//    }
    
    total = Math.round(total * 100) / 100;    
    totalPersona = Math.round((total / pasajeros) * 100) / 100;   
    
    var format = new Muchoviaje.Utils.CurrencyConverter();
    total = format.formatCurrency(total, 2);
    totalPersona = format.formatCurrency(totalPersona, 2);
    
//    total = total.toString().replace(".",",");
//    totalPersona = totalPersona.toString().replace(".",",");   
    
    if ($("#rprice").length) {
        if(position == 1){
            $("#rprice").html(total + " " + "<ins> " + currency.toString() + "</ins>");
        }else{
            $("#rprice").html("<ins> " + currency.toString() + "</ins>" + " " + total);
        }    
    } else {
        if(position == 1){
            if ($(".literal > span").attr("class") != "spantittle")
            {
                $(".literal > span").html(total + " " + "<ins> " + currency.toString() + "</ins>");
            }
            $("#Span26").html(total + " " +  currency.toString());
        }else{
            if ($(".literal > span").attr("class") != "spantittle")
            {
                $(".literal > span").html("<ins> " + currency.toString() + "</ins>" + " " + total);
            }
            $("#Span26").html(currency.toString() + " " + total);
        }        
    }    
    
    if(position == 1){
        $("span.precio").html(total + " " + currency.toString());
    }else{
        $("span.precio").html(currency.toString() + " " + total);
    }        
    
    if(position == 1){
        $("#precioDerecha").html(total + " " + currency.toString());
        $(".porPersona > span").html(totalPersona + "<ins> " + currency.toString() + "</ins>");
    }else{
        $("#precioDerecha").html(currency.toString() + " " + total);
        $(".porPersona > span").html("<ins> " + currency.toString() + "</ins>" + " " +totalPersona);
    }    
}

//=============================================================================================
//--------------------------- Nuevo Calendario "jquery.datepicker" ----------------------------
//=============================================================================================
var goMinDate = "1";
var goMaxDate = "+1Y";
var returnMinDate = "2";
var returnMaxDate = "+1Y+3D";

function nuevosCalendarios(calendario1, calendario2, calendarioIcono1, calendarioIcono2, label1, label2){

    var $datepickerGo;
    var $datepickerReturn;

    //------------ datepicker de ida ------------
	$datepickerGo = $("#" + calendario1).datepicker({
	    dateFormat: "dd/mm/yy", //formato de la fecha
	    minDate: goMinDate, //le fecha mínima es mañana
	    maxDate: goMaxDate, //la fecha máxima seleccionable es un año a partir de hoy
	    showOtherMonths: true,
	    selectOtherMonths: true,
	    firstDay: 1,
	    dayNamesMin: [__t("DayOfWeek_7","Domingo").substring(0, 2), __t("DayOfWeek_1","Lunes").substring(0, 2), __t("DayOfWeek_2","Martes").substring(0, 2), __t("DayOfWeek_3","Miércoles").substring(0, 2), __t("DayOfWeek_4","Jueves").substring(0, 2), __t("DayOfWeek_5","Viernes").substring(0, 2), __t("DayOfWeek_6","Sábado").substring(0, 2)],
	    monthNames: [__t("month_1","Enero"),__t("month_2","Febrero"),__t("month_3","Marzo"),__t("month_4","Abril"),__t("month_5","Mayo"),__t("month_6","Junio"),__t("month_7","Julio"),__t("month_8","Agosto"),__t("month_9","Septiembre"),__t("month_10","Octubre"),__t("month_11","Noviembre"),__t("month_12","Diciembre")],
	    onSelect: function( selectedDate,inst) {
            //comprobamos que la fecha de vuelta no sea menor que la de ida
            compruebaFechas($datepickerGo, $datepickerReturn, calendario2, label2);

            //actualizamos la fecha mínima seleccionable del la fecha de vuelta
            $datepickerReturn.datepicker( "option", 'minDate', new Date( $datepickerGo.datepicker("getDate").getTime()));

	        if(label1!=""){ //comprobamos con este if si tenemos un label que actualizar
	            document.getElementById(label1).innerHTML = dateToString(document.getElementById(calendario1).value)
	        }
        }
	});

	$("#" + calendarioIcono1).click(function() {
	    //$("#" + calendario1).datepicker("show");
	    $datepickerGo.datepicker("show");
	});	
	//------------ fin datepicker de ida ------------

    //------------ datepicker de vuelta ------------
	$datepickerReturn = $("#" + calendario2).datepicker({
	    dateFormat: "dd/mm/yy", //formato de la fecha
	    minDate: returnMinDate, 
	    maxDate: returnMaxDate, //la fecha máxima seleccionable es un año a partir de hoy + 3 días
	    showOtherMonths: true,
	    selectOtherMonths: true,
	    firstDay: 1,
	    dayNamesMin: [__t("DayOfWeek_7","Domingo").substring(0, 2), __t("DayOfWeek_1","Lunes").substring(0, 2), __t("DayOfWeek_2","Martes").substring(0, 2), __t("DayOfWeek_3","Miércoles").substring(0, 2), __t("DayOfWeek_4","Jueves").substring(0, 2), __t("DayOfWeek_5","Viernes").substring(0, 2), __t("DayOfWeek_6","Sábado").substring(0, 2)],
	    monthNames: [__t("month_1","Enero"),__t("month_2","Febrero"),__t("month_3","Marzo"),__t("month_4","Abril"),__t("month_5","Mayo"),__t("month_6","Junio"),__t("month_7","Julio"),__t("month_8","Agosto"),__t("month_9","Septiembre"),__t("month_10","Octubre"),__t("month_11","Noviembre"),__t("month_12","Diciembre")],
	    onSelect: function( selectedDate,inst) {
	        if(label2!=""){//comprobamos con este if si tenemos un label que actualizar
	            document.getElementById(label2).innerHTML = dateToString(document.getElementById(calendario2).value)
	        }
	        //comprobamos que la fecha de vuelta no sea menor que la de ida
            compruebaFechas($datepickerGo, $datepickerReturn, calendario2, label2);
        }
	});

	$("#" + calendarioIcono2).click(function() {
	    $datepickerReturn.datepicker("show");
	});
	//------------ fin datepicker de vuelta ------------
}

//Función que comprueba que la fecha de vuelta sea no sea menor que la de ida.
function compruebaFechas(datepickerGo, datepickerReturn, calendario2_, label2_)
{
    var dateIda = new Date(); 
    dateIda = datepickerGo.datepicker("getDate");
    var dateVuelta = new Date();
    dateVuelta = datepickerReturn.datepicker("getDate");
    
    if(dateVuelta < dateIda) 
    {
        dateVuelta.setTime(dateIda.getTime() + (259200000)) //Sumamos a la fecha de ida tres días en milisegundos, (1000 * 60 * 60 * 24 * 3) = 259200000
        datepickerReturn.datepicker("setDate" , dateVuelta);
        if(label2_!=""){
            document.getElementById(label2_).innerHTML = dateToString(document.getElementById(calendario2_).value) //actualizamos el label de la fecha
        }
    }
}

//=============================================================================================
//------------------------- Fin Nuevo Calendario "jquery.datepicker" --------------------------
//=============================================================================================

function setValues(idOrigen, idDestino, evento){
    //si el check esta chequeado
    if(evento == 0){
        if($("#chkDatosComprador").is(':checked')){    
            if($("#" + idOrigen).val() != ""){
                $("#" + idDestino).val($("#" + idOrigen).val());
            }
        }
    }
}

function getTimestamp(day, month, year)
{
    var dia_aux = parseInt(day,10);
    var mes_aux = parseInt(month,10);
    var ano_aux = parseInt(year,10);
    var fecha = new Date();
    fecha.setFullYear(ano_aux);
    fecha.setMonth(mes_aux-1);
    fecha.setDate(dia_aux);
    fecha.setHours(0);
    fecha.setMinutes(0);
    fecha.setSeconds(0);
    fecha.setMilliseconds(0);
    var timestamp = parseInt(fecha.getTime(),10);
     
    return timestamp;
}

function showCard()
{
    if($("#rdPdebito").is(':checked'))
    {
        if (!$("#divDebito").is(":visible"))
        {
            $("#divCredito").slideUp(500);
            $("#divDebito").slideDown(500);
        }
    }
    else
    {
        if (!$("#divCredito").is(":visible"))
        {
            $("#divCredito").slideDown(500);
            $("#divDebito").slideUp(500);
        }    
    }
}

function ocultarDep()
{
    if($("#ddlbPaisHolder").val() != "CO")
     {
        $("#ddlbEstadoHolder").css("display", "none");
        $("#pEstadoHolder").css("display", "none");
     }
     else
     {
        $("#ddlbEstadoHolder").css("display", "block");
        $("#pEstadoHolder").css("display", "block");
     }
}
