function initKeys() {
    window.setTimeout(function() {
        $(document.documentElement).focus();
        $(document.documentElement).blur();
        $(window).focus();
        //         $(document).focus();
    }, 0);
    $(document.documentElement).keydown(function(event) {
        isIframe = true;
        if (event.keyCode == '27') {
            event.preventDefault();
            close_layers();
        }

    });
}
function showLabel(event, spanId, offX, offY) {
    close_layers();
    var posx = 0;
    var posy = 0;

    if (!(offX)) {
        offX = 15;
    }

    if (!(offY)) {
        offY = 5;
    }

    if (event.pageX || event.pageY) {
        posx = event.pageX;
        posy = event.pageY;
    }
    else if (event.clientX || event.clientY) {
        posx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        posy = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    var mySpan = document.getElementById(spanId);
    mySpan.style.display = "block";
    mySpan.style.top = posy + offY + "px";
    mySpan.style.left = posx + offX + "px";
}
function showStaticLabel(labelId) {
    try {
        document.getElementById(labelId).style.display = 'block';
        document.getElementById(labelId).style.visibility = 'visible';
    } catch (e) {
        //throwError(e, 'showStaticLabel', arguments);
    }
}
function getElementsByClassName(className, tag, elm) {
    var testClass = new RegExp("(^|\\\\s)" + className + "(\\\\s|$)");
    var _tag = tag || "*";
    var _elm = elm || document;
    var elements = (_tag == "*" && _elm.all) ? _elm.all : _elm.getElementsByTagName(_tag);
    var returnElements = [];
    var current;
    var length = elements.length;
    for (var i = 0; i < length; i++) {
        current = elements[i];
        if (testClass.test(current.className)) {
            returnElements.push(current);
        }
    }
    return returnElements;
}

function changeclass(otro, yellow, id) {

    var isIE6 = false;
    if ('Microsoft Internet Explorer' == navigator.appName && navigator.appVersion.indexOf("MSIE 6.0") >= 0) {
        isIE6 = true;
    }
    if (yellow == 'y' && id.charAt(id.length - 1) != 'y') {
        document.getElementById(id).className = "imagesTabs " + otro + "y";
        //        alert("sas: "+document.getElementById(id).className);
        var el;
        if (id == 'tabSpecialli' && isIE6) {
            el = getElementsByClassName('lispeciali');
            for (var cont = 0; cont < el.length; cont++) {
                el[cont].style.display = "block";
            }
        }
    } else {
        document.getElementById(id).className = "imagesTabs " + otro;
        if (id == 'tab_ITSpecialli' && isIE6) {
            el = getElementsByClassName('lispeciali');
            for (cont = 0; cont < el.length; cont++) {
                el[cont].style.display = "none";
            }
        }
    }
}
var selectedKind = "flightsSearch";
function changeSearchEngine(kind, url, lang) {
    if (kind == selectedKind) {
        return;
    }
    var engineIfr = document.getElementById("engineIfr");
    var ifHolder = document.getElementById("ifHolder");
    var iframeParams = document.getElementById("iframeParams").value;
    //   engineIfr.style.height = "341px";
    ifHolder.style.paddingTop = "0px";
    var sflightsSearchSpan,shotelsSearchSpan,sdynpackSearchSpan,spauschalreisenSearchSpan,strainsSearchSpan,svacanzeSearchSpan,scruisesSearchSpan,scarsSearchSpan,ssejourSearchSpan;
    if (document.getElementById("sflightsSearch")) {
        sflightsSearchSpan = document.getElementById("sflightsSearch");
        sflightsSearchSpan.className = "";
    }
    if (document.getElementById("shotelsSearch")) {
        shotelsSearchSpan = document.getElementById("shotelsSearch");
        shotelsSearchSpan.className = "";
    }
    if (document.getElementById("sflightHotelSearch")) {
        sdynpackSearchSpan = document.getElementById("sflightHotelSearch");
        sdynpackSearchSpan.className = "";
    }
    if (document.getElementById("scarsSearch")) {
        scarsSearchSpan = document.getElementById("scarsSearch");
        scarsSearchSpan.className = "";
    }
    if (document.getElementById("scruisesSearch")) {
        scruisesSearchSpan = document.getElementById("scruisesSearch");
        scruisesSearchSpan.className = "";
    }
    if (document.getElementById("strainsSearch")) {
        strainsSearchSpan = document.getElementById("strainsSearch");
        strainsSearchSpan.className = "";
    }
    if (document.getElementById("svacanzeSearch")) {
        svacanzeSearchSpan = document.getElementById("svacanzeSearch");
        svacanzeSearchSpan.className = "";
    }
    if (document.getElementById("spauschalreisenSearch")) {
        spauschalreisenSearchSpan = document.getElementById("spauschalreisenSearch");
        spauschalreisenSearchSpan.className = "";
    }
    if (document.getElementById("ssejourSearch")) {
        ssejourSearchSpan = document.getElementById("ssejourSearch");
        ssejourSearchSpan.className = "";
    }
    document.getElementById("iconSearchTitle").style.padding = "0 0 0 22px";

    engineIfr.style.height = "296px";
    var srcLang = "";
    if (kind == "trainsSearch" && selectedKind != "trainsSearch") {
        strainsSearchSpan.className = "bold";
        engineIfr.src = "/engine/searchEngines/trains/homeTrainsSearchEngine.jsp?searchPageName=trains_search_home";
        if (lang == "it") {
            document.getElementById("messageDreamito").style.background = "url(/images/shared/new/mod_tren_it.gif) no-repeat";
        } else {
            document.getElementById("messageDreamito").style.background = "url(/images/shared/new/modulo_azul_tre.gif) no-repeat";
        }
        document.getElementById("iconSearchTitle").style.background = "url('/images/shared/new_960/icon_tren.png') no-repeat";
        clearErrors();
    } else if (kind == "flightsSearch" && selectedKind != "flightsSearch") {
        sflightsSearchSpan.className = "bold";
        engineIfr.src = "/engine/searchEngines/flights/homeFlightsSearchEngine.jsp?buyPath=1" + iframeParams;
        if(document.getElementById("messageDreamito")){document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_vue_" + lang + ".gif) no-repeat";}
        document.getElementById("iconSearchTitle").style.background = "url('/images/shared/new_960/icon_avion.png') no-repeat";
        clearErrors();
    } else if (kind == "hotelsSearch" && selectedKind != "hotelsSearch") {
        shotelsSearchSpan.className = "bold";
        engineIfr.src = "/engine/searchEngines/hotels/homeHotelsSearchEngine.jsp?buyPath=1" + iframeParams;
        if (lang == "fr_ch" || lang == "fr_ca"){
        	srcLang = "fr";
        	document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_hot_" + srcLang + ".gif) no-repeat";
        } else if (lang == "in" || lang == "en_ca"){
        	srcLang = "en";
        	document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_hot_" + srcLang + ".gif) no-repeat";
        } else if (lang == "it_ch"){
        	srcLang = "it";
        	document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_hot_" + srcLang + ".gif) no-repeat";
        } else if (lang == "de_ch"){
        	srcLang = "de";
        	document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_hot_" + srcLang + ".gif) no-repeat";
        } else {
        	document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_hot_" + lang + ".gif) no-repeat";
        }
        document.getElementById("iconSearchTitle").style.background = "url('/images/shared/new_960/icon_hotel.png') no-repeat";
        clearErrors();
    } else if (kind == "flightHotelSearch" && selectedKind != "flightHotelSearch") {
        sdynpackSearchSpan.className = "bold";
        engineIfr.src = "/engine/searchEngines/dynpack/dynpackSearchEngine.jsp?buyPath=54" + iframeParams + "&isInIframe=true";
        //alert("engineIfr.src: "+engineIfr.src);
        if (lang == "fr_ch" || lang == "fr_ca"){
        	srcLang = "fr";
        	document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_dyn_" + srcLang + ".gif) no-repeat";
        } else if (lang == "in" || lang == "en_ca"){
        	srcLang = "en";
        	document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_dyn_" + srcLang + ".gif) no-repeat";
        } else if (lang == "it_ch"){
        	srcLang = "it";
        	document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_dyn_" + srcLang + ".gif) no-repeat";
        } else if (lang == "de_ch"){
        	srcLang = "de";
        	document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_dyn_" + srcLang + ".gif) no-repeat";
        } else {
        	document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_dyn_" + lang + ".gif) no-repeat";
        }
        document.getElementById("iconSearchTitle").style.background = "url('/images/shared/new_960/icon_dynpack.png') no-repeat";
        document.getElementById("iconSearchTitle").style.padding = "0 0 0 44px";
        clearErrors();
    } else if (kind == "cruisesSearch" && selectedKind != "cruisesSearch") {
        scruisesSearchSpan.className = "bold";
        engineIfr.style.height = "170px";
        ifHolder.style.paddingTop = "30px";
        //http://crociere.edreams.it/iframe_combo_beta.htm
        //"http://cruceros.edreams.es/iframe_combo.htm";
        engineIfr.src = url;
        document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_cru_" + lang + ".gif) no-repeat";
        document.getElementById("iconSearchTitle").style.background = "url('/images/shared/new_960/icon_criadi.png') no-repeat";
        clearErrors();
    } else if (kind == "carsSearch" && selectedKind != "carsSearch") {
        scarsSearchSpan.className = "bold";
        engineIfr.style.height = "274px";
        ifHolder.style.paddingTop = "20px";
        //engineIfr.src = "http://www.edreams.es/edreams/shared/edreams_car_widget/edreams_" + lang + "/index.html";
        switch (lang) {
            case "es":
                engineIfr.src = "http://coches.edreams.es/affiliateXmlStylesheets/edreams_es2/widget/CarSearchWidget.html";
            break;
            case "en":
                engineIfr.src = "http://cars.edreams.com/affiliateXmlStylesheets/edreams_com3/widget/CarSearchWidget.html";
            break;
            case "en_uk":
                engineIfr.src = "http://cars.edreams.co.uk/affiliateXmlStylesheets/edreams_uk3/widget/CarSearchWidget.html";
            break;
            case "de":
                engineIfr.src = "http://mietwagen.edreams.de/affiliateXmlStylesheets/edreams_de3/widget/CarSearchWidget.html";
            break;
            case "de_ch":
                engineIfr.src = "http://mietwagen.edreams.ch/affiliateXmlStylesheets/edreams_dech/widget/CarSearchWidget.html";
            break;
            case "fr":
                engineIfr.src = "http://voiture.edreams.fr/affiliateXmlStylesheets/edreams_fr2/widget/CarSearchWidget.html";
            break;
            case "fr_ch":
                engineIfr.src = "http://voiture.edreams.ch/affiliateXmlStylesheets/edreams_frch/widget/CarSearchWidget.html";
            break;
            case "in":
                engineIfr.src = "http://cars.edreams.in/affiliateXmlStylesheets/edreams_in/widget/CarSearchWidget.html";
            break;
            case "it":
                engineIfr.src = "http://auto.edreams.it/affiliateXmlStylesheets/edreams_it2/widget/CarSearchWidget.html";
            break;
            case "pt":
                engineIfr.src = "http://carros.edreams.pt/affiliateXmlStylesheets/edreams_pt3/widget/CarSearchWidget.html";
            break;
            default:
                engineIfr.src = "http://www.edreams.es/edreams/shared/edreams_car_widget/edreams_" + lang + "/index.html";
        }
        document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_coc_" + lang + ".gif) no-repeat";
        document.getElementById("iconSearchTitle").style.background = "url('/images/shared/new_960/icon_coche.png') no-repeat";
        clearErrors();
    } else if (kind == "pauschalreisenSearch" && selectedKind != "pauschalreisenSearch") {
        spauschalreisenSearchSpan.className = "bold";
        document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_pau_de.gif) no-repeat";
        engineIfr.src = "/engine/searchEngines/pauschalreisen/pauschalreisenEngine.jsp";
        document.getElementById("iconSearchTitle").style.background = "url('/images/shared/new_960/icon_vacaciones.png') no-repeat";
        clearErrors();
    } else if (kind == "vacanzeSearch" && selectedKind != "vacanzeSearch") {
        engineIfr.style.height = "300px";
        ifHolder.style.paddingTop = "0px";
        svacanzeSearchSpan.className = "bold";
        engineIfr.src = "http://edreams.miavacanza.it/cerca.htm";
        document.getElementById("messageDreamito").style.background = "url(/images/shared/new/mod_tren_it.gif) no-repeat";
        document.getElementById("iconSearchTitle").style.background = "url('/images/shared/new_960/icon_vacaciones.png') no-repeat";
        clearErrors();
    } else if (kind == "carsSearch" && selectedKind != "carsSearch") {
        scarsSearchSpan.className = "bold";
        engineIfr.src = url;
        document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_coc_" + lang + ".gif) no-repeat";
        document.getElementById("iconSearchTitle").style.background = "url('/images/shared/new_960/icon_tren.png') no-repeat";
        clearErrors();
    } else if (kind == "smartBoxSearch" && selectedKind != "smartBoxSearch") {
        document.getElementById("iconSearchTitle").style.background = "url('/images/shared/new_960/icon_vacaciones.png') no-repeat";
        window.location = url;
    } else if (kind == "sejourSearch" && selectedKind != "sejourSearch") {
        engineIfr.style.height = "210px";
        ifHolder.style.paddingTop = "20px";
        ssejourSearchSpan.className = "bold";
        engineIfr.src = url;
        document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_coc_" + lang + ".gif) no-repeat";
        document.getElementById("iconSearchTitle").style.background = "url('/images/shared/new_960/icon_vacaciones.png') no-repeat";
        clearErrors();
    }

    var text = 's' + kind;
    if (document.getElementById(text)) {
        document.getElementById("ifHolderNameSearch").innerHTML = document.getElementById(text).innerHTML;
    }


    selectedKind = kind;
}

function clearPicker(iframe) {
    var docScope;
    if (document.getElementById(iframe)) {
        docScope = document;
    } else if (parent.document.getElementById(iframe)) {
        docScope = parent.document;

    }
    docScope.getElementById(iframe).src = "/engine/static-content/html/blank.html";
    return true;
}
var isFlexible = false;

function showFrameBox(address, obj, iframe, left, top, train) {
    //    console.log("delayId: "+delayId);
    if (delayId) {
        clearInterval(delayId);
        delayId = null;
    }
    //    console.log("delayId22: "+delayId);
    close_layers();
    if (address.indexOf('?') != -1) {
        var addressParams = address.substring(address.indexOf('?') + 1, address.length);
        //var paramsForm = addressParams.substring(addressParams.indexOf('=') + 1, addressParams.indexOf('&'));
        var paramsFullField = addressParams.substring(addressParams.indexOf('&') + 1, address.length);
        var paramsField = paramsFullField.substring(paramsFullField.indexOf('=') + 1, paramsFullField.length);
        var depDateField = document.getElementById("departureDate");
        var retDateField = document.getElementById("returnDate");

        if (paramsField == "returnDate" && depDateField.value == iAmFlexible) {
            if (!isFlexible) {
                showAlertInDiv('flexibleAlert', 'no');
                isFlexible = true;
            }
            return;
        }
        if (retDateField && retDateField.value == iAmFlexible) {
            isFlexible = true;
        }
    }
    var docScope, windowScope, ifr;
    var engineFrOffsetTop, engineFrOffsetLeft;
    var availableWindowWidth, availableWindowHeight;
    if (document.getElementById(iframe)) {
        docScope = document;
        windowScope = window;
        engineFrOffsetTop = 0;
        engineFrOffsetLeft = 0;
    } else if (parent.document.getElementById(iframe)) {
        docScope = parent.document;
        windowScope = parent;
        if (docScope.getElementById('engineIfr')) {
            ifr = docScope.getElementById('engineIfr');
        } else if (docScope.getElementById('dynpackSearchData-filterFR')) {
            ifr = docScope.getElementById('dynpackSearchData-filterFR');
        }
        engineFrOffsetTop = findOffsetTop(ifr);
        engineFrOffsetLeft = findOffsetLeft(ifr);

    }
    var aBox = docScope.getElementById(iframe);
    var styleTop = findOffsetTop(document.getElementById(obj)) - top + engineFrOffsetTop;
    var styleLeft = findOffsetLeft(document.getElementById(obj)) - left + engineFrOffsetLeft;

    if (styleTop < 100) {
        styleTop = 100;
    }
    if (top > 1000) {
        var yScroll;
        if (navigator.appName.indexOf("Microsoft") != -1) {
            yScroll = document.body.parentNode.scrollTop;
        } else {
            yScroll = window.scrollY;
        }
        if (yScroll > 146) {
            styleTop = yScroll;
        } else {
            styleTop = 146;
        }
    }
    if (styleLeft < 100) {
        styleLeft = 100;
    }
    aBox.style.display = 'block';
    //    $('#'+iframe).animate({top:styleTop + "px"},{ duration: 'slow', easing: 'linear' });
    aBox.style.top = styleTop + 'px';
    aBox.style.left = styleLeft + 'px';

    if (train) {
        var aux = "";
        if (obj == "trainSearchHPcityArrival") {
            aux = document.trainSearch.departureIata.value;
        }
        if (aux == "") {
            aux = "ALL";
        }
        address = address + "?dest=" + aux;
    }
    docScope.getElementById(iframe + "FR").src = address;
    if (navigator.appName.indexOf("Microsoft") != -1) {
        availableWindowWidth = windowScope.document.body.offsetWidth;
    } else {
        availableWindowWidth = windowScope.innerWidth;
    }

    if ((styleLeft + aBox.offsetWidth) > availableWindowWidth) {
        aBox.style.left = (availableWindowWidth - aBox.offsetWidth) - 20 + 'px';
    }

}

/**
 * Muestra u oculta el framebox de Detalles de Itinerario
 * @author Fabian Couto
 */
setFrameBox = function() {
    var isOpen = false;

    function isVisible(objId) {
        try {
            isOpen = (document.getElementById(objId).style.display == 'block');
        } catch (e) {
            throwError(e, 'setFrameBox.isVisible', arguments);
        }
    }

    function getIsOpen() {
        return isOpen;
    }

    return {
        isVisible:isVisible,
        getIsOpen:getIsOpen
    }
}();

/**
 * Muestra u oculta el framebox de Detalles de Itinerario
 * @author Fabian Couto
 */
//function chVisibility(objId) {
//    var hasToOpen;
//    if($("#aTravelItinerary").hasClass('showTripDetail')){
//        hasToOpen= true;
//        $("#aTravelItinerary").removeClass('showTripDetail');
//        $("#aTravelItinerary").addClass('hideTripDetail');
//    } else{
//        hasToOpen= false;
//        $("#aTravelItinerary").removeClass('hideTripDetail');
//        $("#aTravelItinerary").addClass('showTripDetail');
//    }
//    changeVisibility(objId, hasToOpen);
//}

function findOffsetLeft(element) {
    return findOffset(element, "offsetLeft");
}

function findOffsetTop(element) {
    return findOffset(element, "offsetTop");
}

function showFrameAirlines(idPosition) {
    var theFrame = window.frames["idFrameAirlines"];
    if ((theFrame.name) != "idFrameAirlines") {
        alert(no_aerolineas);
        return;
    }
    var frameIsLoaded = theFrame.frameIsLoaded;
    if ((frameIsLoaded == null) || (!frameIsLoaded)) {
        alert(no_aerolineas);
        return;
    }
    theFrame.showTheAirlinesFrame(document.getElementById(idPosition), 1);
}
var isOneWay = false;
function tripTypeSelected(formId, value, multiDestinationsURL) {
    var returnDateField, returnTimeField, tripFlield;
    returnDateField = document.getElementById('returnDate');
    returnTimeField = document.getElementById('returnTime');
    tripFlield = "";

    if (formId == "flightsSearch_multi") {
        parent.location.href = "/engine/index.jsp?tripT=" + value;
    } else {
        if (value == "ONE_WAY") {
            tripFlield.value = 'ONE_WAY';
            isOneWay = true;
            returnDateField.value = onewaylabel;
            returnDateField.disabled = true;
            returnDateField.style.backgroundColor = "#CCCCCC";
            returnTimeField.disabled = true;
            //            returnTimeField.style.backgroundColor = "#CCCCCC";
        } else if (value == "ROUND_TRIP") {
            tripFlield.value = 'ROUND_TRIP';
            isOneWay = false;
            returnDateField.disabled = false;
            returnDateField.style.backgroundColor = "#FAF4F4";
            if (returnDateField.value == onewaylabel) {
                returnDateField.value = "";
            }
            returnTimeField.disabled = false;
            //            returnTimeField.style.backgroundColor = "#FAF4F4";
        } else if (value == "MULTI_SEGMENT") {
            if (!multiDestinationsURL || multiDestinationsURL == "") {
                parent.window.location.href = "/engine/flights/multi.jsp";
            } else {
                parent.window.location.href = multiDestinationsURL;
            }
        } else if (value == "SHUTTLE") {
            parent.window.location.href = "/vuelos/puente-aereo/";
        }
    }
}

var isDynpackSearch = false;
function checkHomeFlightsForm(formId, isDynpack) {
    var errors = 0;
    clearErrors();
    var product;
    var pageAction = 'flights_search_home'; //For tracking filter
    var pageLabel;                          //For tracking filter
    var b_FilterMoreOptions = false;         //For tracking filter

    if (isDynpack) {
        product = "dynpack";
    } else {
        var flightsForm;
        isDynpackSearch = false;
        product = "vuelos";
        if (parent.frames['engineIfr']) {
            flightsForm = parent.frames['engineIfr'].document.getElementById(formId);
        } else {
            flightsForm = document.getElementById(formId);
        }
        flightsForm.action = "/engine/ItinerarySearch/search";
    }
    if (!validateCity(formId, 'departure', 'flight'))errors ++;
    if (!validateCity(formId, 'arrival', 'flight'))errors ++;
    if (!validateDate(formId, 'departure', errors, isDynpackSearch))errors ++;
    if (isFlexible) {
        return false;
    }
    if (isDynpackSearch) {
        if (!validateThirtyDaysStay(formId))errors ++;
        if (!validateDate(formId, 'return', errors, isDynpackSearch))errors ++;

    } else {
        if (!isOneWay && !isFlexible) {
            if (!validateDate(formId, 'return', errors, isDynpackSearch))errors ++;
        }
    }
    if (errors > 0 && isFlexible) {
        return false;
    }
    if (!validatePassengers(formId))errors ++;
    if (isDynpackSearch) {
        if (!validateFiveOrSevenPeople(formId))errors ++;
    }
    if(document.getElementById("collectionTypeEstimationNeeded") != null ){
        document.getElementById("collectionTypeEstimationNeeded").value = false;
    }
    if(document.getElementById("applyAllTaxes") != null ){
        document.getElementById("applyAllTaxes").value = false;
    }
    if (document.getElementById("collectionMethodId") != null && document.getElementById("collectionMethodId").value != "0-0") {
        document.getElementById("collectionTypeEstimationNeeded").value = true;
        document.getElementById("applyAllTaxes").value = true;
    }
    if (errors < 1) {
        if (!isDynpackSearch) {
            showFlightsSearchEnginePopUnder();
        }

        // tracking filtros - flight page
        if (document.getElementById('fake_filteringCarrier')) {
            //si selecciona alguna companyia
            if (document.getElementById('filteringCarrier').value != '' && document.getElementById('filteringCarrier').value != null) {
                pageAction = 'flights_search_tab';
                pageLabel = 'filteringCarrier';
                gaTrackEvent("form filter", pageAction, pageLabel);
                b_FilterMoreOptions = true;
            }
        }

        // tracking filtros - home page flights
        if (document.getElementById('mainAirportsOnly') && document.getElementById('directFlights')) {
            if (document.getElementById('mainAirportsOnly').checked) {
                pageLabel = 'mainAirportsOnly';
                gaTrackEvent("form filter", pageAction, pageLabel);
            }
            if (document.getElementById('directFlights').checked) {
                pageLabel = 'directFlights';
                gaTrackEvent("form filter", pageAction, pageLabel);
            }
            //sin filtros
            if (!(document.getElementById('mainAirportsOnly').checked) && !(document.getElementById('directFlights').checked) && !b_FilterMoreOptions) {
                pageLabel = 'noFilters';
                gaTrackEvent("form filter", pageAction, pageLabel);
            }
        }

        parent.initSwoosh("paso1", product, formId);
        try {
            if ($.browser.webkit) {
                setTimeout('document.forms[0].submit()', 1000);
                return false;
            } else {
                return true;
            }
        } catch (e) {
            alert(e.message);
        }
    } else {
        return false;
    }
}
function checkDynpackSearch(formId) {
    var errors = 0;
    clearErrors();

    if (!validateCity(formId, 'departure', 'dynpack'))errors ++;
    if (!validateCity(formId, 'arrival', 'dynpack'))errors ++;
    if (!validateDate(formId, 'departure', errors, true))errors ++;
    if (!validateThirtyDaysStay(formId))errors ++;
    if (!validateDate(formId, 'return', errors, true))errors ++;
    isFiveOrSevenPeople = isDynFiveOrSevenPeople(formId);
    if (!validateFiveOrSevenPeople(formId))errors ++;
    if (errors < 1) {
        parent.initSwoosh("paso1", "dynpack", formId);
        return true;
    } else {
        return false;
    }
}
function checkSimpleFlightsForm(formId) {
    var errors = 0;
    clearErrors();

    if (!validateCity(formId, 'departure', 'flight'))errors ++;
    if (!validateCity(formId, 'arrival', 'flight'))errors ++;
    if (!validateDate(formId, 'departure', errors))errors ++;
    if (isFlexible) {
        return false;
    }
    if (!isOneWay && !isFlexible) {
        if (!validateDate(formId, 'return', errors))errors ++;
    }
    if (errors > 0 && isFlexible) {
        return false;
    }
    if (!validatePassengers(formId))errors ++;
    if (errors < 1) {
        initSwoosh("paso1", "vuelos", formId);

        return true;
    } else {
        return false;
    }
}
function checkSimpleDynPackForm(formId) {
    var errors = 0;
    clearErrors();
    if (!validateCity(formId, 'departure'))errors ++;
    if (!validateCity(formId, 'arrival'))errors ++;
    if (!validateDate(formId, 'departure', errors, true))errors ++;
    if (!validateThirtyDaysStay())errors ++;
    if (!validateDate(formId, 'return', errors, true))errors ++;
    if (!validatePassengers(formId))errors ++;
    if (!validateFiveOrSevenPeople())errors ++;
    if (errors < 1) {
        initSwoosh("paso1", "dynpack", formId);
        return true;
    } else {
        return false;
    }
}
function checkTrainsForm(formId) {
    var errors = 0;
    clearErrors();
    var isInternational = document.getElementById("trenAuxPickerInternational").checked;
    var form = document.getElementById(formId);
    if (!validateCity(formId, 'departureTrain', 'train'))errors ++;
    if (!validateCity(formId, 'arrivalTrain', 'train'))errors ++;
    if (!validateDate(formId, 'departure', errors))errors ++;
    if (!isOneWay) {
        if (!validateDate(formId, 'return', errors))errors ++;
    }
    if (!validatePassengers(formId))errors ++;
    document.getElementById("collectionTypeEstimationNeeded").value = false;
    document.getElementById("applyAllTaxes").value = false;        
    if (document.getElementById("collectionMethodId") != null && document.getElementById("collectionMethodId").value != "0-0") {
        document.getElementById("collectionTypeEstimationNeeded").value = true;
        document.getElementById("applyAllTaxes").value = true;
    }
    if (errors < 1) {
        if (!isInternational) {
            form.action = "/engine/ItinerarySearch/search";
            if (isIframe) {
                form.target = "_parent";
                parent.initSwoosh("paso1", "trenes", formId);
            } else {
                form.target = "_self";
                initSwoosh("paso1", "trenes", formId);
            }
        } else {
            form.action = "/engine/searchEngines/trains/launchSearchOutside.jsp";
            form.target = "_blank";
        }
        addFlightsToTrains();
        return true;
    } else {
        return false;
    }
}
function checkMultiFlightsForm(lang) {
    var errors = 0;
    var formId = "flightsSearch_multi";
    clearErrors();
    initMultiFlightsForm();
    if (!validateMultiDate())errors ++;
    /*if (errors > 0) {
     return false;
     }*/
    if (!validateMultiCity())errors ++;
    if (!validatePassengers(formId))errors ++;
    if (errors < 1) {
        initSwoosh("paso1", "multidestino", "flightsSearch_multi", lang);
        return true;
    } else {
        return false;
    }
}
function checkLinearFlightsForm(formId) {
    var errors = 0;
    clearErrors();
    var product;
    var pageLabel;                              // tracking filters
    var pageAction = 'flights_search_results';  // tracking filters

    if (!validateCity(formId, 'departure', 'flight'))errors ++;
    if (!validateCity(formId, 'arrival', 'flight'))errors ++;
    if (!validateDate(formId, 'departure', errors))errors ++;
    if (isFlexible) {
        return false;
    }
    if (!isOneWay && !isFlexible) {
        if (!validateDate(formId, 'return', errors))errors ++;
    }
    if (errors > 0 && isFlexible) {
        return false;
    }
    if (!validatePassengers(formId))errors ++;
    if (errors < 1) {
        var isFlights = formId.toLowerCase().indexOf('flights');
        if (isFlights != -1) {
            product = "vuelos";
        }

        // tracking filtros - home page
        if (document.getElementById('mainAirportsOnly') && document.getElementById('directFlights')) {
            if (document.getElementById('mainAirportsOnly').checked) {
                pageLabel = 'mainAirportsOnly';
                gaTrackEvent("form filter", pageAction, pageLabel);
            }
            if (document.getElementById('directFlights').checked) {
                pageLabel = 'directFlights';
                gaTrackEvent("form filter", pageAction, pageLabel);
            }
            //sin filtros
            if (!(document.getElementById('mainAirportsOnly').checked) && !(document.getElementById('directFlights').checked)) {
                pageLabel = 'noFilters';
                gaTrackEvent("form filter", pageAction, pageLabel);
            }
        }

        initSwoosh("paso1", product, formId);

        return true;
    } else {
        return false;
    }
}
function checkChooseAirport(formId, numSegments, lang, isNotFlights) {
    var errors = 0;
    clearErrors();
    var segmentsNum = Number(numSegments) + 1;
    if (!validateChooseAirport(formId, segmentsNum, isNotFlights))errors ++;
    if (errors < 1) {
        if (segmentsNum <= 1) {

            var elem = document.getElementById("isBDSearch");

            if (elem) {
                var elemArrival = document.getElementById("");

                if (elemArrival) elemArrival.value = "...";
            }
            if (isNotFlights) {
                initSwoosh("paso1", "hoteles", formId);
            } else {
                initSwoosh("paso1", "vuelosDesambiguacion", formId);
            }
        } else {
            initSwoosh("paso1", "multidestino", formId, lang);
        }
        return true;
    } else {
        return false;
    }
}
function checkOfferFlightsForm(formId, lang) {

    if (document.getElementById("tripTypeName").value == "ONE_WAY") {
        document.getElementById("returnDate").value = onewaylabel;
    } else {
        document.getElementById("departureDate").value = "";
    }
    document.getElementById("departureDate").value = "";
    var errors = 0;
    clearErrors();
    //
    var product;
    if (!validateCity(formId, 'departure', 'flight'))errors ++;
    if (!validateCity(formId, 'arrival', 'flight'))errors ++;

    if (errors < 1) {
        var isFlights = formId.toLowerCase().indexOf('flights');
        if (isFlights != -1) {
            product = "vuelos";
        }
        initSwoosh("paso1", product, formId, lang);
        return true;
    } else {
        return false;
    }
}
var submitInterval;
function checkSelItinerary(formId, ind, isMeta, product, lang) {
    $('.content-error').css('display', 'none');
    clearErrors(ind);
    if (!validateItinerary(formId, ind)) {
        checkFade();
        return false;
    }
    if (!isMeta) {
        initSwoosh("paso2", "vuelos");
        setTimeout('document.getElementById("' + formId + '").submit()', 1000);
        return false;
    } else {
        document.getElementById(formId).submit();
    }
}


function isFlashReady(formId) {
    if (hasLoadedFlash) {
        document.getElementById(formId).submit();
        clearInterval(submitInterval);
    }
}
function checkLogin(emailId, passId) {
    clearUserdata();
    var product;
    var errors = 0;
    clearErrors();
    //
    var emailField = document.getElementById(emailId);
    var passField = document.getElementById(passId);
    if (!validateEmail(emailField))errors++;
    if (!validatePass(passField))errors++;

    if (errors < 1) {
        if (product) {
            initSwoosh('paso2', product, 'login');
        }
        return true;
    } else {
        return false;
    }
}
function clearUserdata() {
    var nameField = document.getElementById("name");
    changeToClass(nameField, "");
    var surNameField = document.getElementById("lastName");
    changeToClass(surNameField, "");
    var idField = document.getElementById("idCardNumber");
    changeToClass(idField, "");
    var mobileField = document.getElementById("mobileNumber");
    changeToClass(mobileField, "");
    var addressField = document.getElementById("address");
    changeToClass(addressField, "");
    var cityField = document.getElementById("city");
    changeToClass(cityField, "");
    var zipCodeField = document.getElementById("zipCode");
    changeToClass(zipCodeField, "");
    var regionField = document.getElementById("region");
    changeToClass(regionField, "");
    var emailFieldR = document.getElementById("email");
    changeToClass(emailFieldR, "");
    var email2FieldR = document.getElementById("email2");
    changeToClass(email2FieldR, "");
    var passField = document.getElementById("password");
    changeToClass(passField, "");
    var passField2 = document.getElementById("password2");
    changeToClass(passField2, "");
    var conditionsDiv = document.getElementById("conditionsDiv");
    changeToClass(conditionsDiv, "");
}
function checkUserData(kind) {
    // Limpia los campos del formulario de login
    var emailField = document.getElementById("loginEmail");
    var passField = document.getElementById("loginPassword");
    changeToClass(emailField, "");
    changeToClass(passField, "");

    clearErrors();
    var product;
    var errors = 0;

    var nameField = document.getElementById("name");
    var surNameField = document.getElementById("lastName");
    var idField = document.getElementById("idCardNumber");
    var mobileField = document.getElementById("mobileNumber");
    var addressField = document.getElementById("address");
    var cityField = document.getElementById("city");
    var zipCodeField = document.getElementById("zipCode");
    var regionField = document.getElementById("region");
    var emailField = document.getElementById("email");

    var passField = document.getElementById("password");
    var passField2 = document.getElementById("password2");
    if (kind == "register") {
        var emailField2 = document.getElementById("email2");
        var conditionsField = document.getElementById("acceptedGeneralConditions");
    }

    if (!isFieldFilled(nameField)) {
        errors++;
    } else if (!lengthHigher(2, nameField)) {
        errors++;
    } else {
        if (!validateJustLetters(nameField))errors++;
    }

    if (!isFieldFilled(surNameField)) {
        errors++;
    } else if (!lengthHigher(2, surNameField)) {
        errors++;
    } else {
        if (!validateJustLetters(surNameField))errors++;
    }
    if (!isFieldFilled(idField))errors++;
    if (!isFieldFilled(mobileField)) {
        errors++;
    } else {
        if (!validateMobile(mobileField))errors++;
    }
    if (!isFieldFilled(addressField))errors++;
    if (!isFieldFilled(cityField))errors++;
    if (!isFieldFilled(zipCodeField))errors++;
    if (!isFieldFilled(regionField))errors++;
    if (!validateEmail(emailField))errors++;
    if (kind == "register") {
        if (!validateEmail(emailField2))errors++;

        if (!validateEqualValues(emailField.value, emailField2.value, "email")) {
            changeToClass(emailField, "borderRed");
            changeToClass(emailField2, "borderRed");
            errors++;
        } else {
            changeToClass(emailField, "");
            changeToClass(emailField2, "");
        }
    }
    if (!validatePass(passField))errors++;
    if (!validatePass(passField2))errors++;
    if (!validateEqualValues(passField.value, passField2.value, "pass")) {
        changeToClass(passField, "borderRed");
        changeToClass(passField2, "borderRed");
        errors++;
    } else {
        changeToClass(passField, "");
        changeToClass(passField2, "");
    }
    if (kind == "register") {
        if (!validateConditions(conditionsField))errors++;
    }
    if (errors < 1) {
        if (product) {
            initSwoosh('paso2', product, 'register');
            return false;
        }
        return true;
    } else {
        return false;
    }
}
function checkForgot() {
    clearErrors();
    var emailField = document.getElementById("login");
    return validateEmail(emailField);
}
function checkKeepSubscription() {
    clearErrors();
    var errors = 0;
    var keepSubscriptionlogin = document.getElementById("keepSubscriptionlogin");
    if (document.getElementById("login")) {
        keepSubscriptionlogin.value = document.getElementById("login").value;
    }
    if (!validateEmail(keepSubscriptionlogin))errors++;
    return (errors < 1);
}
function chooseOnlyOne(obj, num, follow) {
    var a = document.getElementsByName(obj.name);

    for (var i = 0; i < a.length; i++) {
        a[i].checked = false;
    }

    obj.checked = true;

    var idForm = 'itinerary' + num;
    if (document.forms[idForm]['segmentPosition0']) {
        var formOutBoundOptions = document.forms[idForm]['segmentPosition0'];
        if (!formOutBoundOptions.length) {
            formOutBoundOptions.checked = true;

            if (follow) chooseOnlyOne(formOutBoundOptions, num, false);
        }
    }

    if (document.forms[idForm]['segmentPosition1']) {
        var formInBoundOptions = document.forms[idForm]['segmentPosition1'];
        if (!formInBoundOptions.length) {
            formInBoundOptions.checked = true;

            if (follow) chooseOnlyOne(formInBoundOptions, num, false);
        }
    }

    if (document.forms[idForm]['segmentPosition2']) {
        var formExtraBoundOptions = document.forms[idForm]['segmentPosition2'];
        if (!formExtraBoundOptions.length) {
            formExtraBoundOptions.checked = true;

            if (follow) chooseOnlyOne(formExtraBoundOptions, num, false);
        }
    }
    if (document.forms[idForm]['segmentPositionOWASRT1']) {
        var formExtraBoundOptions = document.forms[idForm]['segmentPositionOWASRT1'];
        if (!formExtraBoundOptions.length) {
            formExtraBoundOptions.checked = true;

            if (follow) chooseOnlyOne(formExtraBoundOptions, num, false);
        }
    }
}

function chooseOnlyOneSegment(obj) {
    var allRadios_array = $(".radioResults");
    var selectedObjId = obj.id;
    var selectedBaseName = selectedObjId.split('_')[0];
    var selectedFlightNum = selectedObjId.split('_')[1];
    var selectedBoundNum = selectedObjId.split('_')[2];
    var numOfSegemntsInOtherBound = 0;
    for (var i = 0; i < allRadios_array.length; i++) {
        var flightNum = allRadios_array[i].id.split('_')[1];
        var boundNum = allRadios_array[i].id.split('_')[2];
        if (flightNum != selectedFlightNum) {
            allRadios_array[i].checked = false;
            setSegmentDeselected($('#' + allRadios_array[i].id).parent().parent());
        } else if (flightNum == selectedFlightNum) {
            if (boundNum != selectedBoundNum) {
                numOfSegemntsInOtherBound++;
            } else {
                allRadios_array[i].checked = false;
                setSegmentDeselected($('#' + allRadios_array[i].id).parent().parent());
            }
        }
    }
    if ($("#" + obj.id).hasClass("radioResultsSelected")) {
        chooseOnlyOneothers(obj);
        return;
    }

    obj.checked = true;
    setSegmentSelected($('#' + obj.id).parent().parent());
    if (numOfSegemntsInOtherBound == 1) {
        var boundNum = (selectedBoundNum == "0") ? "1" : "0";
        //        var inp = $("#"+selectedBaseName+"_"+selectedFlightNum+"_"+boundNum+"_0");
        var inp = document.getElementById(selectedBaseName + "_" + selectedFlightNum + "_" + boundNum + "_0");
        inp.checked = true;
        setSegmentSelected($('#' + inp.id).parent().parent());
    }
}
function chooseOnlyOneothers(obj) {
    var a = document.getElementsByName(obj.name);
    var selectedObjId = obj.id;

    for (var i = 0; i < a.length; i++) {
        var objId = a[i].id;
        if (selectedObjId.indexOf("-1") != -1) {
            setSegmentDeselected($('#' + objId).parent().parent());
        }
        if (objId.indexOf("-1") == -1) {
            a[i].checked = false;
            setSegmentDeselected($('#' + objId).parent().parent());
        }
    }
    obj.checked = true;
    setSegmentSelected($('#' + obj.id).parent().parent());
}
function segmentClicked(div, kind, price, index) {
    var obj;
    var nameArr = div.split("_");
    if (kind == "results") {

        obj = document.getElementById("segmentPosition_" + nameArr[1] + "_" + nameArr[2] + "_" + nameArr[3]);
        chooseOnlyOneSegment(obj);
    } else if (kind.indexOf("room") != -1) {
        //        actualizarPrecio(price, index);
        obj = document.getElementById(kind);
        chooseOnlyOneothers(obj);
    } else {
        obj = document.getElementById(kind);
        chooseOnlyOneothers(obj);
    }


    //    $('#'+div).className='${firstElementClass} segmentRow pointerCursor floatLeft segmentSelected';
    //    $('#'+div).data('selected', true);
}
function setSegmentrolled(div) {
    if ($("#" + div).data.isSelected != true) {
        $("#" + div).toggleClass("segmentOut segmentHover");
    }
}
//function setSegmentOut(div){
//     if($("#"+div).data.isSelected != true){
//        $("#"+div).toggleClass("segmentOut segmentHover");
//    }
//}
function setSegmentSelected(div) {
    div.removeClass("segmentOut");
    div.removeClass("segmentHover");
    div.addClass("segmentSelected");
    div.css('opacity', '0.5');
    div.fadeTo("slow", 1);
    div.data('isSelected', true);
}
function setSegmentDeselected(div) {
    div.data('isSelected', false);
    div.removeClass("segmentSelected");
    div.removeClass("segmentHover");
    div.addClass("segmentOut");
}


function cleanChecked(num) {
    var objs = [];

    var idForm = 'itinerary' + num;

    if (document.forms[idForm]['segmentPosition0']) {
        var formOutBoundOptions = document.forms[idForm]['segmentPosition0'];
        if (!formOutBoundOptions.length) {
            if (formOutBoundOptions.checked == true) objs.push(formOutBoundOptions);
        } else {
            for (var j = 0; j < formOutBoundOptions.length; j++) {
                if (formOutBoundOptions[j].checked == true) objs.push(formOutBoundOptions[j]);
            }
        }
    }

    if (document.forms[idForm]['segmentPosition1']) {
        var formInBoundOptions = document.forms[idForm]['segmentPosition1'];
        if (!formInBoundOptions.length) {
            if (formInBoundOptions.checked == true) objs.push(formInBoundOptions);
        } else {
            for (var j = 0; j < formInBoundOptions.length; j++) {
                if (formInBoundOptions[j].checked == true) objs.push(formInBoundOptions[j]);
            }
        }
    }

    if (document.forms[idForm]['segmentPosition2']) {
        var formExtraBoundOptions = document.forms[idForm]['segmentPosition2'];
        if (!formExtraBoundOptions.length) {
            if (formExtraBoundOptions.checked == true) objs.push(formExtraBoundOptions);
        } else {
            for (var j = 0; j < formExtraBoundOptions.length; j++) {
                if (formExtraBoundOptions[j].checked == true) objs.push(formExtraBoundOptions[j]);
            }
        }
    }

    if (document.forms[idForm]['segmentPositionOWASRT1']) {
        var formExtraBoundOptions = document.forms[idForm]['segmentPositionOWASRT1'];
        if (!formExtraBoundOptions.length) {
            if (formExtraBoundOptions.checked == true) objs.push(formExtraBoundOptions);
        } else {
            for (var j = 0; j < formExtraBoundOptions.length; j++) {
                if (formExtraBoundOptions[j].checked == true) objs.push(formExtraBoundOptions[j]);
            }
        }
    }

    var setTr = $('.auxFl');
    for (var i = 0; i < setTr.length; i++) {
        (($(setTr[i])).find('input:radio')).attr('checked', false);
    }

    for (var i = 0; i < objs.length; i++) {
        objs[i].checked = true;
    }
}

function checkFade() {
    var setTr = $('.auxFl');
    for (var i = 0; i < setTr.length; i++) {

        if (($(setTr[i])).find('input:radio').is(':checked')) {
            $(setTr[i]).css("background-color", "#ffe787");
        } else {
            $(setTr[i]).css("background-color", "#ffffff");
        }
    }
}

function start_redirect() {
    var position = (document.body.clientWidth / 2) - 275;
    document.getElementById("redirect-front").style.marginLeft = position + 'px';
    document.getElementById("redirect-front").style.display = 'block';
    var browser = navigator.appName;
    if (browser == "Microsoft Internet Explorer") {
        document.getElementById("redirect-back").style.width = screen.width;
        document.getElementById("redirect-back").style.height = screen.height;
    }
    document.getElementById("redirect-back").style.display = 'block';
}
function cancel_redirect() {
    document.getElementById("redirect-back").style.display = 'none';
    document.getElementById("redirect-front").style.display = 'none';
}
function openOfferCitiesBox(obj) {
    var headFootHeight = 30;
    var closeHeight = 9;
    var paddheight = 20;
    var citHeigh = 14;
    var plusHeight = headFootHeight + citHeigh + closeHeight + paddheight;
    var totCitHeight = citHeigh * citNum;
    var totDivHeight = plusHeight + totCitHeight;
    var relativeTop = (totDivHeight / 4) * 3;

    var dCityBox = document.getElementById('defCityBox');	// suggest list
    var dCityBoxShim = document.getElementById('defCityBoxShim');	// workaround: msie div over select
    dCityBox.style.height = totDivHeight + 'px';
    dCityBox.style.top = findOffsetTop(document.getElementById(obj)) - relativeTop + 'px';
    dCityBox.style.left = findOffsetLeft(document.getElementById(obj)) + 150 + 'px';

    dCityBoxShim.style.top = dCityBox.style.top;
    dCityBoxShim.style.left = dCityBox.style.left;
    dCityBoxShim.style.zIndex = dCityBox.style.zIndex - 1;


    dCityBox.style.display = 'block';
}


function replaceAccentsAndSpecial(str) {
    var myStr = str.ltrim().rtrim();
    myStr = myStr.replace(/á/g, "a").replace(/é/g, "e").replace(/í/g, "i").replace(/ó/g, "o").replace(/ú/g, "u").replace(/à/g, "a").replace(/è/g, "e").replace(/ì/g, "i").replace(/ò/g, "o").replace(/ù/g, "u").replace(/â/g, "a").replace(/ê/g, "e").replace(/î/g, "i").replace(/ô/g, "o").replace(/û/g, "u").replace(/n/g, "n").replace(/ç/g, "c");
    myStr = myStr.replace(/Á/g, "A").replace(/É/g, "E").replace(/Í/g, "I").replace(/Ó/g, "O").replace(/Ú/g, "U").replace(/À/g, "A").replace(/È/g, "E").replace(/Ì/g, "I").replace(/Ò/g, "O").replace(/Ù/g, "U").replace(/Â/g, "A").replace(/Ê/g, "E").replace(/Î/g, "I").replace(/Ô/g, "O").replace(/Û/g, "U").replace(/Ñ/g, "N").replace(/Ç/g, "C");
    myStr = myStr.replace(/Ä/g, "Ae").replace(/ä/g, "ae").replace(/Ö/g, "Oe").replace(/ö/g, "oe").replace(/Ü/g, "Ue").replace(/ü/g, "ue").replace(/ß/g, "ss").replace(/ã/g, "a").replace(/õ/g, "o");
    myStr = myStr.replace(/ğ/g, "g").replace(/ş/g, "s").replace(/ı/g, "i").replace(/y/g, "y").replace(/i/g, "i");
    myStr = myStr.replace(/Ğ/g, "G").replace(/Ş/g, "S").replace(/I/g, "I").replace(/Ý/g, "Y").replace(/İ/g, "I");

    return myStr;


}

function setSeachCookie(currentValue, product) {
    var cookieName, myPath, depNodeCode, arrNodeCode, tripType, infants, rooms, cookieValue;
    myPath = "/";
    if (product == "FLIGHT") {
        cookieName = "fsearch";
        depNodeCode = "";
    } else if (product == "TRAIN") {
        cookieName = "tsearch";
    } else if (product == "DYNPACK") {
        cookieName = "dynsearch";
    } else if (product == "HOTELS") {
        cookieName = "hotelsearch";
    }
    if (product != "HOTELS") {
        if (product != "DYNPACK") {
            tripType = (document.getElementById('tripTypeName').checked) ? 'ROUND_TRIP' : 'ONE_WAY';
        }
        var depLoc = replaceAccentsAndSpecial(document.getElementById('departureLocation').value);
        var arrLoc = replaceAccentsAndSpecial(document.getElementById('arrivalLocation').value);
        var adults = document.getElementById('numAdults').value;
        var children = 0;
        if (product == "DYNPACK") {
            children = document.getElementById('numberOfChildsPerRoom').value;
        } else {
            children = document.getElementById('numChilds').value;
        }
        if (product != "DYNPACK") {
            infants = document.getElementById('numInfants').value;
        }
        var depDate = document.getElementById('departureDate').value;
        var retDate = document.getElementById('returnDate').value;
        if (document.getElementById('departureLocationGeoNodeId')) {
            depNodeCode = document.getElementById('departureLocationGeoNodeId').value;
            arrNodeCode = document.getElementById('arrivalLocationGeoNodeId').value;
        } else {
            depNodeCode = "";
            arrNodeCode = "";
        }
        if (product == "DYNPACK")
            rooms = document.getElementById('numberOfRooms').value;
        if (product != "DYNPACK") {
            cookieValue = tripType + "|" + depLoc + "|" + arrLoc + "|" + adults + "|" + children + "|" + infants + "|" + depDate + "|" + retDate + "|" + depNodeCode + "|" + arrNodeCode;
        } else {
            cookieValue = depLoc + "|" + arrLoc + "|" + rooms + "|" + adults + "|" + children + "|" + depDate + "|" + retDate + "|" + depNodeCode + "|" + arrNodeCode;
        }
    } else {
        var depLoc = replaceAccentsAndSpecial(document.getElementById('destinationLocation').value);
        if (document.getElementById('departureLocationGeoNodeId')) {
            depNodeCode = document.getElementById('destinationLocationGeoNodeId').value;
        } else {
            depNodeCode = "";
        }
        var depDate = document.getElementById('checkInDate').value;
        var retDate = document.getElementById('checkOutDate').value;
        rooms = document.getElementById('numberOfRooms').value;
        var stars = document.getElementById('accommodationCategory').value;
        var name = document.getElementById('hotelnamefilter').value;
        if (document.getElementById('hotelnamefilter').value == "") {
            name = " ";
        }
        var adults = "";
        var children = "";
        var childrenAge = "";
        for (var i = 1; i <= rooms; i++) {
            adults += document.getElementById('roomAdults' + i).value + "_";
            children += document.getElementById('roomChilds' + i).value + "_";
            for (var j = 1; j <= document.getElementById('roomChilds' + i).value; j++) {
                childrenAge += document.getElementById('ageHab' + i + j).value + "/";
            }
            childrenAge += "_";
        }
        cookieValue = depLoc + "|" + depDate + "|" + retDate + "|" + rooms + "|" + stars + "|" + name + "|" + adults + "|" + children + "|" + childrenAge + "|" + depNodeCode;
    }
    //        alert(currentValue+" "+cookieValue);
    if (currentValue != cookieValue) {
        var expDays = 1;
        var depDateDay = (depDate.split("/")[0].charAt(0) == 0) ? depDate.split("/")[0].charAt(1) : depDate.split("/")[0];
        var depDateMonth = depDate.split("/")[1] - 1;
        var depDateYear = depDate.split("/")[2];
        var exp = new Date(depDateYear, depDateMonth, depDateDay);
        exp.setTime(exp.getTime() + (expDays * 24 * 60 * 60 * 1000));
        //        alert("cookieName: "+cookieName+" myPath: "+myPath);
        document.cookie = cookieName + "=" + cookieValue + ((exp == null) ? "" : ("; expires=" + exp.toUTCString())) + ";path=" + myPath;
    }
}

function checkDestinationsFlightsForm(formId) {
    var errors = 0;
    clearErrors();
    var product;

    if (!validateCity(formId, 'departure', 'flight'))errors ++;
    if (!validateDate(formId, 'departure', errors))errors ++;


    if (!document.getElementById("tripTypeName2").checked) {
        if (!validateDate(formId, 'return', errors))errors ++;
    }

    if (!validatePassengers(formId))errors ++;

    if (!validateMaxAmout('maxPrice'))errors ++;

    if (errors < 1) {
        initSwoosh('buscadestinos', 'vuelos', formId);
        return true;
    } else {
        return false;
    }
}

function makeVisible(elemName) {
    var elem = document.getElementById(elemName);

    if (elem) elem.style.visibility = 'visible';
    if (elem) elem.style.display = 'block';

    return false;
}

function doSearchByDestination(dest) {
    var elem = document.getElementById('arrivalLocation');
    var form = document.getElementById('destinationForm');
    var elemTripName = document.getElementById('tripTypeName');

    if (elem) elem.value = dest;

    if (form) {
        if ((elemTripName) && (elemTripName.value == "ONE_WAY")) {
            form.returnDate.value = onewaylabel;
        }

        initSwoosh("paso1", "vuelos", "destinationForm");

        if ((elemTripName) && (elemTripName.value == "ONE_WAY")) {
            form.returnDate.value = form.departureDate.value;
        }

        form.submit();
    }
}

function hideByClass(classname) {
    var trList = YAHOO.util.Dom.getElementsByClassName(classname);

    for (var i in trList) {
        trList[i].style.display = "none";
    }
}
;

function hideDestinations(classname) {
    showDestinations();

    if (classname == 'pr100') {
        hideByClass('pr500');
        hideByClass('pr100');
    } else if (classname == 'pr500') {
        hideByClass('pr500');
    }

    return false;
}
;

function showDestinations() {
    var trList100 = YAHOO.util.Dom.getElementsByClassName('pr100');
    var trList500 = YAHOO.util.Dom.getElementsByClassName('pr500');

    for (var i in trList500) {
        trList500[i].style.display = "";
    }

    for (var i in trList100) {
        trList100[i].style.display = "";
    }

    return false;
}
;

function checkSearchOffersForm(formId) {
    var errors = 0;
    clearErrors();
    var product;

    if (!validatePassengers(formId))errors ++;

    if (errors < 1) {
        initSwoosh('paso1', 'vuelos', formId);
        return true;
    } else {
        return false;
    }
}
var isInvoiceRequired = false;
function checkTravellerAndBuyer(formId, productType,isUpselling) {
    var errors = 0;
    var paso = (isUpselling)?"paso31":"paso3";
    clearErrors();
    var selectTravellerAndBuyerForm = document.getElementById("selectTravellerAndBuyer");

    if (!checkTravellers(selectTravellerAndBuyerForm, productType + "Passengers")) {
        errors++;
    }
    if (!checkBuyer(productType + "Passengers")) {
        errors++;
    }
    if (isInvoiceRequired) {
        if (!checkInvoiceData(productType + "Passengers")) {
            errors++;
        }
    }    
    
    if (errors < 1) {
        initSwoosh(paso, 'vuelos', formId);
        return true;
    } else {
        gaTrackPageview("/" + productType + "/error/validation/passengers");
        return false;
    }
}
function checkInvoiceData(gaFormName) {
    var errors = 0;

    var nameField = document.getElementById("invoiceName");
    var idField = document.getElementById("invoiceId");
    var addressField = document.getElementById("invoiceAddress");
    var cityField = document.getElementById("invoiceCity");
    var zipCodeField = document.getElementById("invoiceZipcode");
    var emailField = document.getElementById("invoiceMail");
    if (!isFieldFilled(nameField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + nameField.id);
    }
    if (!isFieldFilled(idField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + idField.id);
    }
    if (!isFieldFilled(addressField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + addressField.id);
    }
    if (!isFieldFilled(cityField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + cityField.id);
    }
    if (!isFieldFilled(zipCodeField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + zipCodeField.id);
    }
    if (!validateEmail(emailField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "validateEmail-" + emailField.id);
    }
    return (errors < 1);
}
function checkBuyer(gaFormName) {
    var errors = 0;

    var nameField = document.getElementById("name");
    var lastNamesField = document.getElementById("lastNames");
    var emailField = document.getElementById("mail");
    var idTypeField = document.getElementById("buyerIdentificationTypeName");
    var idField = document.getElementById("identification");
    var addressField = document.getElementById("address");
    var cityField = document.getElementById("cityName");
    var regionField = document.getElementById("stateName");
    var zipCodeField = document.getElementById("zipCode");
    var phoneNumber1Field = document.getElementById("phoneNumber1");
    var websiteCode = document.getElementById("websiteCode");
    if (!isFieldFilled(nameField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "fieldLength-Buyer" + nameField.id);
    } else {
        if (!lengthHigher(2, nameField)) {
            errors++;
            gaTrackEvent("form error", gaFormName, "fieldLength-Buyer" + nameField.id);
        } else {
            if (!validateJustLetters(nameField)) {
                errors++;
                gaTrackEvent("form error", gaFormName, "justLetters-Buyer" + nameField.id);
            }
        }
    }
    if (!isFieldFilled(lastNamesField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "fieldLength-" + lastNamesField.id);
    } else {
        if (!lengthHigher(2, lastNamesField)) {
            errors++;
            gaTrackEvent("form error", gaFormName, "fieldLength-" + lastNamesField.id);
        } else {
            if (!validateJustLetters(lastNamesField)) {
                errors++;
                gaTrackEvent("form error", gaFormName, "justLetters-" + lastNamesField.id);
            }
        }
    }
    if (!validateEmail(emailField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "validateEmail-" + emailField.id);
    }
    if (!isFieldFilled(idField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + idField.id);
    } else {

        // Test UX[15611] Passengers Page UX Improvements
        var idVal = "";
        if ((!(typeof allowChangeClass === "undefined")) && (allowChangeClass == "NewForm")) {
            idVal = $('input:checked[name="buyerIdentificationTypeName"]').val();
        } else {
            idVal = idTypeField.value;
        }

        if (idVal == "NIF" || idVal == "NIE") {
            if (!isValidID(idField, idVal)) {
                errors++;
                gaTrackEvent("form error", gaFormName, "noValidId-" + idVal);
            }
        }
        // Test UX[15611] Passengers Page UX Improvements
    }
    if (!isFieldFilled(addressField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + addressField.id);
    }
    if (!isFieldFilled(cityField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + cityField.id);
    }
    if (websiteCode != null && websiteCode.value == 'US') {
        if (!isFieldFilled(regionField)) {
            errors++;
            gaTrackEvent("form error", gaFormName, "noFieldFilled-" + regionField.id);
        }
    }
    if (!isFieldFilled(zipCodeField)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + zipCodeField.id);
    }
    if (!isFieldFilled(phoneNumber1Field)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + phoneNumber1Field.id);
    } else {
        if (!validateMobile(phoneNumber1Field)) {
            errors++;
            gaTrackEvent("form error", gaFormName, "validateMobile-" + phoneNumber1Field.id);
        }
    }

    return (errors < 1);
}
var frequentFlyerAirlineCodesSetFieldValue = "";
function checkTravellers(selectTravellerAndBuyerForm, gaFormName) {
    initFrequentFlyerAirlineCodesSetFieldValue();
    var errors = 0;
    var dayOfBirthValue, monthOfBirthValue, yearOfBirthValue, elementId, identificationExpirationDay, identificationExpirationMonth, identificationExpirationYear;
    var yearInput, dayInput, monthInput;
    var errorInIdExpField = {"identificationExpirationDay" : false, "identificationExpirationMonth" : false, "identificationExpirationYear": false};
    var idExpFieldLength = {"identificationExpirationDay" : 0, "identificationExpirationMonth" : 0, "identificationExpirationYear": 0};

    for (var i = 0; i < selectTravellerAndBuyerForm.elements.length; i++) {
        if (selectTravellerAndBuyerForm.elements[i].id) {
            elementId = selectTravellerAndBuyerForm.elements[i].id;
        } else {
            elementId = "";
        }
        if (document.getElementById(elementId)) {

            var field = document.getElementById(elementId);
            var tagName = field.tagName;
            var tagType = field.type;
            if (elementId.indexOf("_") != -1) {
                var PaxFieldId = elementId.substr(0, elementId.indexOf("_"));
                var PaxInd = elementId.substr(elementId.indexOf("_") + 1, elementId.length);
                if (tagName == "INPUT" && (tagType == "text" || tagType == "number" || tagType == "email")) {
                	// anyadido && PaxFieldId !="identificationExpirationYear" && PaxFieldId !="identificationExpirationMonth" && PaxFieldId !="identificationExpirationDay" 
                	// para que no compruebe para cada campo de la fecha de cadudidad que esta vacio, porque muestra tres veces el error
                    // esto se comprobara en el if (PaxFieldId == "identificationExpirationYear") 
                	if (PaxFieldId != "companyMemberNum" && PaxFieldId != "secondLastName" && PaxFieldId !="identificationExpirationYear" && PaxFieldId !="identificationExpirationMonth" && PaxFieldId !="identificationExpirationDay") {
                        if (!isFieldFilled(PaxFieldId, PaxInd)) {
                            errors++;
                            gaTrackEvent("form error", gaFormName, "noFieldFilled-" + PaxFieldId);
                        } else {
                            if (PaxFieldId == "name" || PaxFieldId == "firstLastName") {
                                if (!lengthHigher(2, PaxFieldId, PaxInd)) {
                                    errors++;
                                    gaTrackEvent("form error", gaFormName, "fieldLength-" + PaxFieldId);
                                } else {
                                    if (!validateJustLetters(PaxFieldId, PaxInd)) {
                                        errors++;
                                        gaTrackEvent("form error", gaFormName, "justLetters-" + PaxFieldId);
                                    }
                                }
                            }
                            if (PaxFieldId == "identification") {
                                var identificationTypeName;
                                // Test UX[15611] Passengers Page UX Improvements
                                if ((!(typeof allowChangeClass === "undefined")) && (allowChangeClass == "NewForm")) {
                                    // Test UX[15611] Passengers Page UX Improvements - B
                                    for (var j = 0; document.getElementById(j+"identificationTypeId_" + PaxInd); j++) {
                                        if (document.getElementById(j+"identificationTypeId_" + PaxInd).checked) {
                                            identificationTypeName = document.getElementById(j+"identificationTypeId_" + PaxInd);
                                            break;
                                        }
                                    }
                                } else {
                                    // Test UX[15611] Passengers Page UX Improvements - original y/o notest
                                    identificationTypeName = document.getElementById("identificationTypeName_" + PaxInd);
                                }

                                if (identificationTypeName.value == "NIF" || identificationTypeName.value == "NIE") {
                                    if (!isValidID(PaxFieldId, identificationTypeName.value, PaxInd)) {
                                        errors++;
                                        gaTrackEvent("form error", gaFormName, "noValidId-" + identificationTypeName.value + "-" + PaxFieldId);
                                    }
                                }

                            }
                        }
                    }
                    if (PaxFieldId == "identificationExpirationYear") {
                        var identificationExpirationDayFieldLength = (document.getElementById('identificationExpirationDay_' + PaxInd)).value.length;
                        var identificationExpirationMonthFieldLength = (document.getElementById('identificationExpirationMonth_' + PaxInd)).value.length;
                        var identificationExpirationYearFieldLength = (document.getElementById('identificationExpirationYear_' + PaxInd)).value.length;
                        if (identificationExpirationDayFieldLength > 0 && identificationExpirationMonthFieldLength > 0 && identificationExpirationYearFieldLength > 0) {
	                        errors += validateIdentificationExpirationDate(PaxInd);
	                        gaTrackEvent("form error", gaFormName, "identificationExpirationYear");
                        }
                    }

                    if (PaxFieldId == "yearOfBirth") {
                        yearInput = field;
                        yearOfBirthValue = field.value;
                    }
                    if (PaxFieldId == "companyMemberNum") {
                        handleFrequentFlyerAirlineCodesSet(PaxFieldId, PaxInd);
                    }
                } else if (tagName == "SELECT") {
                    if (PaxFieldId == "dayOfBirth") {
                        dayInput = field;
                        dayOfBirthValue = field.value;
                    }
                    if (PaxFieldId == "monthOfBirth") {
                        monthInput = field;
                        monthOfBirthValue = field.value;
                    }
                }
                if (dayOfBirthValue && monthOfBirthValue && yearOfBirthValue) {
                    if (PaxFieldId != "companyMemberNum" && PaxFieldId != "company") {
                        var paxType = document.getElementById("paxType" + PaxInd).value;
                    }
                    var returnDate = document.getElementById("retDate").value;
                    if (PaxFieldId == "yearOfBirth") {
                        //if(paxType=="ADULT"){
                        if (!isDayWithinMonth(dayOfBirthValue, monthOfBirthValue, yearOfBirthValue, PaxFieldId, PaxInd)) {
                            errors++;
                            gaTrackEvent("form error", gaFormName, "dateFormat-" + PaxFieldId);
                        } else {
                            if (!isYearBeforeToday(yearOfBirthValue, PaxFieldId, PaxInd)) {
                                errors++;
                                gaTrackEvent("form error", gaFormName, "dateBeforeToday-" + PaxFieldId);
                            } else {
                                if (isInputYearthisYear) {
                                    if (!isMonthBeforeToday(monthOfBirthValue, PaxFieldId, PaxInd)) {
                                        errors++;
                                        gaTrackEvent("form error", gaFormName, "monthBeforeToday-" + PaxFieldId);
                                    }

                                }
                            }
                        }
                        if (!isPaxTypeAge(paxType, returnDate, dayOfBirthValue, monthOfBirthValue, yearOfBirthValue, PaxFieldId, PaxInd)) {
                            errors++;
                            gaTrackEvent("form error", gaFormName, "paxTypeAge-" + PaxFieldId);
                        }
                        monthOfBirthValue = parseInt(monthOfBirthValue);
                        monthOfBirthValue = (monthOfBirthValue < 10) ? "0" + monthOfBirthValue : monthOfBirthValue + "";
                        var ibd = parseInt(yearOfBirthValue + monthOfBirthValue + dayOfBirthValue);
                        if (!bDateBeforeToday(ibd, dayInput, monthInput, yearInput, 'birthDateChilds')) {
                            errors++;
                        }
                    }
                }
            }
        }
    }
    return (errors < 1);
}
function checkGuests(travellerAndBuyerFormId) {
    var errors = 0;
    var elementId, identificationExpirationDay, identificationExpirationMonth, identificationExpirationYear;
    var formElements = $('#' + travellerAndBuyerFormId).map(function() {
        return $.makeArray(this.elements);
    });
    for (var i = 0; i < formElements.length; ++i) {
        if ($(formElements[i]).attr('id') && $(formElements[i]).attr('id') != "" && $(formElements[i]).attr('id').indexOf("_") != -1) {
            var formElement = $(formElements[i]);
            var guestsPartsArray = formElement.attr('id').split("_");
            var guestFieldId = guestsPartsArray[0];
            if (guestFieldId != "travellerTypeName" && guestFieldId != "secondLastName" && guestFieldId != "age") {
                var guestType = guestsPartsArray[1];
                var guestTypeNum = guestsPartsArray[2];
                var roomNum = guestsPartsArray[3];
                var guestIndexes = {guestType:guestType,guestTypeNum:guestTypeNum,roomNum:roomNum};
                //                console.log(guestFieldId+"_"+guestType+"_"+guestTypeNum+"_"+roomNum);
                if (!isFieldFilled(guestFieldId, "", guestIndexes)) {
                    errors++;
                } else {
                    if (guestFieldId == "name" || guestFieldId == "firstLastName") {
                        if (!lengthHigher(2, guestFieldId, "", guestIndexes)) {
                            errors++;
                        } else {
                            if (!validateJustLetters(guestFieldId, "", guestIndexes)) {
                                errors++;
                            }
                        }
                    }
                    if (guestFieldId == "identification") {
                        var identificationTypeName = $("#identificationTypeName_" + guestType + "_" + guestTypeNum + "_" + roomNum);
                        if (identificationTypeName.val() == "NIF" || identificationTypeName.val() == "NIE") {
                            if (!isValidID(guestFieldId, identificationTypeName.val(), "", guestIndexes)) {
                                errors++;
                            }
                        }
                    }
                    if (guestFieldId == "identificationExpirationYear") {
                        var identificationExpirationDayFieldLength = ($('#identificationExpirationDay_' + guestType + "_" + guestTypeNum + "_" + roomNum)).val().length;
                        var identificationExpirationMonthFieldLength = ($('#identificationExpirationMonth_' + guestType + "_" + guestTypeNum + "_" + roomNum)).val().length;
                        var identificationExpirationYearFieldLength = ($('#identificationExpirationYear_' + guestType + "_" + guestTypeNum + "_" + roomNum)).val().length;
                        if (identificationExpirationDayFieldLength > 0 && identificationExpirationMonthFieldLength > 0 && identificationExpirationYearFieldLength > 0) {
                            errors += validateIdentificationExpirationDate(guestType + "_" + guestTypeNum + "_" + roomNum, guestIndexes);
                        }
                    }
                }
            }
        }
    }
    return (errors < 1);
}
function checkRepricing(formId) {
    var errors = 0;
    clearErrors();
    var acceptedconditions = document.getElementById("acceptedconditions");
    if (!validateConditions(acceptedconditions, 'payment'))errors++;
    if (errors < 1) {
        initSwoosh('paso4', 'vuelos', formId);
        return true;
    } else {
        return false;
    }
    //
}
function checkPayment(productType, hasUpselling) {
    var paso = 'paso4';
    var productForWait = productType;
    // Tracking del submit con error inline
    try {
        var inlineError = howManyPaymentInlineErrors();
        if (inlineError > 0) {
            gaTrackEvent("inline error", productType + "Payment", "submitWithInlineError");
        }
    } catch (err) {}
    
    var errors = 0;
    clearErrors();
    
    //CR14074 New page for upselling before the confirmation page
    if (!hasUpselling) { // Only we need to validate SMS in the old flow, when no exists upselling page.
    	if (findSmsPhoneErrrors()) {
    		errors++;
    	}
    	
    	for (var i = 0; i < invalidSmsNums.length; ++i) {
            invalidSmsNums[i].value = "";
        }
	}
    //CR14074 New page for upselling before the confirmation page END
    

    if (productType == 'hotels') {
        productForWait = 'hoteles';
        //    	if (!checkTravellers(document.getElementById("closeBookingFromPayment"), productType + "Passengers")) {
        //        	errors++;
        //    	}
        if (!checkGuests("closeBookingFromPayment")) {
            errors++;
        }
        if (!checkBuyer(productType + "Passengers")) {
            errors++;
        }
    } else if (productType == 'dynamic') {
        productForWait = 'dynpack';
        paso = 'paso6';
    }
    
    //CR14074 New page for upselling before the confirmation page
    if (!hasUpselling) {//Same behavior as in SMS validation
	    if (document.getElementById("closeBookingFromPayment")["radioButtonInsurance"]) {
	        if (!validateInsurances()) {
	            errors++;
	            gaTrackEvent("form error", productType + "Payment", "selectAnInsurance");
	        }
	    }
    }
    //CR14074 New page for upselling before the confirmation page END
    var selectedCollectionMethodTypeName;
    var radios = document.getElementById("closeBookingFromPayment")["collectionMethodTypeName"];
    var acceptedconditions = document.getElementById("acceptedconditions");
    if (radios.length) {
        for (var i = 0; i < radios.length; ++i) {
            if (radios[i].checked) selectedCollectionMethodTypeName = radios[i].id;
        }
    } else {
        selectedCollectionMethodTypeName = radios.id;
    }
    if (!selectedCollectionMethodTypeName) {
        showPaxAlertInDiv("noPaymethod");
        gaTrackEvent("form error", productType + "Payment", "noPaymethod");
        gaTrackPageview("/vuelos/error/validation/payment");
        return false;
    }
    switch (selectedCollectionMethodTypeName) {
    case "creditPaymentMethod":
        if (!checkCreditCardMethod(productType + "Payment")) {
            errors++;
        }
        break;
    case "ELVPaymentMethod":
        if (!checkELVMethod(productType + "Payment")) {
            errors++;
        }
        break;
    case "paypalPaymentMethod":
        break;
    case "bankTransferPaymentMethod":
        break;
    }
    if (!validateConditions(acceptedconditions, 'payment')) {
        errors++;
        gaTrackEvent("form error", productType + "Payment", "noConditionsPay");
    }
    if (errors < 1) {
        initSwoosh(paso, productForWait, 'closeBookingFromPayment');
		if($.browser.webkit) {
			setTimeout('check_waitingTime(true)', 2000);			
		} else {			
			check_waitingTime(true);
		}
    }	
    checkInlineConditions();
    gaTrackPageview("/" + productType + "/error/validation/payment");
    return false;
}

function checkCreditCardMethod(gaFormName) {
    var errors = 0;
    var expirationErrors = 0;
    var cardTypeCodeSelect = document.getElementById("cardTypeCode");
    var cardOwner = document.getElementById("cardOwner");
    var cardNumber = document.getElementById("cardNumber");
    var cardExpirationMonth = document.getElementById("cardExpirationMonth");
    var cardExpirationYear = document.getElementById("cardExpirationYear");
    var minCardExpMonth = document.getElementById("minCardExpMonth");
    var minCardExpYear = document.getElementById("minCardExpYear");
    var cardSecNum = document.getElementById("cardSecNum");
    for (var i = 0; i < cardTypeCodeSelect.length; ++i) {
        if (cardTypeCodeSelect.options[i].selected) {
            if ((cardTypeCodeSelect.options[i].id).indexOf('-3D') != -1) {
                set3DPaymentMethod("true");
            }
        }
    }

    //    return false;
    if (!validateNotEmptySelect(cardTypeCodeSelect)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "emptySelect-" + cardTypeCodeSelect.id);
    }
    if (!isFieldFilled(cardOwner)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFiledFilled-" + cardOwner.id);
    } else {
        if (!validateJustLetters(cardOwner)) {
            errors++;
            gaTrackEvent("form error", gaFormName, "justLetters-" + cardOwner.id);
        }
    }
    if (!isFieldFilled(cardNumber)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFiledFilled-" + cardNumber.id);
    } else {
        if (!validateCardNumber(cardNumber, cardNumber.value, cardTypeCodeSelect.value)) {
            errors++;
            gaTrackEvent("form error", gaFormName, "cardNumber-" + cardTypeCodeSelect.value);
        }
    }
    if (!isFieldFilled(cardExpirationMonth)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + cardExpirationMonth.id);
        expirationErrors++;
    }

    if (!isFieldFilled(cardExpirationYear)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + cardExpirationYear.id);
        expirationErrors++;
    }
    if (expirationErrors < 1) {
        if (!validateExpirationDate(cardExpirationMonth, cardExpirationYear)) {
            errors++;
            gaTrackEvent("form error", gaFormName, "expirationDate-creditcard");
            expirationErrors++;
        }
    }

    if (expirationErrors < 1) {
        if (!validateMinimumExpirationDate(cardExpirationMonth, cardExpirationYear, minCardExpMonth, minCardExpYear))errors++;
    }


    if (!isFieldFilled(cardSecNum)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + cardSecNum.id);
    } else {
        if (!validateSecurityCode(cardSecNum, cardTypeCodeSelect.value)) {
            errors++;
            gaTrackEvent("form error", gaFormName, "validateSecurityCode-" + cardTypeCodeSelect.value);
        }
    }

    return (errors < 1);
}
function checkELVMethod(gaFormName) {
    var errors = 0;
    var ELVFirstName = document.getElementById("ELVFirstName");
    var ELVAccount = document.getElementById("ELVAccount");
    var ELVSurname = document.getElementById("ELVSurname");
    var ELVBank = document.getElementById("ELVBank");
    var ELVCredit = document.getElementById("ELVCredit");
    if (!isFieldFilled(ELVFirstName)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + ELVFirstName.id);
    }
    if (!isFieldFilled(ELVAccount)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + ELVAccount.id);
    }
    if (!isFieldFilled(ELVSurname)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + ELVSurname.id);
    }
    if (!isFieldFilled(ELVBank)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + ELVBank.id);
    }
    if (!isFieldFilled(ELVCredit)) {
        errors++;
        gaTrackEvent("form error", gaFormName, "noFieldFilled-" + ELVCredit.id);
    }

    return (errors < 1);
}
function initFrequentFlyerAirlineCodesSetFieldValue() {
    frequentFlyerAirlineCodesSetFieldValue = "";
}
function handleFrequentFlyerAirlineCodesSet(PaxFieldId, PaxInd) {
    var company = "";
    var numOfFreqAirlines = document.getElementById("numOfFreqAirlines_" + PaxInd.substr(0, 1)).value;
    var frequentFlyerAirlineCodesSetField = document.getElementById("frequentFlyerAirlineCodes_" + PaxInd.substr(0, 1));
    var companySelect = document.getElementById("company_" + PaxInd);
    for (var i = 0; i < companySelect.length; ++i) {
        if (companySelect.options[i].selected) {
            company = companySelect.options[i].value;
        }
    }
    var companyMemberNum = document.getElementById("companyMemberNum_" + PaxInd).value;
    if (frequentFlyerAirlineCodesSetFieldValue == "") {
        if (company != "" && companyMemberNum != "") {
            frequentFlyerAirlineCodesSetFieldValue = company + "," + companyMemberNum;
        }
    } else {
        if (company != "" && companyMemberNum != "") {
            frequentFlyerAirlineCodesSetFieldValue += ";" + company + "," + companyMemberNum;
        }
    }
    frequentFlyerAirlineCodesSetField.value = frequentFlyerAirlineCodesSetFieldValue;

}
var warningInterval1, warningInterval2, finalWarningInterval;
function checkSessionTimeout(maxTime, formId, trackingName) {
    var firstTimeToLimit = 10;
    var secondTimeToLimit = 5;
    var minimumTimeInPage = 5;
    var closeWarningTime = (maxTime * 60 * 1000);
    var warning1Time = (maxTime - firstTimeToLimit) * 60 * 1000;
    var warning2Time = (maxTime - secondTimeToLimit) * 60 * 1000;
    if (warning1Time >= minimumTimeInPage) {
        warningInterval1 = setInterval("fireWarning('" + (maxTime - firstTimeToLimit) + "', '" + maxTime + "', '" + 1 + "', '" + trackingName + "')", warning1Time);
    }
    if (warning2Time >= minimumTimeInPage) {
        warningInterval2 = setInterval("fireWarning('" + (maxTime - secondTimeToLimit) + "', '" + maxTime + "', '" + 2 + "', '" + trackingName + "')", warning2Time);
    }
    finalWarningInterval = setInterval("fireFinalWarning('" + maxTime + "', '" + formId + "', '" + trackingName + "')", closeWarningTime);
}
function fireWarning(timeToAlert, maxTime, warningIntervalInd, trackingName) {
    var warInterval = eval("warningInterval" + warningIntervalInd);
    var timeLeft = maxTime - timeToAlert;

    gaTrackEvent("form error", trackingName, "TimeOutWarning-" + warningIntervalInd);

    alertSessionTimeoutWarning(timeToAlert, timeLeft);
    clearInterval(warInterval);
}
function fireFinalWarning(maxTime, formId, trackingName) {
    //    alert("FinalWarning");
    gaTrackEvent("form error", trackingName, "finalTimeOutWarning");

    var myForm = document.getElementById(formId);
    alertSessionTimeout(maxTime);
    clearInterval(finalWarningInterval);
    //myForm.action = "";
    myForm.onsubmit = function() {
        alertSessionTimeout(maxTime);
        return false;
    };
    //
}

function changeShuttleDestination(depLocation, arrLocation) {
    var oShuttleFlightFrom = document.getElementById(depLocation);
    var oArrivalCity = document.getElementById(arrLocation);

    if (oShuttleFlightFrom.selectedIndex == 1) {
        oArrivalCity.value = "Barcelona";
    } else {
        oArrivalCity.value = "Madrid";
    }
}

function changeSegmentVisibility(idSegment, idDate) {
    var oSegment = document.getElementById(idSegment);
    var oInput = document.getElementById(idDate);

    if (oSegment != null) {
        if (oSegment.style.display == "none") {
            oSegment.style.display = "block";
        } else {
            oSegment.style.display = "none";
        }
    }

    if (oInput != null) {
        oInput.value = '';
    }
}

var SHUTTLE_TRIP = 'true';
var NORMAL_TRIP = 'false';

function checkShuttleFlightsForm() {
    //Limpiamos errores
    clearErrors();

    //Fecha a utilizar en los trayectos de puente aereo - fecha de hoy + 2 dias
    var fakeDate = new Date();
    fakeDate.setDate(fakeDate.getDate() + 2);

    // Check date formats and values
    var tripType = (document.getElementById('tripTypeName').checked) ? 'ROUND_TRIP' : 'ONE_WAY';
    var depType = document.getElementById('airShuttleOutBound').value;
    var depDate = document.getElementById('departureDate');
    var retType = document.getElementById('airShuttleInBound').value;
    var retDate = document.getElementById('returnDate');

    // check fecha salida
    if (depType == NORMAL_TRIP) {
        if (!validateEmptyDate(depDate, 'departure', '')) return false;
        if (!validateFormatDate(depDate, 'departure', '')) return false;

        var diafecha0 = getDiaFecha(depDate);
        var mesfecha0 = getMesFecha(depDate);
        var anyofecha0 = getAnyoFecha(depDate);

        if (!validateDateNoNan(depDate, diafecha0, mesfecha0, anyofecha0, 'departure', '')) return false;
        if (!validateDateAfterToday(depDate, diafecha0, mesfecha0, anyofecha0, 'departure', '')) return false;
    } else {
        depDate.value = (fakeDate.getDate() < 10 ? '0' : '') + fakeDate.getDate() + "/" + (fakeDate.getMonth() < 9 ? '0' : '') + (fakeDate.getMonth() + 1) + "/" + fakeDate.getFullYear();
    }

    // check fecha de retorno
    if (tripType != 'ONE_WAY') {
        if (retType == NORMAL_TRIP) {
            if (!validateEmptyDate(retDate, 'return', '')) return false;
            if (!validateFormatDate(retDate, 'return', '')) return false;

            var diafecha1 = getDiaFecha(retDate);
            var mesfecha1 = getMesFecha(retDate);
            var anyofecha1 = getAnyoFecha(retDate);

            if (!validateDateNoNan(retDate, diafecha1, mesfecha1, anyofecha1, 'return', '')) return false;
            if (!validateDateAfterToday(retDate, diafecha1, mesfecha1, anyofecha1, 'return', '')) return false;

            // check fecha de salida y retorno
            if (depType == NORMAL_TRIP) {
                var iDep0 = parseInt(anyofecha0 + mesfecha0 + diafecha0);
                var iDep1 = parseInt(anyofecha1 + mesfecha1 + diafecha1);

                if (iDep0 > iDep1) {
                    changeToClass(depDate, "borderRed");
                    showAlertInDiv('secondAfterFirst', 'departue');
                    document.getElementById('departureDate').focus();
                    return false;
                }
            }
        } else {
            retDate.value = (fakeDate.getDate() < 10 ? '0' : '') + fakeDate.getDate() + "/" + (fakeDate.getMonth() < 9 ? '0' : '') + (fakeDate.getMonth() + 1) + "/" + fakeDate.getFullYear();
        }
    }

    initSwoosh("shuttle", "vuelos", "shuttleFlightsSearch");

    return true;
}

function checkNLConfirmation() {
    clearErrors();
    var acceptedNewsletterBox = document.getElementById("acceptedNewsletter");
    var newsletterDiv = document.getElementById("newsletterDiv");
    if (!acceptedNewsletterBox.checked) {
        changeToClass(newsletterDiv, "borderRed");
        showAlertInDiv('noNL', '');
        return false;
    } else {
        changeToClass(newsletterDiv, "");
        return true;
    }
}

function checkRegisterConfirmation() {
    clearErrors();
    var product;
    var errors = 0;

    var emailField = document.getElementById("email");
    var passField = document.getElementById("password");
    var passField2 = document.getElementById("password2");
    var conditionsField = document.getElementById("acceptedGeneralConditions");

    if (!validateEmail(emailField))errors++;
    if (!validatePass(passField))errors++;
    if (!validatePass(passField2))errors++;
    if (!validateEqualValues(passField.value, passField2.value, "pass")) {
        changeToClass(passField, "borderRed");
        changeToClass(passField2, "borderRed");
        errors++;
    } else {
        changeToClass(passField, "");
        changeToClass(passField2, "");
    }
    if (!validateConditions(conditionsField))errors++;

    if (errors < 1) {
        return true;
    } else {
        return false;
    }
}

function tripTypeSelectedShuttle(formId, value) {
    tripTypeSelected(formId, value);

    var returnShuttleTypeField = document.getElementById('airShuttleInBound');

    if (value == "ONE_WAY") {
        returnShuttleTypeField.disabled = true;
    } else if (value == "ROUND_TRIP") {
        returnShuttleTypeField.disabled = false;
    }
}
function swapVisibility(elementId) {
    if (document.getElementById(elementId).style.display != 'block') {
        document.getElementById(elementId).style.display = 'block';
    } else {
        document.getElementById(elementId).style.display = 'none';
    }
}
function html_entity_decode(str) {
    var ta = document.createElement("textarea");
    ta.innerHTML = str.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    return ta.value;
}
function showFlightsSearchEnginePopUnder() {
    var websiteCode = document.getElementById("websiteCode").value.toLowerCase();
    var numOfPopUnders = 0;
    var hasLiligoPopUnder = document.getElementById("hasLiligoPopUnder");
    var liligoRatio = 0;
    var rdmLiligo = 0;

    if (document.getElementById("liligoRatio")) {
        liligoRatio = document.getElementById("liligoRatio").value;
        rdmLiligo = Math.floor(Math.random() * 101);
    }

    if (liligoBrowserAllowed() && hasLiligoPopUnder != null && hasLiligoPopUnder.value == 'true' && liligoRatio >= rdmLiligo) {
        numOfPopUnders++;
        var depCode = document.getElementById("departureLocation");
        var retCode = document.getElementById("arrivalLocation");
        var departureDate = document.getElementById("departureDate");
        var depDay = getDiaFecha(departureDate);
        var depMonth = getMesFecha(departureDate);
        var depYear = getAnyoFecha(departureDate);
        var retDay = depDay;
        var retMonth = depMonth;
        var retYear = depYear;
        if (!isOneWay) {
            var returnDate = document.getElementById("returnDate");
            retDay = getDiaFecha(returnDate);
            retMonth = getMesFecha(returnDate);
            retYear = getAnyoFecha(returnDate);
        }
        var url = 'http://results.edreams.' + websiteCode + '/edreams/siteunder_ta.jsp?FROM=' + depCode.value + '&TO=' + retCode.value + '&DEPART_DD=' + depDay + '&DEPART_MM=' + depMonth + '&DEPART_YYYY=' + depYear + '&RETOUR_DD=' + retDay + '&RETOUR_MM=' + retMonth + '&RETOUR_YYYY=' + retYear;
        var popUnderWindow = self.window.open(url, 'adsWindow', 'width=650,height=415,scrollbars=yes');
        popUnderWindow.blur();
        
        try{
            popUnderWindow.Init = function(e) {
                with (e) {
                    Params = e.Params;
                    Main = function(){
                        if (typeof window.mozPaintCount != "undefined") {
                            var x = window.open("about:blank");
                            x.close();
                        }
                        var popURL = Params.PopURL;
                        try { opener.window.focus(); }
                        catch (err) { }
                        window.location = popURL;
                    }
                    Main();
                }
            };
            popUnderWindow.Params = {PopURL: url}
            popUnderWindow.Init(popUnderWindow);
        }catch(err){}
    }
    return numOfPopUnders;
}
//hotels
function checkHotelsSearch(formId) {
    clearErrors();
    var errors = 0;

    if (!validateCity(formId, 'hotel', 'hotel')) errors ++;
    if (!validateDate(formId, 'arrival', errors, false)) errors ++;
    if (!validateDate(formId, 'departure', errors, false)) errors ++;
    if (!validateGuests()) errors ++;

    if (errors < 1) {
        // Tracking de filtros de busqueda de hoteles.
        trackingFilteringSearchHotels();

        parent.initSwoosh("paso1", "hotelesOld", formId);
        return true;
    } else {
        return false;
    }
}

function checkHotelsSearchEngine(formId) {
    clearErrorsB();
    var errors = 0;

    if (!validateCity(formId, 'destination', 'hotel'))errors ++;
    if (!validateDate(formId, 'checkIn', errors, false))errors ++;
    if (!validateDate(formId, 'checkOut', errors, false))errors ++;
    if (!validateThirtyDaysStay())errors ++;
    //if (!validateGuests())errors ++;

    if (errors < 1) {
        initSwoosh("paso1", "hoteles", formId);
        //return true;
    } else {
        return false;
    }
}
function clearErrors(ind) {
    //$('.content-error').css('display','none');
    var docScope;
    var index = (ind) ? '-' + ind : '';
    if (document.getElementById('content-error-form-text' + index)) {
        docScope = document;
    } else {
        docScope = parent.document;
    }
    if (docScope.getElementById('content-error-form-text' + index)) {
        docScope.getElementById('content-error-form-text' + index).innerHTML = "";
    }
    if (docScope.getElementById('content-error-form' + index)) {
        docScope.getElementById('content-error-form' + index).style.display = "none";
    }
    if (docScope.getElementById('content-error-back')) {
        docScope.getElementById('content-error-back').style.display = "none";
    }
}
function openPopUp(url, name, height, width) {
    newwindow = window.open(url, name, 'height=' + height + ',width=' + width + ',location=no');
    if (window.focus) {
        newwindow.focus()
    }
    return false;
}

function liligoBrowserAllowed() {
    // no ofrecemos el pop-under de liligo para smartphones y chrome.
    var agent = navigator.userAgent.toLowerCase();
    var isUAMobile = !!(agent.match(/(iPhone|iPod|iPad|blackberry|android|htc|kindle|lg|midp|mmp|mobile|nokia|opera mini|palm|pocket|psp|sgh|smartphone|sonyericsson|symbian|treo mini)/i));
    var isChrome = !!agent.match(/(chrome)/i);

    return !(isUAMobile || isChrome);
}

var anyParamAdded = false;
var urlBase;
function checkSearchEngineLinear(formId, nonSecureBaseUrl, productType) {
    var result = false;
    if (productType == "FLIGHT") {
        result = checkLinearFlightsForm(formId);
    } else if (productType == "TRAIN") {
        result = checkTrainsForm(formId);
    }
    if ("https:" == window.document.location.protocol && result) {
        urlBase = nonSecureBaseUrl + "/engine/ItinerarySearch/search";

        addParam("buyPath");
        addParam("trip");
        addParam("auxOrBt");
        addParam("searchMainProductTypeName");
        addParam("intCityCode");
        addParam("departureLocationGeoNodeId");
        addParam("departureLocation");
        addParam("departureDate");
        addParam("departureTime");
        addParam("numAdults");
        addParam("numChilds");
        addParam("numInfants");
        addParam("arrivalLocationGeoNodeId");
        addParam("arrivalLocation");
        addParam("image");

        var paramId = "tripTypeName";
        var param = document.getElementById(paramId);
        if (param && param.checked) {
            addParam(paramId);
        } else {
            paramId = "tripType1";
            param = document.getElementById(paramId);
            if (param && param.checked) {
                if (!anyParamAdded) {
                    urlBase = urlBase + '?';
                    anyParamAdded = true;
                } else {
                    urlBase = urlBase + '&';
                }
                urlBase = urlBase + "tripTypeName" + '=' + param.value;
            }
        }
        window.document.location.href = urlBase;
        result = false;
    }
    document.getElementById("collectionTypeEstimationNeeded").value = false;
    document.getElementById("applyAllTaxes").value = false;
    if (document.getElementById("collectionMethodId") != null && document.getElementById("collectionMethodId").value != "0-0") {
        document.getElementById("collectionTypeEstimationNeeded").value = true;
        document.getElementById("applyAllTaxes").value = true;
    }
    return result;
}
function submitFormWithoutValidation(formId, swooshStep) {
    document.getElementById(formId).submit();
    initSwoosh(swooshStep, "dynpack");
}

function submitHotelFormWithoutValidation(formId, swooshStep) {
    document.getElementById(formId).submit();
    parent.initSwoosh(swooshStep, "hoteles");
}

function addParam(paramId) {
    var param = document.getElementById(paramId);
    if (param) {
        if (!anyParamAdded) {
            urlBase = urlBase + '?';
            anyParamAdded = true;
        } else {
            urlBase = urlBase + '&';
        }
        urlBase = urlBase + paramId + '=' + param.value;
    }
}

function changeVisibilityInsuranceTip(id) {
    var tipElement = document.getElementById("insuranceTip" + id);
    var arrowRightElement = document.getElementById("arrowRight" + id);
    var arrowDownElement = document.getElementById("arrowDown" + id);

    if (tipElement && arrowRightElement && arrowDownElement) {
        if (tipElement.style.display == "none") {
            tipElement.style.display = "block";
            arrowDownElement.style.display = "inline";
            arrowRightElement.style.display = "none";
        } else {
            tipElement.style.display = "none";
            arrowDownElement.style.display = "none";
            arrowRightElement.style.display = "inline";
        }
    }
}

function showLegalToolTip(elemName, e, offset) {
    var elem = document.getElementById(elemName);

    if (elem) {
        var posx = 0;
        var posy = 0;
        if (!e) var e = window.event;
        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY) {
            posx = e.clientX + document.body.scrollLeft
                    + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop
                    + document.documentElement.scrollTop;
        }

        elem.style.left = posx + 'px';
        elem.style.top = posy + offset + 'px';
        elem.style.display = 'block';
    }
}

function hideLegalToolTip(elemName) {
    var elem = document.getElementById(elemName);

    if (elem) elem.style.display = 'none';
}

function reloj(maxTime, secondsleft, formId) {
    //    alert("FinalWarning");

    var secondsToPrint = maxseconds % 60;
    var minutesToPrint = (maxseconds - secondsToPrint) / 60;

    secondsToPrint = (secondsToPrint < 10 ) ? ('0' + secondsToPrint) : secondsToPrint;
    minutesToPrint = (minutesToPrint < 10 ) ? ('0' + minutesToPrint) : minutesToPrint;
    document.getElementById("countDown").innerHTML = minutesToPrint + ':' + secondsToPrint;

    if (maxseconds <= 0) {
        alertSessionTimeout(maxTime);
        clearInterval(finalWarningInterval);

        var myForm = document.getElementById(formId);

        //myForm.action = "";
        myForm.onsubmit = function() {
            alertSessionTimeout(maxTime);
            return false;
        }
    } else {
        maxseconds--;
    }
}


//currency
function getCurrencyObject(aValue) {

    var lastDot = "";
    var dotsNum = 0;
    var thousandDot, tempNoThousandDotNum;
    var justNumber, readyNumber;
    var currencyObject = new Object();
    currencyObject.currencySymbol = "";
    var indexCount = false;
    var negative = false;
    for (var i = 0; i < aValue.length; ++i) {
        if (aValue.charAt(i) != "," && aValue.charAt(i) != "." && aValue.charAt(i) != "'") {
            if (!isNumeric(aValue.charAt(i))) {
                currencyObject.currencySymbol += aValue.charAt(i);
                if (!indexCount) {
                    currencyObject.currencySymbolInd = i;
                    indexCount = true;
                }
            } else if (aValue.charAt(i) == '-') {
                negative = true;
            }
        }
    }
    if (aValue.charAt(aValue.length - 1) == ".") {
        lastDot = ".";
    }
    currencyObject.currencySymbol += lastDot;
    if (currencyObject.currencySymbol == "BsF") {
        currencyObject.currencySymbol = "Bs.F";
    } else if (currencyObject.currencySymbol == "S/") {
        currencyObject.currencySymbol = "S/.";
    }
    currencyObject.currencySymbol = currencyObject.currencySymbol.replace("&nbsp;", "");
    if (aValue.indexOf(currencyObject.currencySymbol.charAt(0)) == 0) {
        var firstNumInd = aValue.indexOf(currencyObject.currencySymbol.charAt(currencyObject.currencySymbol.length - 1)) + 1;
        justNumber = aValue.substring(firstNumInd, aValue.length);
    } else {
        var lastNumInd = aValue.indexOf(currencyObject.currencySymbol.charAt(0)) - 1;
        justNumber = aValue.substring(0, lastNumInd).ltrim();
    }
    justNumber = justNumber.ltrim();
    justNumber = justNumber.rtrim();
    justNumber = justNumber.replace("&nbsp;", " ");
    var temDotsArray = new Array();
    for (var i = 0; i < justNumber.length; ++i) {
        var charInNum = justNumber.charAt(i);
        if (!parseInt(charInNum)) {
            if (charInNum != "0") {
                temDotsArray.push(charInNum);
            }
        }
        //        if (justNumber.charAt(i) == "," || justNumber.charAt(i) == "." || justNumber.charAt(i) == "'" || justNumber.charAt(i) == " " || justNumber.charAt(i) == "&nbsp;") {
        //            temDotsArray.push(justNumber.charAt(i));
        //        }
    }
    if (temDotsArray.length > 1 && temDotsArray.length <= 2) {
        currencyObject.thousand = true;
        currencyObject.millions = false;
        currencyObject.thousandDot = temDotsArray[0];
        currencyObject.thousandDotInd = justNumber.indexOf(temDotsArray[0]);

        var thousandNumber = justNumber.substring(0, currencyObject.thousandDotInd);
        var restNumber = justNumber.substring(justNumber.indexOf(temDotsArray[0]) + 1, justNumber.length);
        tempNoThousandDotNum = thousandNumber + restNumber;

    } else if (temDotsArray.length > 2) {
        currencyObject.millions = true;
        currencyObject.millionsDot = temDotsArray[0];
        currencyObject.millionsDotInd = justNumber.indexOf(temDotsArray[0]);

        currencyObject.thousand = true;
        currencyObject.thousandDot = temDotsArray[1];
        currencyObject.thousandDotInd = justNumber.indexOf(temDotsArray[1], currencyObject.millionsDotInd + 1);

        var millionNumber = justNumber.substring(0, currencyObject.millionsDotInd);
        var thousandNumber = justNumber.substring(currencyObject.millionsDotInd + 1, currencyObject.thousandDotInd);
        var restNumber = justNumber.substring(currencyObject.thousandDotInd + 1, justNumber.length);
        tempNoThousandDotNum = millionNumber + thousandNumber + restNumber;

    } else {
        var decimals = justNumber.substring(justNumber.indexOf(temDotsArray[0]) + 1, justNumber.length);
        currencyObject.millions = false;
        if (decimals.length > 2) {
            currencyObject.noDecimals = true;
            currencyObject.thousand = true;
            currencyObject.thousandDot = temDotsArray[0];
            currencyObject.thousandDotInd = justNumber.indexOf(temDotsArray[0]);
            var thousandNumber = justNumber.substring(0, currencyObject.thousandDotInd);
            var restNumber = justNumber.substring(justNumber.indexOf(temDotsArray[0]) + 1, justNumber.length);
            tempNoThousandDotNum = thousandNumber + restNumber;
        } else {
            currencyObject.thousand = false;
            tempNoThousandDotNum = justNumber;
        }
    }
    currencyObject.currencyDot = temDotsArray[temDotsArray.length - 1];
    readyNumber = (tempNoThousandDotNum.indexOf(",") != -1) ? tempNoThousandDotNum.replace(/\,/g, ".") : tempNoThousandDotNum;
    currencyObject.readyNumber = readyNumber;
    if (negative) {
        currencyObject.readyNumber = '-' + readyNumber;
    }
    return currencyObject;
}

function roundValue(value) {
    return  Math.round(value);
}
function floorValue(value) {
    return  Math.floor(value);
}
function ceilValue(value) {
    return  Math.ceil(value);
}
function sortNumber(a, b) {
    return a - b;
}
function assembleCurrency(amount, currencyObject) {
    var amountNum, fullMoney;
    amountNum = amount.toString();
    if (currencyObject.currencyDot == ",") {
        amountNum = amountNum.replace(".", ",");
    }
    if (amountNum.length > 6 || currencyObject.noDecimals) {
        if (!currencyObject.thousandDotInd) {
            currencyObject.thousandDotInd = 1;
            if (currencyObject.currencyDot == ",") {
                currencyObject.thousandDot = ".";
                currencyObject.millionDot = ".";
            } else {
                currencyObject.thousandDot = ",";
                currencyObject.millionDot = ",";
            }
        }
        if (currencyObject.millions) {
            amountNum = amountNum.substring(0, currencyObject.millionsDotInd) + currencyObject.millionsDot + amountNum.substring(currencyObject.millionsDotInd, currencyObject.thousandDotInd - 1) + currencyObject.thousandDot + amountNum.substring(currencyObject.thousandDotInd - 1, amountNum.length);
        } else {
            amountNum = amountNum.substring(0, currencyObject.thousandDotInd) + currencyObject.thousandDot + amountNum.substring(currencyObject.thousandDotInd, amountNum.length);
        }
    }
    if (currencyObject.currencySymbolInd == 0) {
        fullMoney = currencyObject.currencySymbol + " " + amountNum;
    } else {
        //    alert("currencyObject.currencySymbol: "+currencyObject.currencySymbol);
        fullMoney = amountNum + " " + currencyObject.currencySymbol;
    }

    return fullMoney;
}
//currency ends

var semaforoShowSearchEngine = false;
function showSearchEngine() {
    if (semaforoShowSearchEngine == false) {
        var searchEngineObj = $("#searchEngineNewFlow");
        var gapSearchEngineObj = $("#gapSearchEngine");
        var searchInfomationObj = $("#searchInfomation");
        var boxNewSearchObj = $("#boxNewSearch");
        var hasToOpen = false;
        var heightSearchEngine = "";
        var heightSearchInfo = "";

        semaforoShowSearchEngine = true;
        if (searchEngineObj.css("display") == 'block') {
            hasToOpen = false;
            heightSearchEngine = searchEngineObj.outerHeight(true) + "px";
            heightSearchInfo = gapSearchEngineObj.outerHeight(true) + "px";
        } else {
            hasToOpen = true;
            searchEngineObj.css("display", "block");
            heightSearchEngine = searchEngineObj.outerHeight(true) + "px";
            searchEngineObj.css("display", "none");
            heightSearchInfo = gapSearchEngineObj.outerHeight(true) + "px";
        }

        if (hasToOpen) {
            gapSearchEngineObj.css("display", "block");
            searchInfomationObj.css("display", "none");
            boxNewSearchObj.css("width", '180px');

            searchEngineObj.css("height", heightSearchInfo);
            searchEngineObj.css("display", "block");
            searchEngineObj.animate({height:heightSearchEngine}, 'slow', function() {
                semaforoShowSearchEngine = false;
            });
        } else {
            searchEngineObj.animate({height:heightSearchInfo}, 'slow', function() {
                searchEngineObj.css("display", "none");
                searchEngineObj.css("height", "0px");
                searchEngineObj.css("height", '');
                gapSearchEngineObj.css("display", "none");
                searchInfomationObj.css("display", "block");
                boxNewSearchObj.css("width", '');
                semaforoShowSearchEngine = false;
            });
        }
    }
}
/**
 * Tracking filtros de hoteles en pagina resultados de vuelos+hotel
 */
function trackingFilteringHotels() {
    var distance = document.getElementById('distanceLimit');
    var stars = document.getElementById('minimumAccommodationCategory');
    var name = document.getElementsByName('accommodationName');
    var distanceLimit = 'distanceLimit';
    var starsCategory = 'minimumAccommodationCategory';

    if (distance) {
        distanceLimit += distance.value;
        gaTrackEvent("form filter", "filtering_search_results", distanceLimit);
    }
    if (stars) {
        starsCategory += stars.value;
        gaTrackEvent("form filter", "filtering_search_results", starsCategory);
    }
    if (name[0] && name[0].value != '' && name[0].value != null) {
        gaTrackEvent("form filter", "filtering_search_results", "accommodationName");
    }
}

/**
 * Funcion que realiza el tracking de ga del filtro en la pagina de resultados vuelos
 */
function trackingFilters() {
    var i;
    var includeTrains = document.getElementById('includeTrain_fake'); //checkbox incluir trenes
    var escalesNumber = document.getElementsByName("maximumNumberOfStopover");
    var escalesDuration = document.getElementsByName("maximumStopoverPeriod");

    //checkbox incluir trenes
    if (includeTrains) {
        if (includeTrains.checked) {
            gaTrackEvent('form filter', 'filtering_search_results', 'includeTrainsCkecked');
        } else {
            gaTrackEvent('form filter', 'filtering_search_results', 'includeTrainsCkeckedNonChecked');
        }
    }

    //numero de escalas
    if (escalesNumber) {
        for (i = 0; i < escalesNumber.length; i++) {
            if (escalesNumber[i].checked) {
                gaTrackEvent('form filter', 'filtering_search_results', escalesNumber[i].id);
            }
        }
    }

    //duracion de las escalas
    if (escalesDuration) {
        for (i = 0; i < escalesDuration.length; i++) {
            if (escalesDuration[i].checked) {
                gaTrackEvent('form filter', 'filtering_search_results', escalesDuration[i].id);
            }
        }
    }

    // scrollers
    if (this.arrayFiltersimgClicked && this.arrayFiltersimgClicked.length > 0) {
        for (i = 0; i < this.arrayFiltersimgClicked.lengthso; i++) {
            gaTrackEvent('form filter', 'filtering_search_results', this.arrayFiltersimgClicked[i]);
        }
    }
}

/**
 * Funcion que realiza el tracking de ga del filtro de extrras en la pagina de resultados vuelos
 */
function trackingExtras() {
    var baggageEstimationNeeded = document.getElementById('baggageEstimationNeeded'); //checkbox
    var numBaggage = document.getElementById("numBaggage");
    var collectionTypeEstimationNeeded = document.getElementById("collectionTypeEstimationNeeded");
    var collectionMethodId = document.getElementById("collectionMethodId");
    var applyAllTaxes = document.getElementById("applyAllTaxes");

    // Tracking submit del formulario
    gaTrackEvent('form full price', 'apply_extras_search_results', 'submit');

    // checkbox maletas
    if (baggageEstimationNeeded) {
        if (baggageEstimationNeeded.checked) {
            gaTrackEvent('form full price', 'apply_extras_search_results', 'baggageEstimationNeededCkecked');

            // numero de maletas
            if (numBaggage) {
                gaTrackEvent('form full price', 'apply_extras_search_results', 'baggageEstimationNum-' + numBaggage.value);
            }
        } else {
            gaTrackEvent('form full price', 'apply_extras_search_results', 'baggageEstimationNeededNonChecked');
        }
    }

    // checkbox metodo de pago
    if (collectionTypeEstimationNeeded) {
        if (collectionTypeEstimationNeeded.checked) {
            gaTrackEvent('form full price', 'apply_extras_search_results', 'collectionTypeEstimationNeededCkecked');

            // metodo de pago
            if (collectionMethodId) {
                gaTrackEvent('form full price', 'apply_extras_search_results', 'collectionType-' + collectionMethodId.value);
            }
        } else {
            gaTrackEvent('form full price', 'apply_extras_search_results', 'collectionTypeEstimationNeededNonChecked');
        }
    }

    // checkbox gastos de gestion
    if (applyAllTaxes) {
        if (applyAllTaxes.checked) {
            gaTrackEvent('form full price', 'apply_extras_search_results', 'applyAllTaxesCkecked');
        } else {
            gaTrackEvent('form full price', 'apply_extras_search_results', 'applyAllTaxesNonChecked');
        }
    }
}

var arrayFiltersimgClicked = [];
/**
 * funcion que alimenta una array de elementos usados para tracking de ga
 * se usa pra las imagenes del scroll en pagina resultados
 * @param id del elemento a trackear
 */
function setScrollFiltersUsed(id) {
    var b_idExists = false; // boolean de control

    if (this.arrayFiltersimgClicked.length > 0) {
        //si hay elementos almacenados
        for (var i = 0; i < this.arrayFiltersimgClicked.length; i++) {
            if (this.arrayFiltersimgClicked[i] == id) {
                b_idExists = true;   //si existe en la array activamos el boolean para no anyadirlo
            }
        }
        if (!b_idExists) { //si no existe se anyade
            this.arrayFiltersimgClicked.push(id);
        }
    } else {
        //la primera vez la array esta vacia, hacemos push
        this.arrayFiltersimgClicked.push(id);
    }
}

function changeVisibilityFilters(type) {
    if (type == 'filter') {
        trackingFilters();
    } else if (type == 'extras') {
        trackingExtras();
    }
    close_layers();
    if (document.getElementById("swooshTabFareList")) {
        document.getElementById("swooshTabFareList").style.display = "block";
        document.getElementById("swooshTabFare").style.display = "block";
        document.body.style.overflow = "hidden";
    }

}


/**
 * Crea un objeto dom con un id, una clase, estilo, nombre y tabindex especificados por parametros con el contenido inner.
 * @author Fabian Couto.
 * @param typeO (String) Tipo de objeto DOM.
 * @param idO (String) Id del objeto DOM.
 * @param classO (String) Clase del objeto DOM.
 * @param styleO (String) Estilo CSS del objeto DOM.
 * @param nameO (String) Nombre del objeto DOM.
 * @param tabindexO (String) Tabindex del objeto DOM.
 * @param innerO (String) Contenido HTML.
 * @return (String).
 */
function createDOM(typeO, idO, classO, styleO, nameO, tabindexO, innerO) {
    try {
        var txtO = '<' + typeO;
        if (idO != null && idO != '') {
            txtO += ' id="' + idO + '"';
        }
        if (classO != null && classO != '') {
            txtO += ' class="' + classO + '"';
        }
        if (styleO != null && styleO != '') {
            txtO += ' style="' + styleO + '"';
        }
        if (nameO != null && nameO != '') {
            txtO += ' name="' + nameO + '"';
        }
        if (tabindexO != null && tabindexO != '') {
            txtO += ' tabindex="' + tabindexO + '"';
        }
        txtO += '>';
        if (innerO != null && innerO != '') {
            txtO += innerO;
        }
        txtO += '</' + typeO + '>';
        return txtO;
    } catch (e) {
        //throwError(e, 'createDOM', arguments);
    }
}

/**
 * Crea un objeto dom select con los valores introducidos por parámetro.
 * @author Fabian Couto.
 * @param idO (String) Id del elemento select.
 * @param classO (String) Clase del elemento select.
 * @param nameO (String) Nombre del elemento select.
 * @param tabindexO (String) Tabindex del elemento select.
 * @param onblurO (String) Onblur del elemento select.
 * @param innerO (String) Contenido HTML interno.
 * @returns {String}
 */
function createDOM_select(idO, classO, nameO, tabindexO, onblurO, innerO) {
    try {
        var txtO = '<select';
        if (idO != null && idO != '') {
            txtO += ' id="' + idO + '"';
        }
        if (classO != null && classO != '') {
            txtO += ' class="' + classO + '"';
        }
        if (nameO != null && nameO != '') {
            txtO += ' name="' + nameO + '"';
        }
        if (tabindexO != null && tabindexO != '') {
            txtO += ' tabindex="' + tabindexO + '"';
        }
        if (onblurO != null && onblurO != '') {
            txtO += ' onblur="' + onblurO + '"';
        }
        txtO += '>';
        if (innerO != null && innerO != '') {
            txtO += innerO;
        }
        txtO += '</select>';
        return txtO;
    } catch (e) {
        //throwError(e, 'createDOM_select', arguments);
    }
}

/**
 * Crea un objeto input[type=hidden] con un id y nombre especificados por parametros.
 * @author Fabian Couto.
 * @param idO (String) Id del objeto DOM.
 * @param nameO (String) Nombre del objeto DOM.
 * @return (String).
 */
function createDOM_hidden(idO, nameO) {
    try {
        var txtO = '<input type="hidden"';
        if (idO != null && idO != '') {
            txtO += ' id="' + idO + '"';
        }
        if (nameO != null && nameO != '') {
            txtO += ' name="' + nameO + '"';
        }
        txtO += ' />';
        return txtO;
    } catch (e) {
        //throwError(e, 'createDOM_hidden', arguments);
    }
}

/**
 * Crea un objeto dom con un id especificado por parametro con el contenido inner.
 * @author Fabian Couto.
 * @param typeO (String) Tipo de objeto DOM.
 * @param idO (String) Id del objeto DOM.
 * @param innerO (String) Contenido HTML.
 * @return (String).
 */
function createDOM_id(typeO, idO, innerO) {
    try {
        return createDOM(typeO, idO, '', '', '', '', innerO);
    } catch (e) {
        //throwError(e, 'createDOM_id', arguments);
    }
}

/**
 * Crea un objeto dom con un id y una clase especificados por parametros con el contenido inner.
 * @author Fabian Couto.
 * @param typeO (String) Tipo de objeto DOM.
 * @param idO (String) Id del objeto DOM.
 * @param classO (String) Clase del objeto DOM.
 * @param innerO (String) Contenido HTML.
 * @return (String).
 */
function createDOM_idClass(typeO, idO, classO, innerO) {
    try {
        return createDOM(typeO, idO, classO, '', '', '', innerO);
    } catch (e) {
        //throwError(e, 'createDOM_idClass', arguments);
    }
}

/**
 * Crea un objeto dom sin atributos, solo con el contenido inner.
 * @author Fabian Couto.
 * @param typeO (String) Tipo de objeto DOM.
 * @param innerO (String) Contenido HTML.
 * @return (String).
 */
function createDOM_inner(typeO, innerO) {
    try {
        return createDOM(typeO, '', '', '', '', '', innerO);
    } catch (e) {
        //throwError(e, 'createDOM_inner', arguments);
    }
}

/**
 * Crea un objeto dom con una clase especificada en parametros y un contenido inner.
 * @author Fabian Couto.
 * @param typeO (String) Tipo de objeto DOM.
 * @param classO (String) Clase del objeto DOM.
 * @param innerO (String) Contenido HTML.
 * @return (String).
 */
function createDOM_class(typeO, classO, innerO) {
    try {
        return createDOM(typeO, '', classO, '', '', '', innerO);
    } catch (e) {
        //throwError(e, 'createDOM_class', arguments);
    }
}
/**
 * Retorna la variable de leyenda de cantidad de niños.
 * @author Fabian Couto.
 * @param childNumber (Number).
 * @returns v_childLayout (String).
 */
function getChildLayout(childNumber) {
    try {
        var v_childLayout = '';
        switch (childNumber) {
        case 0:
            v_childLayout = dynpackEngine_child_first;
            break;
        case 1:
            v_childLayout = dynpackEngine_child_second;
            break;
        default:
            v_childLayout = dynpackEngine_child_first;
            break;
        }
        return v_childLayout;
    } catch (e) {
        //throwError(e, 'getChildLayout', arguments);
    }
}

/**
 * Retorna la variable de leyenda de cantidad de habitaciones.
 * @author Fabian Couto.
 * @param roomNumber (Number).
 * @returns {String}
 */
function getRoomLayout(roomNumber) {
    try {
        var v_roomLayout = '';
        switch (roomNumber) {
        case 0:
            v_roomLayout = dynpackEngine_rooms_first;
            break;
        case 1:
            v_roomLayout = dynpackEngine_rooms_second;
            break;
        case 2:
            v_roomLayout = dynpackEngine_rooms_third;
            break;
        case 3:
            v_roomLayout = dynpackEngine_rooms_fourth;
            break;
        default:
            v_roomLayout = dynpackEngine_rooms_first;
            break;
        }
        return v_roomLayout;
    } catch (e) {
        //throwError(e, 'getRoomLayout', arguments);
    }
}

/**
 * Devuelve la estructura HTML de niños por habitación.
 * @author Fabian Couto.
 * @param r (Number) Iterador de habitaciones.
 * @param numChilds (Number) Iterador de niños.
 * @param v_tabIndex (Number) Tabindex de campos.
 * @returns (String).
 */
function appendChilds(r, numChilds, v_tabIndex) {
    try {
        var fechaActual = new Date().getFullYear();
        var fechaInicial = new Date().getFullYear() - 12;
        var htmlSource = '';
        var iteratorLength = eval(numChilds);
        for (chi = 0; chi < iteratorLength; chi++) {
            htmlSource += createDOM('div', 'Room' + r + 'Child' + chi, 'padLeft20px outerRoom', '', '', '', //display: table-cell;
                    createDOM_inner('label', createDOM_inner('span', ' - ' + (
                            getChildLayout(chi)
                            ))) +
                    createDOM('div', 'innerRoom' + r + 'Child' + chi, 'innerRoom', '', '', '',
                            createDOM_hidden('room' + r + 'Child' + chi + 'BirthDate', 'room' + r + 'Child' + chi + 'BirthDate') +
                            createDOM_select('room' + r + 'Child' + chi + 'BirthDateDay',
                                    'e-small marginTop5px marginLeft12px',
                                    'room' + r + 'Child' + chi + 'BirthDateDay',
                                    v_tabIndex++,
                                    "setHiddenDate('room" + r + "Child" + chi + "BirthDate', " +
                                    "'room" + r + "Child" + chi + "BirthDateDay', " +
                                    "'room" + r + "Child" + chi + "BirthDateMonth', " +
                                    "'room" + r + "Child" + chi + "BirthDateYear')",
                                    createEmptyOption() + createOptions(1, 31)
                                    ) +
                            createDOM_select('room' + r + 'Child' + chi + 'BirthDateMonth',
                                    'e-small marginTop5px',
                                    'room' + r + 'Child' + chi + 'BirthDateMonth',
                                    v_tabIndex++,
                                    "setHiddenDate('room" + r + "Child" + chi + "BirthDate', " +
                                    "'room" + r + "Child" + chi + "BirthDateDay', " +
                                    "'room" + r + "Child" + chi + "BirthDateMonth', " +
                                    "'room" + r + "Child" + chi + "BirthDateYear')",
                                    createEmptyOption() + createOptions(1, 12)
                                    ) +
                            createDOM_select('room' + r + 'Child' + chi + 'BirthDateYear',
                                    'e-small marginTop5px',
                                    'room' + r + 'Child' + chi + 'BirthDateYear',
                                    v_tabIndex++,
                                    "setHiddenDate('room" + r + "Child" + chi + "BirthDate', " +
                                    "'room" + r + "Child" + chi + "BirthDateDay', " +
                                    "'room" + r + "Child" + chi + "BirthDateMonth', " +
                                    "'room" + r + "Child" + chi + "BirthDateYear')",
                                    createEmptyOption() + createOptions(fechaInicial, fechaActual)
                                    )
                            )
                    );
        }
        return htmlSource;
    } catch (e) {
        //throwError(e, 'appendChilds', arguments);
    }
}

/**
 * Crea la estructura de la solicitud de fechas de nacimiento para ninos por habitacion.
 * @author Fabian Couto.
 */
function displayChildrenAgesLinear(numOfChildren, numofRooms) {
    var childrenRoomDiv = document.getElementById('childrenRoomDiv');
    var dynpackSearchRooms = document.getElementById('dynpackSearchRooms');
    var dynHtmlSearchRooms = '';
    var fechaActual = new Date().getFullYear();
    var fechaInicial = new Date().getFullYear() - 12;
    var tabIndex = 0;
    for (var i = 0; i < numofRooms; i++) {
        dynHtmlSearchRooms += '<div class="marginTop10px floatLeft">';
        dynHtmlSearchRooms += '<div class="floatLeft padLeft10px padTop5px width140">' + eval('room' + i) + '</div>';
        for (var j = 0; j < numOfChildren; j++) {
            tabIndex++;
            dynHtmlSearchRooms += '<div class="floatLeft"><label>' + eval('child' + j) + '</label>';
            dynHtmlSearchRooms += '<input type="hidden" name="room' + i + 'Child' + j + 'BirthDate" id="room' + i + 'Child' + j + 'BirthDate">';
            dynHtmlSearchRooms += '<select onblur="setHiddenDate(\'room' + i + 'Child' + j + 'BirthDate\', \'room' + i + 'Child' + j + 'BirthDateDay\', \'room' + i + 'Child' + j + 'BirthDateMonth\', \'room' + i + 'Child' + j + 'BirthDateYear\')" tabindex="' + (tabIndex++) + '" name="room' + i + 'Child' + j + 'BirthDateDay" class="e-small marginLeft10px" id="room' + i + 'Child' + j + 'BirthDateDay">';
            dynHtmlSearchRooms += createEmptyOption() + createOptions(1, 31) + '</select>';
            dynHtmlSearchRooms += '<select onblur="setHiddenDate(\'room' + i + 'Child' + j + 'BirthDate\', \'room' + i + 'Child' + j + 'BirthDateDay\', \'room' + i + 'Child' + j + 'BirthDateMonth\', \'room' + i + 'Child' + j + 'BirthDateYear\')" tabindex="' + (tabIndex++) + '" name="room' + i + 'Child' + j + 'BirthDateMonth" class="e-small marginLeft10px" id="room' + i + 'Child' + j + 'BirthDateMonth">';
            dynHtmlSearchRooms += createEmptyOption() + createOptions(1, 12) + '</select>';
            dynHtmlSearchRooms += '<select onblur="setHiddenDate(\'room' + i + 'Child' + j + 'BirthDate\', \'room' + i + 'Child' + j + 'BirthDateDay\', \'room' + i + 'Child' + j + 'BirthDateMonth\', \'room' + i + 'Child' + j + 'BirthDateYear\')" tabindex="' + (tabIndex++) + '" name="room' + i + 'Child' + j + 'BirthDateYear" class="e-small marginLeft10px marginRight15px" id="room' + i + 'Child' + j + 'BirthDateYear">';
            dynHtmlSearchRooms += createEmptyOption() + createOptions(fechaInicial, fechaActual) + '</select>';
            dynHtmlSearchRooms += '</div>';
        }
        dynHtmlSearchRooms += '<div class="clearBoth">&nbsp;</div>';
        dynHtmlSearchRooms += '</div>';
        if (i != numofRooms - 1) {
            dynHtmlSearchRooms += '<div class="clearBoth">&nbsp;</div>';
        }
    }
    dynpackSearchRooms.innerHTML = dynHtmlSearchRooms;
    childrenRoomDiv.style.display = 'block';
}
/**
 * Estructura inicial para aplicar el filtro.
 * @author Fabian Couto.
 * @param button (DOM Object) Objeto que realiza la llamada.
 * @param domSetBlock (String) Id de objeto a aplicar el filtro.
 * @param arrayIds (String[]) Array de Ids a aplicar el filtro.
 */
//var isEnable = true;
//function showResultsEngine(){
//    var engineHeight=(isEnable)?"330px":"0px";
//    if(isEnable) {
//        $("#engineHolder").css('display', 'block');
//        $("#extend-id").css('position', 'relative');
//        $("#itiResume").css('display', 'none');
//        $("#mapButton").css('display', 'none');
//    }
//    $("#engineHolder").animate({height:engineHeight}, 'slow' , function() {
//        $("#mapButton").toggleClass("showMap hideMap");
//        if(isEnable) {
//
//            isEnable = false;
//        } else{
//            if(hotels_array.length>0)$("#mapButton").css('display', 'block');
//            $("#itiResume").css('display', 'block');
//            $("#extend-id").css('position', '');
//            $("#engineHolder").css('display', 'none');
//            isEnable=true;
//        }
//  });
//}
/**
 * Establece un iframe transparente.
 * @author Fabian Couto
 * @param objParam (String/DOMObject) Parametro que puede ser el Id o el objeto.
 */
function transparentFrame(objParam) {
    try {
        var isIE = '\v' == 'v';
        switch (typeof objParam) {
        case 'object':
            if (objParam.tagName.toLowerCase() == 'iframe') {
                if (isIE) {
                    objParam.allowTransparency = 'allowtransparency';
                    objParam.scrolling = 'no';
                    objParam.contentWindow.document.body.style.backgroundColor = 'transparent';
                } else {
                    objParam.style.backgroundColor = 'transparent';
                    objParam.scrolling = 'no';
                    objParam.contentDocument.body.style.backgroundColor = 'transparent';
                }
            }
            break;
        case 'string':
            var domFrame = document.getElementById(objParam);
            if (isIE) {
                domFrame.allowTransparency = 'allowtransparency';
                domFrame.scrolling = 'no';
                domFrame.contentWindow.document.body.style.backgroundColor = 'transparent';
            } else {
                domFrame.style.backgroundColor = 'transparent';
                domFrame.scrolling = 'no';
                domFrame.contentDocument.body.style.backgroundColor = 'transparent';
            }
            break;
        }
    } catch (e) {
        //throwError(e, 'transparentFrame', arguments)
    }
}

/**
 * Muestra la imagen en una capa más grande.
 * @author Fabian Couto.
 * @param objDom (DOM Object) Objeto de Imagen.
 * @param objectId (String) Capa de visualizacion de imagen.
 */
var selectedInfoImgIndex = "0";
var picsInterval;
var showingPic = 0;
var prevPic = 0;
var picsArray = new Array();
function showImage(indexStr, imgSrc) {
    clearInterval(picsInterval);
    picsInterval = null;
    setPics();
    showingPic = parseInt(indexStr);
    clearHighlights();
    highLightThumb();
    displayPic(imgSrc);
}
function imageBack(indexStr) {
    //    clearHighlights();
    showingPic = parseInt(indexStr) + 1;
    slidehotelPics();
}

function slidehotelPics() {
    doSlidehotelPics();
    picsInterval = setInterval("doSlidehotelPics()", 4000);
}
function doSlidehotelPics() {
    setPics();
    $("#display").fadeTo(100, 0.1, function() {
        var picSrc = $("#thumb_" + showingPic).attr('src');
        clearHighlights();
        highLightThumb();
        displayPic(picSrc);
        $("#display").fadeTo("slow", 1, function() {
            showingPic ++;
        });
    });
}
function displayPic(src) {
    $("#display").attr('src', src);
}
function highLightThumb() {
    $("#thumb_" + showingPic).css('borderColor', '#039');
}
function clearHighlights() {
    for (var i = 0; i < picsArray.length; ++i) {
        $("#thumb_" + i).css('borderColor', '#FFF');
    }
}
function setPics() {
    if (showingPic >= picsArray.length) {
        showingPic = 0;
    }
    prevPic = showingPic - 1;
    if (prevPic < 0) {
        prevPic = picsArray.length - 1;
    }
}
function initPics() {
    for (var i = 0; i < picsArray.length; ++i) {
        $("#thumb_" + i).data('ind', i);
        $("#thumb_" + i).mouseover(function() {
            showImage($(this).data('ind'), picsArray[$(this).data('ind')]);
        });
        $("#thumb_" + i).mouseout(function() {
            imageBack($(this).data('ind'));
        });
    }
}
function showOption(index) {
    var tabsArray = ["tab0","tab1","tab2","tab3"];
    var divsArray = ["desc","pictures","comm","mapa"];
    for (var i = 0; i < tabsArray.length; ++i) {
        if (i == index) {
            $("#" + tabsArray[i]).removeClass("infoHotelYellowTab");
            $("#" + tabsArray[i]).addClass("infoHotelBlueTab");
            $("#" + tabsArray[i]).removeClass("defaultBlueText");
            $("#" + tabsArray[i]).addClass("whiteText");
            $("#" + divsArray[i]).css('display', 'block');
        } else {
            $("#" + tabsArray[i]).removeClass("infoHotelBlueTab");
            $("#" + tabsArray[i]).addClass("infoHotelYellowTab");
            $("#" + tabsArray[i]).removeClass("whiteText");
            $("#" + tabsArray[i]).addClass("defaultBlueText");
            $("#" + divsArray[i]).css('display', 'none');
        }
    }
    resizeFrame();
    if (index == 1) {
        initPics();
        slidehotelPics();
    } else {
        clearInterval(picsInterval);
        showingPic = 0;
        if (index == 3) {
            initMapG();
        }
    }
}


/**
 * Elimina las clases del objeto.
 * @author Fabian Couto.
 * @param objDom (DOM Object) objeto que realiza la llamada.
 */
function eraseClass(objId) {
    try {
        var isIE = '\v' == 'v';
        if (isIE) {
            document.getElementById(objId).className = '';
        }
    } catch (e) {
        //throwError(e, 'eraseClass', arguments);
    }
}

function submitChangeProductType(changeTo) {
    document.getElementById("productCategoryName").value = changeTo;
    document.getElementById("formChangeProductType").submit();
}

function sortAccommodations(sortType) {
    var b_beforeClick; //para control del efecto del doble click
    var b_afterclick;
    var gaLabel = "accommodationSortTypeName";

    b_beforeClick = document.getElementById("accommodationSortTypeName").value;
    b_afterclick = sortType;
    document.getElementById("accommodationSortTypeName").value = sortType;

    if (b_beforeClick != b_afterclick) {
        gaLabel += sortType;
        gaTrackEvent("form filter", "filtering_search_results", "")
        document.getElementById("formSortAccommodations").submit();
    }
}

var selectedRoomIndex = 0;
function actualizarPrecio(stringPrecio, index) {
    document.getElementById("roomPriceBox").innerHTML = stringPrecio;
    selectedRoomIndex = index;
}
function showFrameBoxFromLeft(aproximatePrice, page, searchId) {
    showFrameBox('/engine/dynpack/popups/fareInfo.jsp?isApproximatePrice=' + aproximatePrice + '&page=' + page + '&index=-1&searchId=' + searchId + '&isDynPackSearch=true&arrowDir=left&selectedRoomIndex=' + selectedRoomIndex, 'summaryLink', 'ifDesgloseBox', -100, 8, false);
}

function preselectDynpackProductInfoHotel(productCategoryName, formId, ind) {
    parent.$('.content-error').css('display', 'none');

    preselectDynpackProduct(productCategoryName, formId, ind, true);
    parent.close_layers();

}

function preselectDynpackProduct(productCategoryName, formId, ind, isInfo) {
    $('.content-error').css('display', 'none');
    var scope = (isInfo) ? parent.document : document;
    var cargandoDiv, contentDiv;
    var hasErrors = false;
    if (productCategoryName == "ACCOMMODATION") {
        cargandoDiv = scope.getElementById("cargandoHotel");
        contentDiv = scope.getElementById("hotelContent");
    } else {
        cargandoDiv = scope.getElementById("cargandoFlight");
        contentDiv = scope.getElementById("flightContent");
        clearErrors(ind);
        if (!validateItinerary(formId, ind)) hasErrors = true;
    }
    if (!hasErrors) {
        cargandoDiv.style.display = "block";
        contentDiv.style.display = "none";
        scope.getElementById(formId).submit();
        return true;
    } else {
        return false;
    }
}


function checkRoomSelectionForm(formId) {
    var errors = 0;
    clearErrors();
    if (!validateRadio(formId, 'indexRoomGroupSelected'))errors ++;
    if (errors < 1) {
        initSwoosh("paso4", "dynpack", formId);
        return true;
    } else {
        return false;
    }
}

var semaforoVisibilityTrip = false;
function chVisibility(objId) {
    if (!semaforoVisibilityTrip) {
        semaforoVisibilityTrip = true;
        var hasToOpen;
        if ($("#aTravelItinerary").hasClass('showTripDetail')) {
            hasToOpen = true;
            $("#aTravelItinerary").removeClass('showTripDetail');
            $("#aTravelItinerary").addClass('hideTripDetail');
            $("#aTravelItinerary2").removeClass('showTripDetail');
            $("#aTravelItinerary2").addClass('hideTripDetail');
        } else {
            hasToOpen = false;
            $("#aTravelItinerary").removeClass('hideTripDetail');
            $("#aTravelItinerary").addClass('showTripDetail');
            $("#aTravelItinerary2").removeClass('hideTripDetail');
            $("#aTravelItinerary2").addClass('showTripDetail');
        }
        changeVisibility(objId, hasToOpen);
    }
}
//function changeVisibility(div, hasToOpen){
//    $("#"+div).css("display", "block");
//// alert($("#paxTit").outerHeight(true));
//    var hotHeight = 0;
//    var paxHeight = 0;
//    var paxTitHeight = 0;
////    if($("#infoHotelAnchor-1")){
////        hotHeight = $("#infoHotelAnchor-1").outerHeight(true);
////    }
//    if($("#paxTit")){
//        paxTitHeight = $("#paxTit").outerHeight(true);
//    }
//    if($("#datos_pax")){
//        paxHeight = $("#datos_pax").outerHeight(true);
//
//    }
//    var myHeight = $("#datos_reserva").outerHeight(true)+$("#itiTit").outerHeight(true)+hotHeight+paxHeight+paxTitHeight+10+"px";
//    if(!hasToOpen){
//        $("#"+div).animate({height:"0px"}, 'slow' , function() {
//            $("#"+div).css("display", "none");
//            $("#"+div).css("height", "0px");
//        });
//    }else{
//        $("#"+div).css("display", "block");
//        $("#"+div).css("height", "0px");
//        $("#"+div).animate({height:myHeight},{ duration: 'slow'});
//    }
//}
function changeVisibility(div, hasToOpen) {
    $("#" + div).css("display", "block");
    var paxHeight, paxTitHeight, infoLeftColumn, paymentDiv = 0;
    if ($("#paxTit")) paxTitHeight = $("#paxTit").outerHeight(true);
    if ($("#datos_pax")) paxHeight = $("#datos_pax").outerHeight(true);
    if ($('#infoLeftColumn')) infoLeftColumn = $('#infoLeftColumn').outerHeight(true) + 20;
    if ($('#paymentDiv')) paymentDiv = $('#paymentDiv').outerHeight(true);
    var myHeight = $("#datos_reserva").outerHeight(true) + $("#itiTit").outerHeight(true) + paxHeight + paxTitHeight + 10 + 'px';
    if (!hasToOpen) {
        $("#" + div).animate({
            height: "0px"
        }, 'slow', function () {
            $("#" + div).css("display", "none");
            $("#" + div).css("height", "0px");
            semaforoVisibilityTrip = false;
            if (paymentDiv < infoLeftColumn) $('#blankSpace').css('height', (infoLeftColumn - paymentDiv) + 'px');
            moveBubbles();
        });
    } else {
        $("#" + div).css("display", "block");
        $("#" + div).css("height", "0px");
        $("#" + div).animate({
            height: myHeight
        }, 'slow', function () {
            semaforoVisibilityTrip = false;
            if (!$('#blankSpace')) $('#selectTravellerAndBuyer').append('<div id="blankSpace"></div>');
            $('#blankSpace').css('height', '0px');
            moveBubbles();
        });
    }
}

function fadeInFlight(elem) {
    var id = elem.id;

    $("#" + id).css("background-color", "#eeeeee");
}

function fadeOutFlight(elem) {
    var id = elem.id;

    if ($("#" + id).find('input:radio').is(':checked')) {
        $("#" + id).css("background-color", "#ffe787");
    } else {
        $("#" + id).css("background-color", "#ffffff");
    }
}

function cleanNonDigits(number) {
    try {
        return number.replace(/\D/gi, "");
        //        return "a";
    } catch (e) {
        return number;
    }
}
/**
 *  funcion para cambiar el banner horizontal de la home
 */
var edrNumBannerHome = 1;
function slideBanner() {
    try {
        edrNumBannerHome %= 3;
        edrNumBannerHome++;

        document.getElementById('bannerHome').style.background = "url(/images/creas/it/newhome/buscador/fr_ita_02_0" + edrNumBannerHome + ".jpg) no-repeat";
    } catch (e) {
    }
}

function cleanNonDigitsIdentification(number, idField) {
    try {
        if ((document.getElementById(idField).value == "NIF") || (document.getElementById(idField).value == "NIE")) {
            return number.replace(/[^0-9a-zA-Z]/gi, "");
        } else {
            return number;
        }
    } catch (e) {
        return number;
    }
}

//invoicing
function changeVisibilityInvoiceForm(isChecked) {
    var mainInvoiceDiv = document.getElementById("mainInvoiceDiv");
    if (isChecked) {
        mainInvoiceDiv.style.display = "block";
    } else {
        mainInvoiceDiv.style.display = "none";
        setInvoicingToFalse("invoice");
        setInvoicingToFalse("cia");
    }
}
function changeVisibilityInvoiceForCia(isChecked) {
    if (!document.getElementById("InvoiceForCiaDiv")) return false;
    var InvoiceForCiaDiv = document.getElementById("InvoiceForCiaDiv");
    if (isChecked) {
        InvoiceForCiaDiv.style.display = "block";
    } else {
        InvoiceForCiaDiv.style.display = "none";
        setInvoicingToFalse("cia");
    }
}
function changeVisibilityInvoiceDataForm(isChecked) {
    var invoiceDataDiv = document.getElementById("invoiceDataDiv");
    if (isChecked) {
        isInvoiceRequired = true;
        invoiceDataDiv.style.display = "block";
    } else {
        isInvoiceRequired = false;
        invoiceDataDiv.style.display = "none";
    }
}
function setInvoicingToFalse(kind) {
    var invoiceRequired = document.getElementById("invoiceRequired");
    var professionalNo = document.getElementById("professionalNo");
    if (kind == "invoice") {
        invoiceRequired.checked = false;
        changeVisibilityInvoiceForCia(false);
        changeVisibilityInvoiceDataForm(false);
    }
    if (kind == "cia") {
        professionalNo.checked = true;
        changeVisibilityInvoiceDataForm(false);
    }
}
//fill pax-buyer
var isPaxBuyerSelectFilled, paxBuyerSelectFilled, paxBuyerSelect, defaultPaxBuyerSelectContent;
function initPaxBuyer() {
    isPaxBuyerSelectFilled = false;
    paxBuyerSelectFilled = false;
    paxBuyerSelect = document.getElementById("paxBuyer");
    setInvoicingToFalse("receipt")
    if (document.all) {
        for (var i = 0; i < document.all.paxBuyer.options.length; i++) {
            defaultPaxBuyerSelectContent = document.all.paxBuyer.options[i];
        }
    } else {
        defaultPaxBuyerSelectContent = paxBuyerSelect.innerHTML;
    }
    setCountryPrefix('countryPhoneNumber1', 'phoneNumberPrefix1');
    setCountryPrefix('countryPhoneNumber2', 'phoneNumberPrefix2');
}
function fillPaxBuyerSelect(lastPaxIndex, ishotel) {
    //
    var notFilledNum = 0;
    for (var i = 0; i <= lastPaxIndex; i++) {
        if (!checkPaxs(i, ishotel)) {
            notFilledNum++;
        }
    }
    isPaxBuyerSelectFilled = (notFilledNum <= 0);
    if (!isPaxBuyerSelectFilled) {
        return false;
    }
    if (!paxBuyerSelectFilled)doFillPaxBuyerSelect(lastPaxIndex, ishotel);
}
function checkPaxs(paxInd, ishotel) {
    var name, surname;
    var paxType = document.getElementById("travellerTypeName_" + paxInd).value;
    if (paxType == "ADULT") {
        if (!ishotel) {
            name = document.getElementById("name_" + paxInd);
            surname = document.getElementById("firstLastName_" + paxInd);
        } else {
            name = document.getElementById("name_Adult_0_" + paxInd);
            surname = document.getElementById("firstLastName_Adult_0_" + paxInd);
        }
        var secondSurname;
        if (document.getElementById("secondLastName_" + paxInd)) {
            secondSurname = document.getElementById("secondLastName_" + paxInd);
        }
        return (name.value != "" && surname.value != "");
    } else {
        return true;
    }
}
function doFillPaxBuyerSelect(lastPaxIndex, ishotel) {
    var name, surname;
    var secondSurname = "";
    var userName = "";
    for (var i = 0; i < paxBuyerSelect.length; i++) {
        if (paxBuyerSelect.options[i].value == "user") {
            userName = paxBuyerSelect.options[i].text;
            break;
        }
    }
    for (var i = 0; i <= lastPaxIndex; i++) {
        var paxType = document.getElementById("travellerTypeName_" + i).value;
        if (paxType == "ADULT") {
            if (!ishotel) {
                name = document.getElementById("name_" + i).value;
                surname = document.getElementById("firstLastName_" + i).value;
            } else {
                name = document.getElementById("name_Adult_0_" + i).value;
                surname = document.getElementById("firstLastName_Adult_0_" + i).value;
            }
            if (document.getElementById("secondLastName_" + i)) {
                if (!ishotel) {
                    secondSurname = document.getElementById("secondLastName_" + i).value;
                }else{
                    secondSurname = document.getElementById("secondLastName_Adult_" + i).value;
                }
            }
            var fullName = name + " " + surname + " " + secondSurname;
            if (document.all) { //IE workaround
                if ((name.trim() + " " + surname.trim()) != userName.trim()) {
                    var oOption = document.createElement("OPTION");
                    oOption.text = fullName;
                    oOption.value = i;
                    document.all.paxBuyer.add(oOption);
                }
            } else {
                if (name.trim() + " " + surname.trim() != userName.trim()) {
                    paxBuyerSelect.innerHTML += "<option value='" + i + "'>" + fullName + "</option>";
                }
            }
        }
    }
    paxBuyerSelectFilled = true;
}
function resetPaxBuyerSelect() {
    if (document.all) {
        //        for(var i=0; i<document.all.paxBuyer.options.length; i++){
        //            document.all.paxBuyer.remove([i]);
        //        }
        document.all.paxBuyer.options.length = 0;
        var defOption = document.createElement("OPTION");
        defOption.text = defaultPaxBuyerSelectContent.text;
        defOption.value = defaultPaxBuyerSelectContent.value;
        document.all.paxBuyer.add(defOption);
    } else {
        paxBuyerSelect.innerHTML = defaultPaxBuyerSelectContent;
    }
    paxBuyerSelectFilled = false;
}
function fillBuyerFromPax(ishotel) {
    for (var i = 0; i < paxBuyerSelect.length; i++) {
        if (paxBuyerSelect.options[i].selected) {
            doFillBuyerFromPax(paxBuyerSelect.options[i].value,ishotel);
        }
    }
}
function doFillBuyerFromPax(paxInd,ishotel) {
    var paxSecondSurname = "";
    var paxName, paxSurname,paxSecondSurnameField, paxEmail, paxIdentificationTypeName,paxIdentificationTypeNameField, paxIdentification,paxIdentificationField, paxAddress, paxCityName, paxStateName, paxZipCode, paxPhoneNumber1, paxPhoneNumber2;
    if (paxInd == "-1") {
        return;
    } else if (paxInd == "user") {
        //        this method (fillBuyerFormUser) is in JSP page to take advantage of JSP variables
        paxName = fillBuyerFormUser('paxName');
        paxSurname = fillBuyerFormUser('paxSurname');
        paxEmail = fillBuyerFormUser('paxEmail');
        paxIdentificationTypeName = "";
        paxIdentification = fillBuyerFormUser('paxIdentification');
        paxAddress = fillBuyerFormUser('paxAddress');
        paxCityName = fillBuyerFormUser('paxCityName');
        paxStateName = fillBuyerFormUser('paxStateName');
        paxZipCode = fillBuyerFormUser('paxZipCode');
        paxPhoneNumber1 = fillBuyerFormUser('paxPhoneNumber1');
        paxPhoneNumber2 = fillBuyerFormUser('paxPhoneNumber2');
    } else {
        if (!ishotel) {
            paxName = document.getElementById("name_" + paxInd).value;
            paxSurname = document.getElementById("firstLastName_" + paxInd).value;
            paxSecondSurnameField = document.getElementById("secondLastName_" + paxInd);
            paxIdentificationTypeNameField = document.getElementById("identificationTypeName_" + paxInd);
            paxIdentificationField = document.getElementById("identification_" + paxInd);
        } else {
            paxName = document.getElementById("name_Adult_0_" + paxInd).value;
            paxSurname = document.getElementById("firstLastName_Adult_0_" + paxInd).value;
            paxSecondSurnameField = document.getElementById("secondLastName_Adult_0_" + paxInd);
            paxIdentificationTypeNameField = document.getElementById("identificationTypeName_Adult_0_" + paxInd);
            paxIdentificationField = document.getElementById("identification_Adult_0_" + paxInd);
        }
        if (paxSecondSurnameField) {
            paxSecondSurname = paxSecondSurnameField.value;
        }
        paxEmail = "";
        for (var i = 0; i < paxIdentificationTypeNameField.length; i++) {
            if (paxIdentificationTypeNameField.options[i].selected) {
                paxIdentificationTypeName = paxIdentificationTypeNameField.options[i].value;
            } 
        }
        if (paxIdentificationField) {
            paxIdentification = paxIdentificationField.value;
        }
        paxAddress = "";
        paxCityName = "";
        paxStateName = "";
        paxZipCode = "";
        paxPhoneNumber1 = "";
        paxPhoneNumber2 = "";
    }

    var buyerNameField = document.getElementById("name");
    var buyerSurnameField = document.getElementById("lastNames");
    var buyerEmailField = document.getElementById("mail");
    var buyerIdentificationTypeName = document.getElementById("buyerIdentificationTypeName");
    var buyerIdentification = document.getElementById("identification");
    var buyerAddress = document.getElementById("address");
    var buyerCityName = document.getElementById("cityName");
    var buyerStateName = document.getElementById("stateName");
    var buyerZipCode = document.getElementById("zipCode");
    var buyerPhoneNumber1 = document.getElementById("phoneNumber1");
    var buyerPhoneNumber2 = document.getElementById("phoneNumber2");

    buyerNameField.value = paxName;
    buyerSurnameField.value = paxSurname + paxSecondSurname;
    buyerEmailField.value = paxEmail;
    for (var i = 0; i < buyerIdentificationTypeName.length; i++) {
        if (buyerIdentificationTypeName.options[i].value == paxIdentificationTypeName) {
            buyerIdentificationTypeName.options[i].selected = "selected";
        }
    }
    buyerIdentification.value = paxIdentification;
    buyerAddress.value = paxAddress;
    buyerCityName.value = paxCityName;
    buyerStateName.value = paxStateName;
    buyerZipCode.value = paxZipCode;
    buyerPhoneNumber1.value = paxPhoneNumber1;
    buyerPhoneNumber2.value = paxPhoneNumber2;
}
//fill pax-buyer ends
var currTotalSmsPrice = 0.00;
var addedSms = 0;
var invalidSmsNums = [];
var storedSmsPrice;
function toggleSmsForm(isChecked, upselling) {
    //alert((document.getElementById("smsDiv")));
    var smsFormDiv = document.getElementById("smsFormDiv");
    var smsDiv = document.getElementById("smsDiv");
    if (isChecked) {
        smsFormDiv.style.display = "block";
    } else {
        addedSms = 0;
        smsDiv.style.display = "none";
        currTotalSmsPrice = 0.00;
        smsFormDiv.style.display = "none";
        var form;

        //
        if(upselling) {
        	form = document.getElementById("upselling");
        } else {
        	form = document.getElementById("closeBookingFromPayment");
        }        
        for (var i = 0; i < form.elements.length; i++) {
            if (form.elements[i].id.indexOf("smsPhoneNumber") != -1) {
            	form.elements[i].value = "";
            	form.elements[i].filled = false;
            }
        }
        reCalcTotalPrice();
    }
}
function setCountryPrefix(selectId, spanId) {
    var selectField = document.getElementById(selectId);
    var buyerCountryPrefixSpan = document.getElementById(spanId);
    for (var i = 0; i < selectField.options.length; ++i) {
        if (selectField.options[i].selected) {
            buyerCountryPrefixSpan.innerHTML = selectField.options[i].id;
        }
    }
}
function pricingSms(number, aValue, field, traveller) {
    if (number.trim() != "") {
    	addedSms ++;
        field.filled = true;
        /*if (checkSmsNumber(number, field, traveller)) {
            if (!field.filled) {
                addedSms ++;
                field.filled = true;
            }
        } else {
            invalidSmsNums.push(field);
            return false;
        }*/
    } else {
        field.filled = false;
        addedSms --;
    }

    var smsDiv = document.getElementById("smsDiv");
    var smsFeeSpan = document.getElementById("smsFee");
    smsDiv.style.display = (addedSms > 0) ? "block" : "none";
    var totalSmsPrice = parseFloat(aValue) * parseFloat(addedSms);
    currTotalSmsPrice = totalSmsPrice;
    smsFeeSpan.innerHTML = totalSmsPrice.toMoney(defaultCurrency);
    reCalcTotalPrice();
}

function checkInlineConditions() {
//    esta condiciones nos indica que no estamos en el formulario de hoteles
    if (document.getElementById("aTravelItinerary")) {
        var acceptedconditions = document.getElementById("acceptedconditions");
        if (!acceptedconditions.checked) {
            document.getElementById("orangeWarningText3").style.display = 'block';
            document.getElementById("orangeWarningText3").style.top = (findOffsetTop(document.getElementById("mandatoryConditions")) - 36) + 'px';
            document.getElementById("orangeWarningText3").style.left = (findOffsetLeft(document.getElementById("mandatoryConditions")) - 177) + 'px';
        }
        checkCreditCardData();
        checkInlineInsurance();
    }
}

function checkInlineCreditCardData() {
    //    esta condiciones nos indica que no estamos en el formulario de hoteles
    if (document.getElementById("aTravelItinerary")) {
        if (howManyPaymentInlineErrors() >= 2) {
            document.getElementById("orangeWarningText2").style.display = 'block';
            document.getElementById("orangeWarningText2").style.top = (findOffsetTop(document.getElementById("ccDiv")) - 36) + 'px';
            document.getElementById("orangeWarningText2").style.left = (findOffsetLeft(document.getElementById("ccDiv")) - 177) + 'px';
        }
        if (isAllPaymentDataOK()) {
            hideLabel('orangeWarningText2');
        }
    }
}
function checkCreditCardData() {
    //    esta condiciones nos indica que no estamos en el formulario de hoteles
    if (document.getElementById("aTravelItinerary")) {
        if (isAllPaymentDataOK()) {
            hideLabel('orangeWarningText2');
        } else {
            document.getElementById("orangeWarningText2").style.display = 'block';
            document.getElementById("orangeWarningText2").style.top = (findOffsetTop(document.getElementById("ccDiv")) - 36) + 'px';
            document.getElementById("orangeWarningText2").style.left = (findOffsetLeft(document.getElementById("ccDiv")) - 177) + 'px';
        }
    }
}

//CR14074 added isUpselling param
function checkInlineInsurance(isUpselling) {
	var formName;
	if(isUpselling) {
		formName = "upselling";
	} else {
		formName = "closeBookingFromPayment";
	}
    if (document.getElementById(formName)["radioButtonInsurance"]) {
        var hasInsurace;
        var insurancesChecked = document.getElementById(formName)["radioButtonInsurance"];

        for (var j = 0; j < insurancesChecked.length; ++j) {
            if (insurancesChecked[j].id == "insurancesChecked") {
                hasInsurace = (insurancesChecked[j].checked);
            }
        }
        if (hasInsurace) {
        	var fields = [];
            var numOfChecks = 0;
            var closeBookingFromPaymentInputs = document.getElementById(formName).getElementsByTagName("input");
            for (var i = 0; i < closeBookingFromPaymentInputs.length; i++) {
                var inp = closeBookingFromPaymentInputs[i].name;
                
                if (inp.indexOf("nsuranceOffers") != -1) {
                    var fields = document.forms[formName][inp];
                }
            }
            if (fields.length > 1) {
                for (var i = 0; i < fields.length; ++i) {
                    if (fields[i].checked)numOfChecks++;
                }
            } else {
                if (fields.checked)numOfChecks++;
            }
            if (numOfChecks < 1) {
                document.getElementById("orangeWarningText1").style.display = 'block';
                document.getElementById("orangeWarningText1").style.top = (findOffsetTop(document.getElementById("insurancesBox")) + 3) + 'px';
                document.getElementById("orangeWarningText1").style.left = (findOffsetLeft(document.getElementById("insurancesBox")) - 142) + 'px';
            }
        }
    }    
}
//CR14074 added isUpselling param END.

function moveBubbles() {
    try {
        //    esta condiciones nos indica que no estamos en el formulario de hoteles
        if (document.getElementById("aTravelItinerary")) {
            if (document.getElementById("orangeWarningText1").style.display == 'block') {
                document.getElementById("orangeWarningText1").style.top = (findOffsetTop(document.getElementById("insurancesBox")) + 3) + 'px';
                document.getElementById("orangeWarningText1").style.left = (findOffsetLeft(document.getElementById("insurancesBox")) - 142) + 'px';
            }
            if (document.getElementById("orangeWarningText2").style.display == 'block') {
                document.getElementById("orangeWarningText2").style.top = (findOffsetTop(document.getElementById("ccDiv")) - 36) + 'px';
                document.getElementById("orangeWarningText2").style.left = (findOffsetLeft(document.getElementById("ccDiv")) - 177) + 'px';
            }
            if (document.getElementById("orangeWarningText3").style.display == 'block') {
                document.getElementById("orangeWarningText3").style.top = (findOffsetTop(document.getElementById("mandatoryConditions")) - 36) + 'px';
                document.getElementById("orangeWarningText3").style.left = (findOffsetLeft(document.getElementById("mandatoryConditions")) - 177) + 'px';
            }
        }
    } catch (err) {
    }
}

function validateMaxAmout(fieldId) {
    var amountInput = document.getElementById(fieldId);

    if (amountInput.value.trim() != "") {
        if (isNaN(amountInput.value)) {
            changeToClass(amountInput, "borderRed");
            showAlertInDiv('maxPriceIsNaN', '');
            return false;
        } else {
            var patt = /^\d*$/;
            var result = patt.test(amountInput.value.trim());
            if (!result) {
                changeToClass(amountInput, "borderRed");
                showAlertInDiv('maxPriceIsNaN', '');
                return false;
            }
        }
    }

    return true;
}

var depCityField0, depCityField1, depCityField2, arrCityField0, arrCityField1, arrCityField2, dateInput0, dateInput1, dateInput2;
function initMultiFlightsForm() {
    depCityField0 = document.getElementById("departureLocation0");
    changeToClass(depCityField0, "");
    depCityField1 = document.getElementById("departureLocation1");
    changeToClass(depCityField1, "");
    depCityField2 = document.getElementById("departureLocation2");
    changeToClass(depCityField2, "");
    arrCityField0 = document.getElementById("arrivalLocation0");
    changeToClass(arrCityField0, "");
    arrCityField1 = document.getElementById("arrivalLocation1");
    changeToClass(arrCityField1, "");
    arrCityField2 = document.getElementById("arrivalLocation2");
    changeToClass(arrCityField2, "");
    dateInput0 = document.getElementById("departureDate0");
    changeToClass(dateInput0, "");
    dateInput1 = document.getElementById("departureDate1");
    changeToClass(dateInput1, "");
    dateInput2 = document.getElementById("departureDate2");
    changeToClass(dateInput2, "");
}

function validateMultiCity() {
    var dep0Errors = 0;
    var arr0Errors = 0;
    var dep1Errors = 0;
    var arr1Errors = 0;
    var dep2Errors = 0;
    var arr2Errors = 0;

    if (depCityField0.value == "") {
        changeToClass(depCityField0, "borderRed");
        showAlertInDiv('noAeropuerto0', 'departure');
        dep0Errors ++;
    }
    if (dep0Errors < 1) {
        if (depCityField0.value.search(/\d/) != -1) {
            changeToClass(depCityField0, "borderRed");
            showAlertInDiv('cityNoNumbers0', 'departure');
        }
    }
    if (arrCityField0.value == "") {
        changeToClass(arrCityField0, "borderRed");
        showAlertInDiv('noAeropuerto0', 'arrival');
        arr0Errors ++;
    }
    if (arr0Errors < 1) {
        if (arrCityField0.value.search(/\d/) != -1) {
            changeToClass(arrCityField0, "borderRed");
            showAlertInDiv('cityNoNumbers0', 'arrival');
            return false;
        }
    }
    if (depCityField1.value == "") {
        if (arrCityField1.value != "" || depCityField2.value != "" || arrCityField2.value != "") {
            changeToClass(depCityField1, "borderRed");
            showAlertInDiv('noAeropuerto1', 'departure');
            dep1Errors ++;
        }
        if (arrCityField2.value != "") {
            changeToClass(arrCityField1, "borderRed");
            showAlertInDiv('noAeropuerto1', 'arrival');
            dep2Errors ++;
        }

    } else {
        if (dep1Errors < 1) {
            if (depCityField1.value.search(/\d/) != -1) {
                changeToClass(depCityField1, "borderRed");
                showAlertInDiv('cityNoNumbers1', 'departure');
            }
        }

        if (arrCityField1.value == "") {
            changeToClass(arrCityField1, "borderRed");
            showAlertInDiv('noAeropuerto1', 'arrival');
            arr1Errors ++;
        }
        if (arr1Errors < 1) {
            if (arrCityField1.value.search(/\d/) != -1) {
                changeToClass(arrCityField1, "borderRed");
                showAlertInDiv('cityNoNumbers1', 'arrival');
                return false;
            }
        }
    }
    if (depCityField2.value == "") {
        if (arrCityField2.value != "") {
            changeToClass(depCityField2, "borderRed");
            showAlertInDiv('noAeropuerto2', 'departure');
            dep2Errors ++;
        }
    } else {
        if (dep2Errors < 1) {
            if (depCityField2.value.search(/\d/) != -1) {
                changeToClass(depCityField2, "borderRed");
                showAlertInDiv('cityNoNumbers2', 'departure');
            }
        }
        if (arrCityField2.value == "") {
            changeToClass(arrCityField2, "borderRed");
            showAlertInDiv('noAeropuerto2', 'arrival');
            arr2Errors ++;
        }
        if (arr2Errors < 1) {
            if (arrCityField2.value.search(/\d/) != -1) {
                changeToClass(arrCityField2, "borderRed");
                showAlertInDiv('cityNoNumbers2', 'departure');
                return false;
            }
        }
    }

    if (dep0Errors > 0 || arr0Errors > 0 || dep1Errors > 0 || arr1Errors > 0 || dep2Errors > 0 || arr2Errors > 0) {
        return false;
    } else {
        return true;
    }
}

function validateMultiDate() {
    var diafecha0 = getDiaFecha(dateInput0);
    var mesfecha0 = getMesFecha(dateInput0);
    var anyofecha0 = getAnyoFecha(dateInput0);
    var diafecha1 = getDiaFecha(dateInput1);
    var mesfecha1 = getMesFecha(dateInput1);
    var anyofecha1 = getAnyoFecha(dateInput1);
    var diafecha2 = getDiaFecha(dateInput2);
    var mesfecha2 = getMesFecha(dateInput2);
    var anyofecha2 = getAnyoFecha(dateInput2);

    var iDep0 = parseInt(anyofecha0 + mesfecha0 + diafecha0);
    var iDep1 = parseInt(anyofecha1 + mesfecha1 + diafecha1);
    var iDep2 = parseInt(anyofecha2 + mesfecha2 + diafecha2);

    var date0Errors = 0;
    var date1Errors = 0;
    var date2Errors = 0;
    if (!validateEmptyDate(dateInput0, 'departure', '0'))date0Errors ++;
    if (date0Errors == 0) {
        if (!validateFormatDate(dateInput0, 'departure', '0'))date0Errors ++;
    }
    if (date0Errors == 0) {
        if (!validateDateNoNan(dateInput0, diafecha0, mesfecha0, anyofecha0, 'departure', '0'))date0Errors ++;
    }
    if (date0Errors == 0) {
        if (!validateDateAfterToday(dateInput0, diafecha0, mesfecha0, anyofecha0, 'departure', '0'));
    }
    if (depCityField1.value != "" || arrCityField1.value != "" || depCityField2.value != "" || arrCityField2.value != "") {

        if (!validateEmptyDate(dateInput1, 'departure', '1'))date1Errors ++;
        if (date1Errors == 0) {
            if (!validateFormatDate(dateInput1, 'departure', '1'))date1Errors ++;
        }
        if (date1Errors == 0) {
            if (!validateDateNoNan(dateInput1, diafecha1, mesfecha1, anyofecha1, 'departure', '1'))date1Errors ++;
        }
        if (date1Errors == 0) {
            if (!validateDateAfterToday(dateInput1, diafecha1, mesfecha1, anyofecha1, 'departure', '1'));
        }
    } else {
        dateInput1.value = dateInput0.value;
    }
    if (depCityField2.value != "" || arrCityField2.value != "") {
        if (!validateEmptyDate(dateInput2, 'departure', '2'))date2Errors ++;
        if (date2Errors == 0) {
            if (!validateFormatDate(dateInput2, 'departure', '2'))date2Errors ++;
        }
        if (date2Errors == 0) {
            if (!validateDateNoNan(dateInput2, diafecha2, mesfecha2, anyofecha2, 'departure', '2'))date2Errors ++;
        }
        if (date2Errors == 0) {
            if (!validateDateAfterToday(dateInput2, diafecha2, mesfecha2, anyofecha2, 'departure', '2'));
        }
    } else {
        dateInput2.value = dateInput0.value;
    }

    if (date0Errors == 0 && date1Errors == 0 && date2Errors == 0) {
        if (iDep1 < iDep0) {
            changeToClass(dateInput1, "borderRed");
            showAlertInDiv('secondAfterFirst', 'departure');
            dateInput1.focus();
            date1Errors ++;
        }
        if (iDep2 < iDep0) {
            changeToClass(dateInput2, "borderRed");
            showAlertInDiv('thirdAfterFirst', 'departure');
            date1Errors ++;
        }
        if (iDep2 < iDep0) {
            changeToClass(dateInput2, "borderRed");
            showAlertInDiv('thirdAfterSecond', 'departure');
            date2Errors ++;
        }
    }
    if (date0Errors == 0 && date1Errors == 0 && date2Errors == 0) {
        return true;
    } else {
        return false;
    }
}

var idep;

function validateChooseAirport(formId, segmentsNum, isNotFlights) {

    var myForm = document.getElementById(formId);
    var origenObj = new Object();
    origenObj.checked = false;
    origenObj.selected = "";
    var destinoObj = new Object();
    destinoObj.checked = false;
    destinoObj.selected = "";
    var errorsNum = 0;


    for (var j = 0; j < segmentsNum; ++j) {
        //        alert("j: "+j)
        origenObj = checkOrigenChecked(formId, origenObj, j, isNotFlights);
        destinoObj = checkDestinoChecked(formId, destinoObj, j, isNotFlights);

        if (!origenObj.checked) {
            showAlertInDiv('chooseAirport', 'departure');
            errorsNum++;
        }
        if (!destinoObj.checked) {
            showAlertInDiv('chooseAirport', 'arrival');
            errorsNum++;
        }
        if (errorsNum == 0) {
            if (origenObj.selected != "" && (origenObj.selected == destinoObj.selected)) {
                if (isNotFlights) {
                    showAlertInDiv('sameCities', '');
                } else {
                    showAlertInDiv('sameAirports', '');
                }
                errorsNum++;
            }
        }

    }
    if (segmentsNum == 0 && isNotFlights) {
        destinoObj = checkDestinoChecked(formId, destinoObj, j, isNotFlights);
        if (!destinoObj.checked) {
            showAlertInDiv('chooseAirport', 'arrival');
            errorsNum++;
        }
    }
    return (errorsNum <= 0);
}
function checkOrigenChecked(formId, origenObj, j, isNotFlights) {
    var isOrigenChecked = false;
    var origenSelected;
    var origenAirports;
    if (isNotFlights) {
        origenAirports = document.getElementById(formId).departureCodeSelection;
    } else {
        origenAirports = document.getElementById(formId)["departureGeoNodeIdSelection" + j];
    }
    if (origenAirports) {
        for (var i = 0; i < origenAirports.length; i++) {
            if (origenAirports[i].checked) {
                isOrigenChecked = true;
                origenSelected = origenAirports[i].value;
            }
        }
    } else {
        isOrigenChecked = true;
        origenSelected = "";
    }
    origenObj.checked = isOrigenChecked;
    origenObj.selected = origenSelected;
    return origenObj;
}
function checkDestinoChecked(formId, destinoObj, j, isNotFlights) {
    var isDestinoChecked = false;
    var destinoSelected;
    var destinoAirports;
    if (isNotFlights) {
        destinoAirports = document.getElementById(formId).destinationCodeSelection;
    } else {
        destinoAirports = document.getElementById(formId)["arrivalGeoNodeIdSelection" + j];
    }

    if (destinoAirports) {
        for (var i = 0; i < destinoAirports.length; i++) {
            if (destinoAirports[i].checked) {
                isDestinoChecked = true;
                destinoSelected = destinoAirports[i].value;
            }
        }
    } else {
        isDestinoChecked = true;
        destinoSelected = "";
    }
    destinoObj.checked = isDestinoChecked;
    destinoObj.selected = destinoSelected;
    return destinoObj;
}


//function clearContentErrorGroup() {
//    var el = getElementsByClassName('content-error');
//    for (cont = 0; cont < el.length; cont++) {
//        el[cont].style.display = "none";
//    }
//    return;
//}

function validateItinerary(formId, ind) {
    var outBoundChecked = false;
    var inBoundChecked = false;
    var thirdBoundChecked = false;
    var outBoundRadios = document.forms[formId]['segmentPosition0'];
    var inBoundRadios;
    var thirdBoundRadios;
    var errorTextVar;
    var isMulti = false;

    var elemRadioOut, elemRadioIn, elemRadioThird;

    if (outBoundRadios.length) {
        for (var i = 0; i < outBoundRadios.length; ++i) {
            if (outBoundRadios[i].checked) {
                elemRadioOut = outBoundRadios[i];
                outBoundChecked = true;
            }
        }
    } else {
        elemRadioOut = outBoundRadios;
        outBoundRadios.checked = true;
        outBoundChecked = true;
    }
    if (document.forms[formId]['segmentPosition1']) {
        inBoundRadios = document.forms[formId]['segmentPosition1'];
        if (inBoundRadios.length) {
            for (var i = 0; i < inBoundRadios.length; ++i) {
                if (inBoundRadios[i].checked) {
                    elemRadioIn = inBoundRadios[i];
                    inBoundChecked = true;
                }
            }
        } else {
            elemRadioIn = inBoundRadios;
            inBoundRadios.checked = true;
            inBoundChecked = true;
        }
    } else {
        inBoundChecked = true;
    }
    if (document.forms[formId]['segmentPosition2']) {
        isMulti = true;
        thirdBoundRadios = document.forms[formId]['segmentPosition2'];
        if (thirdBoundRadios.length) {
            for (var i = 0; i < thirdBoundRadios.length; ++i) {
                if (thirdBoundRadios[i].checked) {
                    elemRadioThird = thirdBoundRadios[i];
                    thirdBoundChecked = true;
                }
            }
        } else {
            thirdBoundRadios.checked = true;
            elemRadioThird = thirdBoundRadios;
            thirdBoundChecked = true;
        }
    } else {
        thirdBoundChecked = true;
    }
    if (outBoundChecked && inBoundChecked && thirdBoundChecked) {
        return true;
    } else {
        var setTr = $('.auxFl');
        for (var i = 0; i < setTr.length; i++) {
            ($(setTr[i])).find('input:radio').get()[0].checked = false;
        }
        if (elemRadioOut) elemRadioOut.checked = true;
        if (elemRadioIn) elemRadioIn.checked = true;
        if (elemRadioThird) elemRadioThird.checked = true;


        if (!outBoundChecked) {
            if (isMulti) {
                errorTextVar = "selectThreeResultsOptions";
            } else {
                errorTextVar = "chooseOut";
            }
        } else if (!inBoundChecked) {
            if (isMulti) {
                errorTextVar = "selectThreeResultsOptions";
            } else {
                errorTextVar = "selectTwoResultsOptions";
            }
        } else if (!thirdBoundChecked) {
            errorTextVar = "selectThreeResultsOptions";
        }
        showAlertInDiv(errorTextVar, ind + 'tabFare');
        return false;
    }
}
function isFieldFilled(field, paxInd, guestInd) {
    var fieldId, fieldValue;
    if (field.id) {
        fieldValue = field.value;
        fieldId = field.id;
    } else {
        if (paxInd != '') {
            fieldId = field + "_" + paxInd;
            fieldValue = document.getElementById(fieldId).value;
        } else {
            fieldId = field + "_" + guestInd.guestType + "_" + guestInd.guestTypeNum + "_" + guestInd.roomNum;
            fieldValue = document.getElementById(fieldId).value;
        }
    }
    if (fieldValue.trim().length < 1) {
        if (paxInd == null) {
            changeToClass(document.getElementById(fieldId), "borderRed");
            showAlertInDiv('no' + fieldId, '');
        } else {
            changeToClass(document.getElementById(fieldId), "borderRed");
            showPaxAlertInDiv('no' + field, paxInd);
        }
        return false;
    } else {
        if (paxInd == null) {
            changeToClass(field, "");
        } else {
            changeToClass(document.getElementById(fieldId), "");
        }
        return true;
    }
}
function validateJustLetters(field, paxInd, guestInd) {
    var fieldId, fieldValue;
    var hasError = false;
    if (field.id) {
        fieldValue = field.value;
        fieldId = field.id;
    } else {
        if (paxInd != '') {
            fieldId = field + "_" + paxInd;
            fieldValue = document.getElementById(fieldId).value;
        } else {
            fieldId = field + "_" + guestInd.guestType + "_" + guestInd.guestTypeNum + "_" + guestInd.roomNum;
            fieldValue = document.getElementById(fieldId).value;
        }
    }
    //var notAllowed = '1234567890@#$%&¬/=?¿*';
    var allowed = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅàáâãäåÆæÈÉÊËèéêëÌÍÎÏIİìíîïıiŒœÒÓÔÕÖØøòóôõöøÙÚÛÜùúûüŸÝýÿÇçÑñÐþÞµŠšSsŞşGĞgğƒ.- ';
    for (var i = 0; i < fieldValue.length; i++) {
        if (allowed.indexOf(fieldValue.charAt(i)) == -1) {
            hasError = true;
        }
    }
    if (hasError) {
        if (paxInd == null) {
            changeToClass(document.getElementById(fieldId), "borderRed");
            showAlertInDiv('noNumbersIn' + fieldId, '');
        } else {
            changeToClass(document.getElementById(fieldId), "borderRed");
            showPaxAlertInDiv('noNumbersIn' + field, paxInd);
        }
        return false;
    } else {
        if (paxInd == null) {
            changeToClass(field, "");
        } else {
            changeToClass(document.getElementById(fieldId), "");
        }
        return true;
    }
}
function fieldContainsNumbers(field, paxInd) {
    var fieldId, fieldValue;
    if (field.id) {
        fieldValue = field.value;
        fieldId = field.id;
    } else {
        fieldId = field + "_" + paxInd;
        fieldValue = document.getElementById(fieldId).value;
    }
    if (fieldValue.search(/\d/) != -1) {
        changeToClass(document.getElementById(fieldId), "borderRed");
        if (field.id) {
            showPaxAlertInDiv('noNumbersIn' + fieldId);
        } else {
            showPaxAlertInDiv('noNumbersIn' + field, paxInd);
        }
        return true;
    }
    changeToClass(document.getElementById(fieldId), "");
    return false;
}
function isMonthBeforeToday(month, field, paxInd) {
    var today = new Date();
    var thisMonth = today.getMonth() + 1;
    var fieldId = field + "_" + paxInd;
    if (month > thisMonth) {
        var formattedLimitDate = today.getDate() + "/" + thisMonth + "/" + today.getFullYear();
        changeToClass(document.getElementById(fieldId), "borderRed");
        showPaxAlertInDiv('badDateOfBirthPrevious', paxInd, formattedLimitDate);
        return false;
    } else {
        changeToClass(document.getElementById(fieldId), "");
        return true;
    }
}
var isInputYearthisYear = false;
function isYearBeforeToday(year, field, paxInd) {
    var today = new Date();
    var thisMonth = today.getMonth() + 1;
    var thisYear = today.getFullYear();
    var fieldId = field + "_" + paxInd;
    isInputYearthisYear = (year == thisYear);
    if (year > thisYear) {
        var formattedLimitDate = today.getDate() + "/" + thisMonth + "/" + thisYear ;
        changeToClass(document.getElementById(fieldId), "borderRed");
        showPaxAlertInDiv('badDateOfBirthPrevious', paxInd, formattedLimitDate);
        return false;
    } else {
        changeToClass(document.getElementById(fieldId), "");
        return true;
    }
}
function isYearAfterToday(year, field, paxInd) {
    var today = new Date();
    var thisYear = today.getFullYear();
    var fieldId = field + "_" + paxInd;
    if (year < thisYear) {
        changeToClass(document.getElementById(fieldId), "borderRed");
        showPaxAlertInDiv('no' + field, paxInd);
        return false;
    } else {
        changeToClass(document.getElementById(fieldId), "");
        return true;
    }
}
function isFirstDateAfterSecondDate(firstDate, secondDate) {
    var oneDay = 24 * 60 * 60 * 1000;	// hours*minutes*seconds*milliseconds
    var diffDays = (firstDate.getTime() - secondDate.getTime()) / (oneDay);
    if (diffDays > 0) {
        return true;
    } else {
        return false;
    }
}
function isPaxTypeAge(paxType, returnDate, birthDay, birthMonth, birthYear, field, paxInd) {
    //alert("paxType: "+paxType);
    var fieldId = field + "_" + paxInd;
    var limitYear,limitDate,limitYearTop,limitDateTop;
    //    birthDay = (parseInt(birthDay) < 10) ? "0" + birthDay : birthDay;
    birthMonth = (parseInt(birthMonth) < 10) ? "0" + birthMonth : birthMonth;
    var paxDOB = parseInt(birthYear + birthMonth + birthDay);
    if (paxType == "CHILD") {
        limitYear = parseInt(returnDate.substr(0, 4)) - 12;
        limitDate = parseInt(limitYear + returnDate.substr(4, 2) + returnDate.substr(6, 2));
        limitYearTop = limitYear + 10;
        limitDateTop = parseInt(limitYearTop + returnDate.substr(4, 2) + returnDate.substr(6, 2));

    } else if (paxType == "INFANT") {
        limitYear = parseInt(returnDate.substr(0, 4)) - 2;
        limitDate = parseInt(limitYear + returnDate.substr(4, 2) + returnDate.substr(6, 2));
        limitYearTop = limitYear + 2;
        limitDateTop = parseInt(limitYearTop + returnDate.substr(4, 2) + returnDate.substr(6, 2));
    } else if (paxType == "ADULT") {
        return true;
    }
    limitDate += "";
    var formattedLimitDate = limitDate.substr(6, 2) + "/" + limitDate.substr(4, 2) + "/" + limitYear;
    if (paxDOB > limitDate) {
        if (paxType == "CHILD" || paxType == "INFANT") {
            limitDateTop += "";
            if (paxDOB > limitDateTop) {
                var formattedLimitDateTop = limitDateTop.substr(6, 2) + "/" + limitDateTop.substr(4, 2) + "/" + limitYearTop;
                changeToClass(document.getElementById(fieldId), "borderRed");
                showPaxAlertInDiv('badDateOfBirthTwoDates', paxInd, formattedLimitDate, formattedLimitDateTop);
                return false;
            }
        }
        return true;
    } else {


        //        var formattedLimitDate = limitDate.substr(6, 2) + "/" + limitDate.substr(4, 2) + "/" + limitYear;
        changeToClass(document.getElementById(fieldId), "borderRed");
        showPaxAlertInDiv('badDateOfBirth', paxInd, formattedLimitDate);
        return false;
    }
}
function isDayWithinMonth(day, month, year, field, paxInd) {
    var fieldId, fieldDayId, fieldMonthId;
    var isAlertToShow = false;
    var isLeap = ((year % 4) == 0);
    var thirtyDays = [4,6,9,11];
    fieldId = field + "_" + paxInd;
    if (field == "yearOfBirth") {
        fieldDayId = "dayOfBirth_" + paxInd;
        fieldMonthId = "monthOfBirth_" + paxInd;
    }
    if (month == 2) {
        var numOfdays = (isLeap) ? 29 : 28;
        if (parseInt(day) > numOfdays) {
            isAlertToShow = true;
        }
    } else {
        for (var i = 0; i < thirtyDays.length; ++i) {
            if (month == thirtyDays[i]) {
                if (parseInt(day) > 30) {
                    isAlertToShow = true;
                }
                break;
            }
        }
    }

    if (isAlertToShow) {
        changeToClass(document.getElementById(fieldDayId), "borderRed");
        changeToClass(document.getElementById(fieldMonthId), "borderRed");
        changeToClass(document.getElementById(fieldId), "borderRed");
        showAlertInDiv('birthDateChilds', 'no');
        return false;
    } else {
        changeToClass(document.getElementById(fieldDayId), "");
        changeToClass(document.getElementById(fieldMonthId), "");
        changeToClass(document.getElementById(fieldId), "");
        return true;
    }
}
function isValidID(field, type, paxInd, guestInd) {
    var fieldId, fieldValue, isIDOK, alertFunction, alertVar;
    if (paxInd != null) {
        if (paxInd != '') {
            fieldId = field + "_" + paxInd;
            fieldValue = document.getElementById(fieldId).value;
        } else {
            fieldId = field + "_" + guestInd.guestType + "_" + guestInd.guestTypeNum + "_" + guestInd.roomNum;
            fieldValue = document.getElementById(fieldId).value;
        }
        alertFunction = "showPaxAlertInDiv";
    } else {
        fieldId = field.id;
        fieldValue = field.value;
        paxInd = "";
        alertFunction = "showAlertInDiv";
    }
    if (type == "NIF") {
        isIDOK = checkNIF(fieldValue);
        alertVar = "noValidNif";
    } else if (type == "NIE") {
        isIDOK = checkNIE(fieldValue);
        alertVar = "noValidNie";
    }
    if (!isIDOK) {
        changeToClass(document.getElementById(fieldId), "borderRed");
        eval(alertFunction)(alertVar, paxInd);
        return false;
    } else {
        changeToClass(document.getElementById(fieldId), "");
        return true;
    }

}
function checkNIF(idnum) {
    var re2 = new RegExp("^[0-9]{1,8}[A-Za-z]$");
    if (!re2.test(idnum)) {
        return false;
    }

    var nif;
    var nifLetter;
    if (idnum.indexOf('-') == -1) {
        nif = idnum.substring(0, idnum.length - 1);
        nifLetter = idnum.substring(idnum.length - 1, idnum.length);
    } else {
        nif = idnum.substring(0, idnum.length - 2);
        nifLetter = idnum.substring(idnum.length - 1, idnum.length);
    }

    if (getNIFChar(nif) != nifLetter.toUpperCase()) {
        return false;
    }

    return true;
}

function checkNIE(g) {
	g = g.toUpperCase();
    var h = "TRWAGMYFPDXBNJZSQVHLCKET";
    var f = g.substr(g.length - 1, 1);
    if (/^[XYZ]{1}/.test(g)) {
        var d = new Array("X", "Y", "Z");
        var b = new Array("0", "1", "2");
        c = g;
        for (var e = 0; e < d.length; e++) {
            c = c.replace(d[e].toUpperCase(), b[e]);
        }
        var c = c.substr(0, g.length - 1) % 23;
        var a = h.substring(c, c + 1);
        if (a == f) {
        	return true;
        }
        return false;
    }
    return false;
}

function str_replace(search, replace, subject) {
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length; 
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    }; 
    return sa ? s : s[0];
}

function getNIFChar(nif) {
    var resto = nif % 23;
    var letra = "";
    switch (resto) {
    case 0:  letra = "T"; break;
    case 1:  letra = "R"; break;
    case 2:  letra = "W"; break;
    case 3:  letra = "A"; break;
    case 4:  letra = "G"; break;
    case 5:  letra = "M"; break;
    case 6:  letra = "Y"; break;
    case 7:  letra = "F"; break;
    case 8:  letra = "P"; break;
    case 9:  letra = "D"; break;
    case 10: letra = "X"; break;
    case 11: letra = "B"; break;
    case 12: letra = "N"; break;
    case 13: letra = "J"; break;
    case 14: letra = "Z"; break;
    case 15: letra = "S"; break;
    case 16: letra = "Q"; break;
    case 17: letra = "V"; break;
    case 18: letra = "H"; break;
    case 19: letra = "L"; break;
    case 20: letra = "C"; break;
    case 21: letra = "K"; break;
    case 22: letra = "E"; break;
    }
    return letra;
}
function validateMobile(field) {
    //return isFieldFilled(field);
    var mobileValue = field.value;
    var rePHONE = new RegExp("^[0-9]{7,15}$");

    if (!mobileValue.match(rePHONE)) {
        showAlertInDiv('validMobile', '');
        changeToClass(field, "borderRed");
        return false;
    }
    return true;
}
function validateEmail(field) {
    var emailValue = field.value;
    var pattern = new RegExp(/^^([-_]*[\.]?\w+)*@[A-Za-z0-9]+([-]*[.]?[A-Za-z0-9]+)*(\.[A-Za-z]{2,4})+$/);

    if (!pattern.test(emailValue)) {
        showAlertInDiv('validEmail', '');
        changeToClass(field, "borderRed");
        return false;
    }
    changeToClass(field, "");
    return true;
}

function validateEqualValues(str, str2, type) {
    var msgKind = (type == "email") ? "notEqualEmails" : "notEqualPasswords";
    if (str == "") {
        return false;
    }
    if (str != str2) {
        showAlertInDiv(msgKind, '');
        return false;
    }
    return true;
}
function validatePass(field) {
    var passValue = field.value;
    if (passValue.length < 1) {
        showAlertInDiv('noPass', '');
        changeToClass(field, "borderRed");
        return false;
    }
    return true;
}
function validateInsurances(upselling) {
    var hasInsurace;
    //CR14074 New page for upselling before the confirmation page
    var formName;
    if(upselling) {
    	formName = "upselling";
    } else {
    	formName = "closeBookingFromPayment";
    }
    //CR14074 New page for upselling before the confirmation page
    var insurancesChecked;
    var fieldDivToMark = document.getElementById("insurancesCheckedDiv");
    if(!upselling) {
    	insurancesChecked = document.getElementById(formName)["radioButtonInsurance"];
    } else {
    	insurancesChecked = document.getElementById(formName)["radioButtonInsurance"];
    }
    for (var j = 0; j < insurancesChecked.length; ++j) {
        if (insurancesChecked[j].id == "insurancesChecked") {
            hasInsurace = (insurancesChecked[j].checked);
        }
    }

    if (hasInsurace) {
        var numOfChecks = 0;
        var closeBookingFromPaymentInputs = document.getElementById(formName).getElementsByTagName("input");
        var fieldsBundle = null;
        var fieldsSimple = null;
        for (var i = 0; i < closeBookingFromPaymentInputs.length; i++) {
            var inp = closeBookingFromPaymentInputs[i].name;
            //alert((closeBookingFromPaymentInputs.length));
            if (inp == "bundleInsuranceOffers") {
                fieldsBundle = document.forms[formName][inp];
            }
            if (inp == "simpleInsuranceOffers") {
                fieldsSimple = document.forms[formName][inp];
            }
        }
        if (fieldsBundle != null) {
            if (fieldsBundle.length > 1) {
                for (var i = 0; i < fieldsBundle.length; ++i) {
                    if (fieldsBundle[i].checked)numOfChecks++;
                }
            } else {
                if (fieldsBundle.checked)numOfChecks++;
            }
        }
        if (fieldsSimple != null) {
            if (fieldsSimple.length > 1) {
                for (var i = 0; i < fieldsSimple.length; ++i) {
                    if (fieldsSimple[i].checked)numOfChecks++;
                }
            } else {
                if (fieldsSimple.checked)numOfChecks++;
            }
        }
        if (numOfChecks < 1) {
            showPaxAlertInDiv('selectAnInsurance', '');
            changeToClass(fieldDivToMark, "borderRed");
            return false;
        }
    }
    changeToClass(fieldDivToMark, "");
    return true;
}
function validateConditions(field, type) {
    var conditionsValue = field.checked;
    var conditionsDiv = document.getElementById("conditionsDiv");
    if (!conditionsValue) {
        if (type == "payment") {
            showPaxAlertInDiv('noConditionsPay', '');
        } else {
            showAlertInDiv('noConditions', '');
        }
        changeToClass(conditionsDiv, "borderRed");
        return false;
    } else {
        changeToClass(conditionsDiv, "");
        return true;
    }
}
function validateNotEmptySelect(select) {
    for (var i = 0; i < select.length; ++i) {
        if (select.options[i].selected) {
            if (select.options[i].value == "") {
                showPaxAlertInDiv('noCC', '');
                changeToClass(select, "borderRed");
                return false;
            }
        }
    }
    changeToClass(select, "");
    return true;
}
function validateCardNumber(field, ccnumber, cctype, ccj) {
    var alertToReturn = "";
    var cctypeAux = cctype;
    //	if (ccnumber == ccj) {
    //		return alertToReturn;
    //	} else
    if (ccnumber.indexOf("xxxxx") == -1) {
        if (!isCardNumber(ccnumber, cctypeAux)) {
            showPaxAlertInDiv('badCCNum', '');
            changeToClass(field, "borderRed");
            return false;
        }
    }
    changeToClass(field, "");
    return true;
}
function validateExpirationDate(monthField, yearField) {
    var intMonth,intYear,intMinYear,intMaxYear,intMinMonth;

    intMonth = parseInt(monthField.value, 10);
    intYear = parseInt(yearField.value, 10);

    var nowDate = new Date();
    var minFullYear = "" + nowDate.getFullYear();
    var minMonth = "" + nowDate.getMonth();
    intMinYear = parseInt(minFullYear.substr(2, 2), 10);
    intMinMonth = parseInt(minMonth) + 1;
    intMaxYear = intMinYear + 10;
    if (isNaN(intMonth)) {
        showAlertInDiv('nocardExpirationMonth', '');
        changeToClass(monthField, "borderRed");
        return false;
    }
    if (intMonth < 1 || intMonth > 12) {
        showAlertInDiv('nocardExpirationMonth', '');
        changeToClass(monthField, "borderRed");
        return false;
    }
    if (isNaN(intYear)) {
        showAlertInDiv('nocardExpirationYear', '');
        changeToClass(yearField, "borderRed");
        return false;
    }
    if (intYear < intMinYear || intYear > intMaxYear) {
        showAlertInDiv('nocardExpirationYear', '');
        changeToClass(yearField, "borderRed");
        return false;
    }
    var fieldDateToNum = parseInt((yearField.value + monthField.value), 10);
    if (intMinMonth < 10) {
        minMonth = "0" + intMinMonth;
    }
    var nowDateToNum = parseInt((intMinYear + minMonth), 10);
    if (fieldDateToNum < nowDateToNum) {
        showPaxAlertInDiv('badCardExpirationDate', '');
        changeToClass(monthField, "borderRed");
        changeToClass(yearField, "borderRed");
        return false;
    }

    changeToClass(monthField, "");
    changeToClass(yearField, "");
    return true;
}

function validateMinimumExpirationDate(monthField, yearField, minMonth, minYear) {
    var intMonth,intYear,intMinYear,intMaxYear,intMinMonth;

    intMonth = parseInt(monthField.value, 10);
    intYear = parseInt(yearField.value, 10);


    var minFullYear = minYear.value;
    intMinYear = parseInt(minFullYear.substr(2, 2), 10);
    intMinMonth = parseInt(minMonth.value);
    intMaxYear = intMinYear + 10;
    if (isNaN(intMonth)) {
        showAlertInDiv('nocardExpirationMonth', '');
        changeToClass(monthField, "borderRed");
        return false;
    }
    if (intMonth < 1 || intMonth > 12) {
        showAlertInDiv('nocardExpirationMonth', '');
        changeToClass(monthField, "borderRed");
        return false;
    }
    if (isNaN(intYear)) {
        showAlertInDiv('nocardExpirationYear', '');
        changeToClass(yearField, "borderRed");
        return false;
    }
    if (intYear < intMinYear || intYear > intMaxYear) {
        showAlertInDiv('nocardExpirationYear', '');
        changeToClass(yearField, "borderRed");
        return false;
    }
    var fieldDateToNum = parseInt((yearField.value + monthField.value), 10);
    if (intMinMonth < 10) {
        minMonth = "0" + intMinMonth;
    }
    var nowDateToNum = parseInt((intMinYear + minMonth), 10);
    if (fieldDateToNum < nowDateToNum) {
        var limitDate = minMonth + "/" + minYear.value;
        showPaxAlertInDiv('badMinCardExpirationDate', '', limitDate);
        changeToClass(monthField, "borderRed");
        changeToClass(yearField, "borderRed");
        return false;
    }

    changeToClass(monthField, "");
    changeToClass(yearField, "");
    return true;
}


function validateSecurityCode(field, type) {
    if ((type != "MA") && (type != "MA-3D")) {
        if (!isNum(field.value)) {
            showPaxAlertInDiv('cvvJustNumber', '');
            changeToClass(field, "borderRed");
            return false;
        }
        if ((type == 'AX') || (type == 'AX-3D')) {
            if (field.value.length != 4) {
                showPaxAlertInDiv('cvvAmericanExpress', '');
                changeToClass(field, "borderRed");
                return false;
            }
        } else if (field.value.length != 3) {
            showPaxAlertInDiv('cvvVisaMastercard', '');
            changeToClass(field, "borderRed");
            return false;
        }
    }
    changeToClass(field, "");
    return true;
}
function isCardNumber(cardnumber, type) {
    // Parse type, in case has sufix like '-3D'
    var len, rules;
    var intIdx = type.indexOf("-");
    if (intIdx >= 0) {
        type = type.substring(0, intIdx);
    }

    // Check number
    if (type == "4B") {
        return true;
    } else if (type == "CA" || type == "RM" || type == "MC" || type == "MD" || type == "M6" || type == "M4" || type == "MP" || type == "EC" || type == "MI") {
        len = new Array('16');
        rules = new Array('51', '52', '53', '54', '55');
    } else if (type == "CM") {
        len = new Array('16');
        rules = new Array('51', '52', '53', '54', '55');
    } else if (type == "E1" || type == "VI" || type == "RV" || type == "VV" || type == "VB" || type == "3V" || type == "EA") {
        len = new Array('13', '16');
        rules = new Array('4');
    } else if (type == "VD" || type == "DL") {
        len = new Array('13', '16');
        rules = new Array('4');
    } else if (type == "VE") {
        len = new Array('13', '16');
        rules = new Array('4');
    } else if (type == "AX") {
        len = new Array('15');
        rules = new Array('34', '37');
    } else if (type == "DC") {
        len = new Array('14');
        rules = new Array('30', '36', '38');
    } else if (type == "MA") {
        len = new Array('16');
        rules = new Array('50', '51', '52', '53', '54', '55');
    } else {
        return false;
    }

    if (!luhnCheck(cardnumber))
        return false;

    for (var n = 0; n < len.length; n++)
        if (cardnumber.toString().length == len[n]) {
            for (var m = 0; m < rules.length; m++) {
                var headdigit = cardnumber.substring(0, rules[m].toString().length);
                if (headdigit == rules[m])
                    return true;
            }
            return false;
        }
    return false;
}
function luhnCheck(CardNumber) {
    if (! isNum(CardNumber)) {
        return false;
    }

    var no_digit = CardNumber.length;
    var oddoeven = no_digit & 1;
    var sum = 0;
    for (var count = 0; count < no_digit; count++) {
        var digit = parseInt(CardNumber.charAt(count));
        if (!((count & 1) ^ oddoeven)) {
            digit *= 2;
            if (digit > 9)
                digit -= 9;
        }
        sum += digit;
    }
    return (sum % 10 == 0);
}
function isNum(argvalue) {
    argvalue = argvalue.toString();

    if (argvalue.length == 0) return false;

    for (var n = 0; n < argvalue.length; n++)
        if (argvalue.substring(n, n + 1) < "0" || argvalue.substring(n, n + 1) > "9") return false;
    return true;
}

//
var currClass;


function firstCharUpper(stringToFormat) {
    var formattedString = stringToFormat.charAt(0).toUpperCase() + stringToFormat.substr(1, stringToFormat.length - 1);
    return formattedString;
}

function lengthHigher(minLength, field, paxInd, guestInd) {
    var fieldId, fieldValue;
    var hasError = false;
    if (field.id) {
        fieldValue = field.value;
        fieldId = field.id;
    } else {
        if (paxInd != '') {
            fieldId = field + "_" + paxInd;
            fieldValue = document.getElementById(fieldId).value;
        } else {
            fieldId = field + "_" + guestInd.guestType + "_" + guestInd.guestTypeNum + "_" + guestInd.roomNum;
            fieldValue = document.getElementById(fieldId).value;
        }
    }
    if (fieldValue.length < minLength) {
        hasError = true;
    }
    if (hasError) {
        changeToClass(document.getElementById(fieldId), "borderRed");
        if (paxInd == null) {
            showAlertInDiv('lengthHigher' + firstCharUpper(fieldId), '');
        } else {
            showPaxAlertInDiv('lengthHigher' + firstCharUpper(field), paxInd);
        }
        return false;
    } else {
        if (paxInd == null) {
            changeToClass(field, "");
        } else {
            changeToClass(document.getElementById(fieldId), "");
        }
        return true;
    }
}
function isDateReal(date) {
    if (date.length != 8) {
        return false;
    }
    var day = Number(date.substring(0, 2));
    var month = Number(date.substring(2, 4)) - 1; // January=0, December = 11
    var year = Number(date.substring(4, 8));
    var dateObject = new Date(year, month, day);
    var dateObjectDay = dateObject.getDate();
    var dateObjectMonth = dateObject.getMonth();
    return (dateObjectDay == day && dateObjectMonth == month);
}
function validateDateFields(expirationDayField, expirationMonthField, expirationYearField) {
    var fields = new Array(expirationDayField, expirationMonthField, expirationYearField);
    var fieldsLength = new Array(2, 2, 4);
    var fieldsMax = new Array(31, 12);
    var currField;
    var errors = 0;
    var validField = new Array(true, true, true);
    for (var i = 0; i <= 2; i++) {
        currField = fields [i];
        if (currField.value.length > 0) {
            if (currField.value.length < fieldsLength[i]) {
                validField = false;
                errors++;
                break;
            } else if (!isNum(currField.value)) {
                validField = false;
                errors++;
                break;
            } else {
                if (i < 2) { //field is day or month
                    if (Number(currField.value) < 1 || Number(currField.value) > fieldsMax) {
                        validField = false;
                        errors++;
                        break;
                    }
                    else {
                        validField = true;
                    }
                } else { //field is year
                    validField = true;
                }
            }
        }
    }
    if (validField) {
        var expirationDate = expirationDayField.value.toString() + expirationMonthField.value.toString() + expirationYearField.value.toString();
        validField = isDateReal(expirationDate);
    }
    if (!validField) {
        errors++;
    }
    return errors;
}

function validateIdentificationExpirationDate(paxInd) {
    var identificationExpirationDayField = document.getElementById('identificationExpirationDay_' + paxInd);
    var identificationExpirationMonthField = document.getElementById('identificationExpirationMonth_' + paxInd);
    var identificationExpirationYearField = document.getElementById('identificationExpirationYear_' + paxInd);
    var identificationExpirationDateFields = new Array(identificationExpirationDayField, identificationExpirationMonthField, identificationExpirationYearField);
    var expirationDateErrors = validateDateFields(identificationExpirationDayField, identificationExpirationMonthField, identificationExpirationYearField);
    var isValidDate = true;
    if (expirationDateErrors > 0) {
        isValidDate = false;
    }
    if (isValidDate) {
        var identificationExpirationDate = identificationExpirationDayField.value.toString() + identificationExpirationMonthField.value.toString() + identificationExpirationYearField.value.toString();
        var retDateYear = Number(document.getElementById('retDate').value.substr(0, 4));
        var retDateMonth = Number(document.getElementById('retDate').value.substr(4, 2));
        var retDateDay = Number(document.getElementById('retDate').value.substr(6, 2));
        var identificationExpirationYear = Number(identificationExpirationDate.substr(4, 4));
        var identificationExpirationMonth = Number(identificationExpirationDate.substr(2, 2));
        var identificationExpirationDay = Number(identificationExpirationDate.substr(0, 2));
        var identificationExpirationDateObject = new Date(identificationExpirationYear, identificationExpirationMonth - 1, identificationExpirationDay);
        var returnDateObject = new Date(retDateYear, retDateMonth - 1, retDateDay);
        var validExpirationDate = isFirstDateAfterSecondDate(identificationExpirationDateObject, returnDateObject);
        isValidDate = isValidDate && validExpirationDate;
        if (!isValidDate) {
            expirationDateErrors++;
        }
    }
    if (isValidDate) {
        changeToClass(identificationExpirationDateFields[0], "");
        changeToClass(identificationExpirationDateFields[1], "");
        changeToClass(identificationExpirationDateFields[2], "");
    } else {
        changeToClass(identificationExpirationDateFields[0], "borderRed");
        changeToClass(identificationExpirationDateFields[1], "borderRed");
        changeToClass(identificationExpirationDateFields[2], "borderRed");
        showPaxAlertInDiv('invalidIdentificationExpirationDate', paxInd);
    }
    return expirationDateErrors;
}

function doShowAlert(toAlert, docScope, errorTextDiv, errorDiv) {
// Test UX[15611] Passengers Page UX Improvements
// Miro si existe la variabe allowChangeClass y si su valor de NewForm para decidir si estamos en la version del test.
    if ((!(typeof allowChangeClass === "undefined")) && (allowChangeClass == "NewForm")) {
        docScope.getElementById(errorTextDiv).innerHTML += '<li>' + toAlert + '</li>';
    } else {
        docScope.getElementById(errorTextDiv).innerHTML += toAlert + "<br/>";
    }

    docScope.getElementById(errorDiv).style.display = "block";
    //    windowScope.location.href = "#errorAnchor";
}
function hideAlert() {
    document.getElementById("content-error-form").style.display = "none";
}
function showPaxAlertInDiv(error, paxInd, limitDateParam, limitDateSecParam) {
    errorDiv = 'content-error-form';
    errorTextDiv = 'content-error-form-text';
    paxNum = parseInt(paxInd) + 1;
    if (isNaN(paxNum)) {
        paxNum = paxInd;
    }
    limitDate = limitDateParam;
    limitDateSec = limitDateSecParam;

    var toAlert = getPaxAlert(error);
    doShowAlert(toAlert, document, errorTextDiv, errorDiv);
    window.location.href = "#errorAnchor";
}

function validateRadio(formId, field) {
    var radio = document.getElementsByName(field);
    var check = false;
    for (var i = 0; i < radio.length; i++) {
        if (radio[i].checked) {
            check = true;
        }
    }

    if (!check) {
        showAlertInDiv('emptyRadio', '');
        return false;
    }
    return true;
}

/* Customer care javascript */

/* Funcion para mostrar un determinado DIV del documento */
function mostrar(id, item) {
    /* divs:= vector que contiene todos los elementos DIV del documento HTML */
    var faqDivs;
    var divs = document.getElementsByTagName('div');


    /* se examina el vector de DIVs */
    for (var indice = 0; indice < divs.length; indice ++) {
        /* Se muestra el DIV cuyo nombre coincide con el que recibe la funcion */
        if (divs[indice].id.indexOf("faq") != -1) {
            if (divs[indice].id == id) {
                divs[indice].style.display = "block";
                setActive(item);
            } else {
                if (isFaq(divs[indice].id)) divs[indice].style.display = "none";
            }
        }

    }
    return true;
}

/* Identificar si el id pasado se trata de un identificador de
 una faq, cuyos IDs los hemos itemtificado faq_xxx para tal proposito */
function isFaq(id) {
    if (id.substring(0, 3) == 'faq') return true;
    else return false;
}

/* Identificar si el id pasado se trata de un item del menu
 cuyos IDs se han nombrado como itemXX para tal proposito */
function isItem(id) {
    if (id.substring(0, 4) == 'item') return true;
    else return false;
}
/* Poner el color del item del menu seleccionado (capa visible) en rojo */
function setActive(id) {
    /* items:= vector de todos los elementos con etiqueta SPAN */
    var items;
    items = document.getElementById('lista').getElementsByTagName('strong');

    /* Se recorre el vector de items */
    for (var indice = 0; indice < items.length; indice++) {
        /* Se comprueba si el elemento examinado (item del menu) se corresponde con el seleccionado por el usuario */
        if (isItem(items[indice].id)) {
            if (items[indice].id == id) /* si: se fija el color a rojo */
                items[indice].style.color = "#000066";
            else                         /* no: se fija al azul por defecto */
                items[indice].style.color = "#0066FF";
        }
    }
}

function setActiveByDefault(id) {
    document.getElementById(id).style.color = "#000066";
}

function checkSmsNumber(number, field, traveller) {
    var errors = 0;
    clearErrors();
    if (!number.length > 4)errors ++;
    if (!isNumeric(number))errors ++;

    var rePHONE = new RegExp("^[0-9]{7,15}$");
    if (!number.match(rePHONE)) errors ++;

    if (errors > 0) {
        /*showPaxAlertInDiv('validMobile', traveller);
        changeToClass(field, "borderRed");*/
        return false;
    } else {
        changeToClass(field, "");
        return true;
    }
}
var insurances = [];
function fillInsurancesArray(id) {
    insurances.push(id);
}
function unpricingInsurance(isHigher) {
    for (var i = 0; i < insurances.length; i++) {
        if (document.getElementById("insuranceId" + insurances[i])) {
            if (document.getElementById("insuranceId" + insurances[i]).checked) {
                document.getElementById("insuranceId" + insurances[i]).checked = false;
                pricingInsurance(insurances[i], isHigher, "true");
            }
        }
    }
    document.getElementById("insurancesBlock").style.display = "none";
}
function unpricingInsuranceTest(isHigher) {
    for (var i = 0; i < insurances.length; i++) {
        if (document.getElementById("insuranceId" + insurances[i])) {
            if (document.getElementById("insuranceId" + insurances[i]).checked) {
                document.getElementById("insuranceId" + insurances[i]).checked = false;
                pricingInsurance(insurances[i], isHigher, "true");
            }
        }
    }
}

function showInsurances() {
    document.getElementById("insurancesBlock").style.display = "block";
}
function isNumeric(charac) {
    return ((charac - 0) == charac && charac.length > 0) || charac == '-';
}

var priceIns = 0;
var insPriceSelectedNoSelectable = 0;
function pricingInsurance(elem, isHigher, InsHasToBeAddedToPrice) {
    var insuranceValue = parseFloat(document.getElementById("insurancePr" + elem).value);
    if(document.getElementById("insPrDetailA" + elem)){
        var insuranceDetailAValue = parseFloat(document.getElementById("insurancePrDetailA" + elem).value);
        var insuranceDetailBValue = parseFloat(document.getElementById("insurancePrDetailB" + elem).value);
    }
    var insuranceCheck = document.getElementById("insuranceId" + elem);
    var insuranceElem = document.getElementById("insPr" + elem);
    if(document.getElementById("insPrDetailA" + elem)){
        var insuranceDetailAElem = document.getElementById("insPrDetailA" + elem);
        var insuranceDetailBElem = document.getElementById("insPrDetailB" + elem);
    }
    var divInsurance = document.getElementById("divInsurance" + elem);

    if (insuranceCheck.checked) {
        if (insuranceElem) {
            insuranceElem.innerHTML = insuranceValue.toMoney(defaultCurrency);
            insuranceElem.style.display = "block";
        }
        if (insuranceDetailAElem) {
            insuranceDetailAElem.innerHTML = insuranceDetailAValue.toMoney(defaultCurrency);
            insuranceDetailAElem.style.display = "block";
        }
        if (insuranceDetailBElem) {
            insuranceDetailBElem.innerHTML = insuranceDetailBValue.toMoney(defaultCurrency);
            insuranceDetailBElem.style.display = "block";
        }
        if (divInsurance) {
            divInsurance.style.display = "block";
        }
        //        alert("insuranceId" + elem +" InsHasToBeAddedToPrice: "+InsHasToBeAddedToPrice);
        if (InsHasToBeAddedToPrice == "true") {
            priceIns = priceIns + insuranceValue;
            reCalcTotalPrice();
        }
        //block individual insurances from the bundle
        if(elem.substr(0,1) == 'B'){
            currentTagTokens = document.getElementById("insIncludedIn" + elem).value.split( "," );
            for ( var i = 0; i < currentTagTokens.length; i++ ) {
                var ins =  document.getElementById("insSimpleVisualization" + currentTagTokens[i]).value;
                document.getElementById("insuranceId" + ins).disabled = true;
                if(document.getElementById("insuranceId" + ins).checked){
                    document.getElementById("insuranceId" + ins).checked = false;
                    pricingInsurance(ins, '', 'true');
                }
            }
        }

    } else {

        if (insuranceElem) {
            insuranceElem.innerHTML = " ";
            insuranceElem.style.display = "none";
        }
        if (divInsurance) {
            divInsurance.style.display = "none";
        }

        if (InsHasToBeAddedToPrice == "true") {
            priceIns = priceIns - insuranceValue;
            reCalcTotalPrice();
        }

        //clear individual insurances from the bundle
        if(elem.substr(0,1) == 'B'){
            currentTagTokens = document.getElementById("insIncludedIn" + elem).value.split( "," );
            for ( var i = 0; i < currentTagTokens.length; i++ ) {
                var ins =  document.getElementById("insSimpleVisualization" + currentTagTokens[i]).value;
                document.getElementById("insuranceId" + ins).disabled = false;
            }
        }
    }

}

function set3DPaymentMethod(isSecure3DAvailable) {
    if (isSecure3DAvailable == "true") {
        var creditPaymentMethodeRadio = document.getElementById("creditPaymentMethod");
        var cardsSelect = document.getElementById("cardTypeCode");
        for (var i = 0; i < cardsSelect.options.length; ++i) {
            if (cardsSelect.options[i].selected) {
                if (cardsSelect.options[i].id.indexOf("-3D") != -1) {
                    //                    alert("SECURE3D");
                    creditPaymentMethodeRadio.value = "SECURE3D";
                }
                break;
            }
        }
    }
}
var priceCC = 0;
var currentEdreamsCardDiscount = 0;
function pricingCC() {
    var selectedCardFee = 0;
    var selectedEdreamsCardDiscount = 0;
    var cardsSelect = document.getElementById("cardTypeCode");
    var taxHidden = document.getElementById("taxesValue");
    var cheapestHidden = document.getElementById("cheapestCollectionMethod");
    var taxesAndFeeHidden = document.getElementById("taxesAndFees");
    var taxValue = 0;
    var taxAndFeeValue = 0;
    var collectionName = $("#paymentCollectionName");
    var isFullPrice = ($('#fullPriceEnabled').val() == 'true');
    if(taxHidden != null){
    	taxValue = parseFloat(taxHidden.value.trim());
	}
    if(taxesAndFeeHidden != null){
    	taxAndFeeValue = parseFloat(taxesAndFeeHidden.value.trim());
    }

    if(cardsSelect != null){
    	if(cheapestHidden != null && cardsSelect.value ==cheapestHidden.value && taxAndFeeValue!= null && isFullPrice){
    		selectedCardFee = 0;
    		priceCC = 0;
    		if(taxHidden != null){
    			priceCC -= taxValue;
	    	}
    		
    	}else{
	        for (var i = 0; i < cardsSelect.options.length; ++i) {
	            if (cardsSelect.options[i].selected) {
	                selectedCardFee = parseFloat(document.getElementById("cCfare" + cardsSelect.options[i].id).value.trim());
	                priceCC = selectedCardFee;
	                selectedEdreamsCardDiscount = parseFloat(document.getElementById("edreamsCardDiscount" + cardsSelect.options[i].id).value.trim());
	                break;
	            }
	        }
	        if(taxHidden != null && isFullPrice){
	        	selectedCardFee += taxValue;
	    	}
	    }
        currentEdreamsCardDiscount = selectedEdreamsCardDiscount;
    	if(collectionName != null && $('#creditPaymentMethod').is(':checked')){
            if(cardsSelect.selectedIndex != 0){
                var textCCSelected = $('#cardTypeCode option:selected').text();
                if (textCCSelected.indexOf("+")>=0) {
                    collectionName.text(textCCSelected.split("+")[0].trim());
                } else {
                    collectionName.text(textCCSelected.split("-")[0].trim());
                }
                collectionName.removeClass('displayNone');
            }else{
                collectionName.addClass('displayNone');
            }
        }
        var cCFeeSpan = document.getElementById("cCFee");
        if(cCFeeSpan != null){ cCFeeSpan.innerHTML = selectedCardFee.toMoney(defaultCurrency);}
        var edreamsCardDiscountSpan = document.getElementById("edreamsCardDiscount");
        if(edreamsCardDiscountSpan){
            edreamsCardDiscountSpan.innerHTML = selectedEdreamsCardDiscount.toMoney(defaultCurrency);
            if (selectedEdreamsCardDiscount != 0) {
                document.getElementById("edreamsCardDiscountDiv").style.display = "block";
            } else {
                document.getElementById("edreamsCardDiscountDiv").style.display = "none";
            }
        }
        reCalcTotalPrice();
    }else if (taxesAndFeeHidden != null && isFullPrice){
    	selectedCardFee = taxAndFeeValue;
    	priceCC = taxAndFeeValue - taxValue;
    	var cCFeeSpan = document.getElementById("cCFee");
        if(cCFeeSpan != null){ cCFeeSpan.innerHTML = selectedCardFee.toMoney(defaultCurrency);}
        var edreamsCardDiscountSpan = document.getElementById("edreamsCardDiscount");
        if(edreamsCardDiscountSpan){
            edreamsCardDiscountSpan.innerHTML = selectedEdreamsCardDiscount.toMoney(defaultCurrency);
            if (selectedEdreamsCardDiscount != 0) {
                document.getElementById("edreamsCardDiscountDiv").style.display = "block";
            } else {
                document.getElementById("edreamsCardDiscountDiv").style.display = "none";
            }
        }
        reCalcTotalPrice();
    }
}

var lastCCSelected = "";

function setCCFeeToZero() {
    var cardsSelect = document.getElementById("cardTypeCode");
    lastCCSelected = cardsSelect.value;
    cardsSelect.options[0].selected = true;
}
var isConfirmPurchaseDivExpanded = false;
var pricePaypal = 0;
function pricingPaypal(isSelected) {
    try {
        var payPalCost = 0;
        var creditcardDetailDiv = document.getElementById("creditcardDetailDiv");
        var paypalDetailDiv = document.getElementById("paypalDetailDiv");
        var pPFee = document.getElementById("pPFee");
        if (document.getElementById("payPalFee")) {
            payPalCost = parseFloat(document.getElementById("payPalFee").value);
        }
        pricePaypal = payPalCost;
        var paypalConfirmationDiv = document.getElementById("paypalConfirmationDiv");
        var finalPriceBoxBudgetPaypal = document.getElementById("finalPriceBoxBudgetPaypal");
//        var confirmPurchaseDiv = document.getElementById("confirmPurchaseDiv");
//        var confirmPurchaseDivHeight = eval(parseInt(document.getElementById("confirmPurchaseDiv").style.height));

        if (isSelected) {
            creditcardDetailDiv.style.display = "none";
            paypalDetailDiv.style.display = "block";
            pPFee.innerHTML = payPalCost.toMoney(defaultCurrency);
//            if(!isConfirmPurchaseDivExpanded) {
//            	confirmPurchaseDiv.style.height = (isNaNHeight(confirmPurchaseDiv) + 55) + "px";
//            }
//            isConfirmPurchaseDivExpanded = true;
            paypalConfirmationDiv.style.display = "block";
            finalPriceBoxBudgetPaypal.innerHTML = payPalCost.toMoney(defaultCurrency);
            setCCFeeToZero();
          	pricingCC();
        } else {
            creditcardDetailDiv.style.display = "block";
            paypalDetailDiv.style.display = "none";
            pricePaypal = 0;
            if (paypalConfirmationDiv) paypalConfirmationDiv.style.display = "none";
//            if (isConfirmPurchaseDivExpanded) {
//                confirmPurchaseDiv.style.height = (confirmPurchaseDivHeight - 55) + "px";
//            }
//            isConfirmPurchaseDivExpanded = false;
        }
        reCalcTotalPrice();
    } catch (e) {
        //throwError(e, 'pricingPaypal', arguments);
    }
}

function isNaNHeight(objHeight) {
    if (objHeight.style.height != null) {
        if (!isNaN(parseInt(objHeight.style.height))) {
            return parseInt(objHeight.style.height);
        } else if (!isNaN(parseInt(objHeight.scrollHeight))) {
            return parseInt(objHeight.scrollHeight);
        } else if (!isNaN(parseInt(objHeight.clientHeight))) {
            return parseInt(objHeight.clientHeight);
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

function updateBaggageFeeSpan(paxIndex) {
    if (!document.getElementById("numBags_" + paxIndex)) {
        return;
    }
    var bagsSelect = document.getElementById("numBags_" + paxIndex);
    var bagIndex = 0;
    for (var i = 0; i < bagsSelect.options.length; i++) {
        if (bagsSelect.options[i].selected) {
            bagIndex = i;
            break;
        }
    }
    var baggageFeeSpan = document.getElementById("baggageFeeSpan_" + paxIndex);
    var priceHidden = parseFloat(document.getElementById("index" + bagIndex + "_" + paxIndex).value);
    baggageFeeSpan.innerHTML = priceHidden.toMoney(defaultCurrency);
}

function priceBaggage() {
//    var finalPriceInfoLeft = document.getElementById('finalPriceInfoLeft');
//    var priceTotal = parseFloat(document.getElementById('finalPriceInfoLeftValue').value);
//    var numOfTravellers = parseFloat(document.getElementById('numOfTravellers').value.trim());
//    for (t = 0; t < numOfTravellers; t++) {
//        var selector = document.getElementById('numBags_' + t);
//        if(selector) {
//            var selectedSuitecase = selector[selector.selectedIndex].value;
//            var priceValue = parseFloat(document.getElementById('index' + selectedSuitecase + '_' + t).value);
//            priceTotal = priceTotal + priceValue;
//        }
//    }
//    finalPriceInfoLeft.innerHTML = priceTotal.toMoney(defaultCurrency);
//
//    var totalPricePerPax = document.getElementById("totalPricePerPax");
//    if (totalPricePerPax) {
//        var pricePerPax = priceTotal / numOfTravellers;
//        totalPricePerPax.innerHTML = pricePerPax.toMoney(defaultCurrency);
//    }
}

function showPaymentType(type) {
    var typesArr = ["ccDiv", "elvDiv", "payPalDiv", "bankTransferDiv"];
    var collectionName = $("#paymentCollectionName");
        
    for (var i = 0; i < typesArr.length; ++i) {
        var typeDiv = document.getElementById(typesArr[i]);
        if (type != typesArr[i]) {
            typeDiv.style.display = "none";

        } else {
            typeDiv.style.display = "block";
        }
    }
    if (type == "ccDiv") {
        var cardsSelect = document.getElementById("cardTypeCode");

        for (i = 0; i < cardsSelect.options.length; i++) {
            if (cardsSelect.options[i].value == lastCCSelected) {
                cardsSelect.options[i].selected = true;
                break;
            }
        }

        pricingCC();
    }
    var fullPriceEnabled = document.getElementById("fullPriceEnabled").value;
    if (type == "payPalDiv") {
        pricingPaypal(true);
        collectionName.text('PayPal');
        if (fullPriceEnabled == 'true') {
            collectionName.removeClass('displayNone');
        } else {
            collectionName.addClass('displayNone');
        }

    } else {
        pricingPaypal(false);
        collectionName.text('');
    }
    if (type == "bankTransferDiv") {
        var creditcardDetailDiv = document.getElementById("creditcardDetailDiv");
        collectionName.text(bankTransferText);
        if (fullPriceEnabled == 'true') {
            creditcardDetailDiv.style.display = "block";
            collectionName.removeClass('displayNone');
        } else {
            creditcardDetailDiv.style.display = "none";
            collectionName.addClass('displayNone');
        }

        setCCFeeToZero();
        pricingCC();
    }

    moveBubbles();
}
var promotionAmount = 0;
function clearPromoValidation() {
    document.getElementById("promoValidationMessage").innerHTML = '';
    document.getElementById("promoValidationMessage").style.display = "none";
}
function promotionsAjaxPassengers() {
    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                var aux = eval('(' + xmlHttp.responseText + ')');
                var amount = aux.amount;
                var maxAmount = aux.maxAmount;
                var codes = aux.codes;

                var maxReached = false;
                var maxExceeded = false;
                var areAnyBadCodes = false;
                var textInfoMessage = "";
                var previousPromoCodes = "";

                for(i=0; i<codes.length;i++){
                    var codeId = codes[i].id;
                    var codeStatus = codes[i].status;

//                    VALID: the code is valid and belongs to a not combinable campaign
//                    NOT_COMBINABLE: the code cannot belong to a combinable campaign
//                    INVALID: the isnâ€™t valid
//                    MAX_USAGES_REACHED: the code is valid but has reached the maximum usages
//                    MAX_AMOUNT_REACHED; valid code and the total amount is exactly the maximum amount of the campaign group
//                    MAX_AMOUNT_EXCEEDED: valid code but the total amount exceeds the max
                    if(codeStatus == 'VALID' || codeStatus == 'MAX_AMOUNT_REACHED'){
                        if(i != 0){
                            textInfoMessage = textInfoMessage + "<br/>";
                        }
                        textInfoMessage = textInfoMessage + promoCode +" <span class=\"bold\">" + codeId + "</span> ";
                        if(previousPromoCodes != ''){
                            previousPromoCodes = previousPromoCodes + ',';
                        }
                        previousPromoCodes = previousPromoCodes + codeId;

                        if(codeStatus == 'MAX_AMOUNT_REACHED'){
                            maxReached = true;
                        }
                    }else if(codeStatus == 'MAX_AMOUNT_EXCEEDED'){
                        maxExceeded = true;
                    }else{
                        areAnyBadCodes = true;
                    }
                }
                document.getElementById("previousPromoCodes").value = previousPromoCodes;

                if(textInfoMessage != ''){
                    textInfoMessage = textInfoMessage + "<span class=\"greenText bold\">" + promoCodeOK + " " + amount.toMoney(defaultCurrency) + "</span>";
                    if(maxReached){
                        textInfoMessage = textInfoMessage + "<br/><br/>" + promoCodeMaxReached;
                    }else{
                        textInfoMessage = textInfoMessage + "<br/><br/>" + promoCodeAnother1 + " " + maxAmount.toMoney(defaultCurrency) + promoCodeAnother2;
                    }
                }
                document.getElementById("promoValidationMessageOK").innerHTML = textInfoMessage;
                document.getElementById("promoValidationMessage").style.display = "block";

                if(maxReached){
                    document.getElementById("promoValidationBox").style.display = "none";
                }else{
                    document.getElementById("promoValidationBox").style.display = "block";
                }

                if(maxExceeded){
                    document.getElementById("promoValidationMessageLimitReached").innerHTML = promoCodeMaxExceeded;
                }else{
                    document.getElementById("promoValidationMessageLimitReached").innerHTML = "";
                }

                if(areAnyBadCodes){
                    document.getElementById("promoValidationMessage").innerHTML = promoCodeKO;
                    document.getElementById("promoValidationMessage").style.display = "block";
                }else{
                    document.getElementById("promoValidationMessage").innerHTML = "";
                    document.getElementById("promoValidationMessage").style.display = "none";
                    if(!maxExceeded){
                        document.getElementById("promotionalCode").value = "";
                    }
                }

                promotionAmount =  - amount;

                var promoSummaryBox = document.getElementById("promoSummaryBox");
                if(promoSummaryBox){
                    if(amount > 0){
                        promoSummaryBox.style.display = "block";
                        var amountPromo = - amount;
                        document.getElementById("promoSummaryBoxPrice").innerHTML = amountPromo.toMoney(defaultCurrency);
                        reCalcTotalPrice();

                        var finalTotalPrice = parseFloat(document.getElementById("finalPriceInputValue").value);
                        finalTotalPrice = finalTotalPrice + amountPromo;
                        document.getElementById("finalPriceSpanValue").innerHTML = finalTotalPrice.toMoney(defaultCurrency);
                        document.getElementById("finalPriceInfoLeft").innerHTML = finalTotalPrice.toMoney(defaultCurrency);
                    }else{
                        promoSummaryBox.style.display = "none";
                        document.getElementById("promoSummaryBoxPrice").innerHTML = '';
                    }
                }
            }
        }
    };
    var promotionalCodeValue = document.getElementById("promotionalCode").value;
    var previousPromoCodes = document.getElementById("previousPromoCodes").value;
    var promotionalCodesValue = "";

    if(previousPromoCodes != ''){
        promotionalCodesValue = previousPromoCodes;
        if(promotionalCodeValue != ''){
            promotionalCodesValue = promotionalCodesValue + ',' + promotionalCodeValue;
        }
    }else{
        promotionalCodesValue = promotionalCodeValue;
    }

    var rndNumber = Math.floor(Math.random()*1000);
    var url = '/engine/ItinerarySelection/calculatePromotionalCodeAmount?promotionalCodes=' + promotionalCodesValue + '&p=' + rndNumber;

    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);

}

function clearPromotionalCodes(){
    if(document.getElementById("promotionalCode")){
        document.getElementById("promotionalCode").value = '';
        document.getElementById("previousPromoCodes").value = '';
        promotionsAjaxPassengers();
        if(document.getElementById("finalPriceInputValue")){
            promotionAmount = 0;
            var finalTotalPrice = parseFloat(document.getElementById("finalPriceInputValue").value);
            document.getElementById("finalPriceSpanValue").innerHTML = finalTotalPrice.toMoney(defaultCurrency);
            document.getElementById("finalPriceInfoLeft").innerHTML = finalTotalPrice.toMoney(defaultCurrency);
            reCalcTotalPrice();
        }
    }
}

var serviceFee = 0;
function showPhonesInsideServicesAndReprice(toShow) {
    if (toShow == 'P') {
        document.getElementById("phonesInsideServices").style.display = 'block';
    } else {
        document.getElementById("phonesInsideServices").style.display = 'none';
    }
    serviceFee = 0;

    if (document.getElementById("postsellServiceOptionSelection_" + toShow).checked) {
        serviceFee = parseFloat(document.getElementById("postsellServiceOptionSelectionFee_" + toShow).value.trim());
        document.getElementById("serviceFeeDetailDiv").innerHTML = serviceFee.toMoney(defaultCurrency);
        document.getElementById("serviceDetailDiv").style.display = "block";
    }
    reCalcTotalPrice();
}

function selectInsurances(elemName, elemNoName) {
    var el = document.getElementById(elemName);
    el.checked = true;

    checkNoInsurances(elemNoName);

    return true;
}

function clickInsurances(elemName) {
    var el = document.getElementById(elemName);
    if (el) el.click();
}

function checkInsurances(elemName) {
    var el = document.getElementById(elemName);
    if (el) el.checked = true;
}

function uncheckInsurances(elemName) {
    var el = document.getElementById(elemName);
    if (el) el.checked = false;
}

function checkNoInsurances(elemNoInsurances) {
    var allUnselected = true;
    for (var i = 0; i < insurances.length; i++) {
        if (document.getElementById("insuranceId" + insurances[i])) {
            allUnselected = allUnselected && !document.getElementById("insuranceId" + insurances[i]).checked;
        }
    }

    if (allUnselected) {
        var noInsurances = document.getElementById(elemNoInsurances);
        if (noInsurances) {
            noInsurances.checked = true;
        }
    }
}

function reCalcTotalPrice(){
    //initial price
    var finalTotalPrice = parseFloat(document.getElementById("finalPriceInputValue").value);
    //bags
    if(document.getElementById("finalPriceBagsInputValue")){
        finalTotalPrice = finalTotalPrice + parseFloat(document.getElementById("finalPriceBagsInputValue").value);
    }
    //insurances
    finalTotalPrice = finalTotalPrice + priceIns + insPriceSelectedNoSelectable;
    //serviceFee
    finalTotalPrice = finalTotalPrice + serviceFee;
    //sms
    finalTotalPrice = finalTotalPrice + currTotalSmsPrice;
    //discounts
    finalTotalPrice = finalTotalPrice + promotionAmount;
    //edreamsCardDiscount
    finalTotalPrice = finalTotalPrice + currentEdreamsCardDiscount;
    //creditcard
    finalTotalPrice = finalTotalPrice + priceCC;
    //paypal
    finalTotalPrice = finalTotalPrice + pricePaypal;

    var finalPriceSpan = document.getElementById("finalPriceSpan");
    var finalPriceSpaninConditions = document.getElementById("finalPriceSpaninConditions");
    var finalPriceInfoLeft = document.getElementById("finalPriceInfoLeft");

    /*
    BF[16436] Fallo en actualización de Precio en Pago en Full Price (S&H to Bottom) - 
    Se nos pide que no se modifique el precio en la columna tanto para fullprice como en no fullprice.*/
    if(document.getElementById("finalPriceLeftFullPrice").value == 'true' && finalPriceInfoLeft != null){
        finalPriceInfoLeft.innerHTML = finalTotalPrice.toMoney(defaultCurrency);

        var finalPriceInfoLeftPerPassenger = document.getElementById("finalPriceInfoLeftPerPassenger");
        if (finalPriceInfoLeftPerPassenger) {
            var passengers = document.getElementById("passengers").value;
            var finalPricePerPassenger = finalTotalPrice / passengers;
            finalPriceInfoLeftPerPassenger.innerHTML = finalPricePerPassenger.toMoney(defaultCurrency) ;
        }
    }

    //CR14074
    if (finalPriceSpaninConditions) {
    	finalPriceSpan.innerHTML = finalPriceSpaninConditions.innerHTML = finalTotalPrice.toMoney(defaultCurrency);
    } else {
    	finalPriceSpan.innerHTML = finalTotalPrice.toMoney(defaultCurrency);
    }
    if (document.getElementById("finalPriceBoxBudgetPaypal")) {
        document.getElementById("finalPriceBoxBudgetPaypal").innerHTML = finalTotalPrice.toMoney(defaultCurrency);
    }
}

function initPriceWithBags(){
    var price = parseFloat(document.getElementById("finalPriceInfoLeftValue").value);
    var priceBags = 0.0;
    var numOfTravellers = parseInt(document.getElementById("numOfTravellers").value);
    for (t = 0; t < numOfTravellers; t++) {
        if(document.getElementById('numBags_' + t)){
            selectedSuitecase = document.getElementById('numBags_' + t)[document.getElementById('numBags_' + t).selectedIndex].value;
            priceHidden = parseFloat(document.getElementById("index" + selectedSuitecase + "_" + t).value);
            priceBags = priceBags + priceHidden;
        }
    }
    var totalPrice = price + priceBags;
    var totalPricePerPassengers = totalPrice / numOfTravellers;
    document.getElementById("finalPriceInfoLeft").innerHTML = totalPrice.toMoney(defaultCurrency);
    document.getElementById("finalPriceInfoLeftPerPassenger").innerHTML = totalPricePerPassengers.toMoney(defaultCurrency);
}

function inlineCreditCardType(gaFormName) {
    var isTestVersion = false;
    var cardTypeCode = $("#cardTypeCode").val();

    if (ux13139 == "B") {
        isTestVersion = true;
    }

    if (cardTypeCode == "0") {
        $("#creditCardTypeOK").hide();
        $("#creditCardTypeKO").show();
        document.getElementById("creditCardTypeKOMsg").style.visibility = 'visible';
        gaTrackEvent("inline error", gaFormName + "Payment", "creditCardtype");
    } else {
        if ((cardTypeCode == 'AX') || (cardTypeCode == 'AX-3D')) {
            $("#cardSecNum").attr("placeholder","XXXX");
        } else {
            $("#cardSecNum").attr("placeholder","XXX");
        }

        $("#creditCardTypeOK").show();
        $("#creditCardTypeKO").hide();
        document.getElementById("creditCardTypeKOMsg").style.visibility = 'hidden';

        if (isTestVersion) {
            var cardNumber = $("#cardNumber").val();
            var cardSecNum = $("#cardSecNum").val();

            if (cardNumber.trim().length != 0) {
                inlineCreditCardNumber(gaFormName);
            }

            if (cardSecNum.trim().length != 0) {
                inlineCreditCardCVV(gaFormName);
            }
        }
    }

    checkInlineCreditCardData();
}

function inlineCreditCardHolder(gaFormName) {
    var errors = 0;
    var cardOwner = $("#cardOwner").val();

    if (cardOwner.trim().length < 1) {
        errors++;
    } else {
        var allowed = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅàáâãäåÆæÈÉÊËèéêëÌÍÎÏİìíîïıŒœÒÓÔÕÖØøòóôõöøÙÚÛÜùúûüŸÝýÿÇçÑñÐþÞµŠšŞşĞğƒ.- ';
        for (var i = 0; (i < cardOwner.length && errors == 0); i++) {
            if (allowed.indexOf(cardOwner.charAt(i)) == -1) {
                errors++;
            }
        }
    }

    if (errors != 0) {
        $("#creditCardHolderOK").hide();
        $("#creditCardHolderKO").show();
        document.getElementById("creditCardHolderKOMsg").style.visibility = 'visible';
        gaTrackEvent("inline error", gaFormName + "Payment", "creditCardHolder");
    } else {
        $("#creditCardHolderOK").show();
        $("#creditCardHolderKO").hide();
        document.getElementById("creditCardHolderKOMsg").style.visibility = 'hidden';
    }

    checkInlineCreditCardData();
}

function inlineCreditCardNumber(gaFormName) {
    var errors = 0;
    var cardNumber = $("#cardNumber").val();
    var cardTypeCode = $("#cardTypeCode").val();

    if (cardNumber.indexOf("xxxxx") == -1) {
        if (!isCardNumber(cardNumber, cardTypeCode)) {
            errors++;
        }
    }

    if (errors != 0) {
        $("#creditCardNumberOK").hide();
        $("#creditCardNumberKO").show();
        document.getElementById("creditCardNumberKOMsg").style.visibility = 'visible';
        gaTrackEvent("inline error", gaFormName + "Payment", "creditCardNumber");
    } else {
        $("#creditCardNumberOK").show();
        $("#creditCardNumberKO").hide();
        document.getElementById("creditCardNumberKOMsg").style.visibility = 'hidden';
    }

    checkInlineCreditCardData();
}

function inlineCreditCardExpiration(gaFormName) {
    var errors = 0;
    var isTestVersion = false;
    var isMonthAndYearFilled = false;
    var cardExpirationMonth = $("#cardExpirationMonth").val();
    var cardExpirationYear = $("#cardExpirationYear").val();
    var isCreditCardExpiresOK = false;

    if (ux13139 == "B") {
        isTestVersion = true;
    }

    if (cardExpirationMonth.trim().length != 0 && (cardExpirationYear.trim().length != 0)) {
        isMonthAndYearFilled = true;
    }

    // Comprobamos que el campo fecha este ya validado.
    if (document.getElementById("creditCardExpiresOK")) {
        if (document.getElementById("creditCardExpiresOK").style.display == 'inline') {
            isCreditCardExpiresOK = true;
        }
    }

    // Vamos a validar si el campo anyo y mes estan llenos o no es la version de test o no venimos de un version validada
    if (isMonthAndYearFilled || !isTestVersion || isCreditCardExpiresOK) {
        if ((cardExpirationMonth.trim().length < 1) || (cardExpirationYear.trim().length < 1)) {
            errors++;
        } else {
            var intMonth,intYear,intMinYear,intMaxYear,intMinMonth;

            intMonth = parseInt(cardExpirationMonth, 10);
            intYear = parseInt(cardExpirationYear, 10);

            var nowDate = new Date();
            var minFullYear = "" + nowDate.getFullYear();
            var minMonth = "" + nowDate.getMonth();
            intMinYear = parseInt(minFullYear.substr(2, 2), 10);
            intMinMonth = parseInt(minMonth) + 1;
            intMaxYear = intMinYear + 10;
            if (isNaN(intMonth)) {
                errors++;
            }
            if (intMonth < 1 || intMonth > 12) {
                errors++;
            }
            if (isNaN(intYear)) {
                errors++;
            }
            if (intYear < intMinYear || intYear > intMaxYear) {
                errors++;
            }
            var fieldDateToNum = parseInt((cardExpirationYear + cardExpirationMonth), 10);
            if (intMinMonth < 10) {
                minMonth = "0" + intMinMonth;
            }
            var nowDateToNum = parseInt((intMinYear + minMonth), 10);
            if (fieldDateToNum < nowDateToNum) {
                errors++;
            }
        }

        if (errors != 0) {
            $("#creditCardExpiresOK").hide();
            $("#creditCardExpiresKO").show();
            document.getElementById("creditCardExpiresKOMsg").style.visibility = 'visible';
            gaTrackEvent("inline error", gaFormName + "Payment", "creditCardExpiration");
        } else {
            $("#creditCardExpiresOK").show();
            $("#creditCardExpiresKO").hide();
            document.getElementById("creditCardExpiresKOMsg").style.visibility = 'hidden';
        }
    }

    checkInlineCreditCardData();
}

function inlineCreditCardCVV(gaFormName) {
    var errors = 0;
    var cardSecNum = $("#cardSecNum").val();
    var cardTypeCode = $("#cardTypeCode").val();

    if ((cardTypeCode != "MA") && (cardTypeCode != "MA-3D")) {
        if (!isNum(cardSecNum)) {
            errors++;
        }
        if ((cardTypeCode == 'AX') || (cardTypeCode == 'AX-3D')) {
            if (cardSecNum.length != 4) {
                errors++;
            }
        } else if (cardSecNum.length != 3) {
            errors++;
        }
    }

    if (errors != 0) {
        $("#creditCardCVVOK").hide();
        $("#creditCardCVVKO").show();
        document.getElementById("creditCardCVVKOMsg").style.visibility = 'visible';
        gaTrackEvent("inline error", gaFormName + "Payment", "creditCardCVV");
    } else {
        $("#creditCardCVVOK").show();
        $("#creditCardCVVKO").hide();
        document.getElementById("creditCardCVVKOMsg").style.visibility = 'hidden';
    }

    checkInlineCreditCardData();
}

function fkSubmitServices(productType) {
    for (var i = 0; i < invalidSmsNums.length; ++i) {
        invalidSmsNums[i].value = "";
    }
    var errors = 0;
    clearErrors();

    if (document.getElementById("closeBookingFromPayment")["radioButtonInsurance"]) {
        if (!validateInsurances()) {
            errors++;
            gaTrackEvent("form error", productType + "Services", "selectAnInsurance");
        }
    }

    if (errors < 1) {
        initSwoosh('paso3', 'vuelos', 'closeBookingFromPayment');
        var t=setTimeout("goToNewPaymentStep()",1000);
    }

    gaTrackPageview("/" + productType + "/error/validation/services");
}

function goToNewPaymentStep() {
//    To Show
    var finalPriceInfoLeft = document.getElementById("finalPriceInfoLeft");
    var priceInfoTax = document.getElementById("priceInfoTax");
    var titleTestBis = document.getElementById("titleTestBis");
    var paymentDiv = document.getElementById("paymentDiv");

    if (finalPriceInfoLeft) {
        finalPriceInfoLeft.style.display='block';
    }

    if (priceInfoTax) {
        priceInfoTax.style.display='block';
    }

    if (titleTestBis) {
        titleTestBis.style.display='block';
    }

    if (paymentDiv) {
        paymentDiv.style.display='block';
    }


//    to Hide
    var roomPriceBox = document.getElementById("roomPriceBox");
    var perPaxInfo = document.getElementById("perPaxInfo");
    var priceInfoTaxBis = document.getElementById("priceInfoTaxBis");
    var titleTest = document.getElementById("titleTest");
    var servicesDiv = document.getElementById("servicesDiv");
    var servicesButton = document.getElementById("servicesButton");

    if (roomPriceBox) {
        roomPriceBox.style.display='none';
    }

    if (perPaxInfo) {
        perPaxInfo.style.display='none';
    }

    if (priceInfoTaxBis) {
        priceInfoTaxBis.style.display='none';
    }

    if (titleTest) {
        titleTest.style.display='none';
    }

    if (servicesDiv) {
        servicesDiv.style.display='none';
    }

    if (servicesButton) {
        servicesButton.style.display='none';
    }

    hideWaitPage();
}

function howManyPaymentInlineErrors() {
    var inlineError = 0;

    try {
        if (document.getElementById("creditCardTypeKOMsg").style.visibility == 'visible') {
            inlineError++;
        }

        if (document.getElementById("creditCardHolderKOMsg").style.visibility == 'visible') {
            inlineError++;
        }

        if (document.getElementById("creditCardNumberKOMsg").style.visibility == 'visible') {
            inlineError++;
        }
        if (document.getElementById("creditCardExpiresKOMsg").style.visibility == 'visible') {
            inlineError++;
        }

        if (document.getElementById("creditCardCVVKOMsg").style.visibility == 'visible') {
            inlineError++;
        }
    } catch (err) {
    }

    return inlineError;
}

function isAllPaymentDataOK() {
    var inlineOK = 0;

    try {
        if (document.getElementById("creditCardTypeOK").style.display == 'inline') {
            inlineOK++;
        }

        if (document.getElementById("creditCardHolderOK").style.display == 'inline') {
            inlineOK++;
        }

        if (document.getElementById("creditCardNumberOK").style.display == 'inline') {
            inlineOK++;
        }
        if (document.getElementById("creditCardExpiresOK").style.display == 'inline') {
            inlineOK++;
        }

        if (document.getElementById("creditCardCVVOK").style.display == 'inline') {
            inlineOK++;
        }
    } catch (err) {
    }

    if ((inlineOK == 5)) {
        return true;
    } else {
        var cardOwner = $("#cardOwner").val();
        var cardNumber = $("#cardNumber").val();
        var cardExpirationMonth = $("#cardExpirationMonth").val();
        var cardExpirationYear = $("#cardExpirationYear").val();
        var cardSecNum = $("#cardSecNum").val();

        if ((howManyPaymentInlineErrors() == 0) && (cardOwner.trim().length != 0) && (cardNumber.trim().length != 0) && (cardExpirationMonth.trim().length != 0) && (cardExpirationYear.trim().length != 0) && (cardSecNum.trim().length != 0)) {
            return true;
        }
    }

    return false;
}
function startRedirect(step, product, id, lang, isWL){
    document.getElementById("waitScreen").style.visibility = "visible";
    document.getElementById("waitScreen").style.display = "block";
    if(!isWL){
        setSwooshStep(step, product, id, lang);
    }
    document.getElementById(id).submit();
}
function checkUpselling(productType) {

	var errors = 0;
    clearErrors();

	if (findSmsPhoneErrrors()) {
		errors++;
	}

    for (var i = 0; i < invalidSmsNums.length; ++i) {
        invalidSmsNums[i].value = "";
    }

    if (document.getElementById("upselling")["radioButtonInsurance"]) {
        if (!validateInsurances("upselling")) {
            errors++;
            gaTrackEvent("form error", productType + "Upselling", "selectAnInsurance");
        }
    }

    if (errors < 1) {
        initSwoosh('paso3', 'vuelos', "upselling");
        return true;
    } else {
        gaTrackPageview("/" + productType + "/error/validation/upselling");
        return false;
    }
}

function initUpsellingHandlers() {
	$(document).ready(function(){
		//Funcion para que muestre el precio junto al texto de quiero confirmacion sms
		$('#smsPriceText').hide();
		$('#smsFormDiv').find('input').bind('change', function(e){
		    var tr = $(this).closest('tr');
		    if ($(this).val() == '') {
		        tr.css('background','#fff');
		        //ocultar texto de precio si todos los inputs estan vacios
		        var inputsEmpty = $('#smsFormDiv').find('input[value!=""]');
		        if (inputsEmpty.length == 0){
		        	$('#smsPriceText').hide();
		        }

		    } else {
		        tr.css('background','#ffe787');
		    }
		});

		$('#smsNotification').bind('click', function(e){
		    if (!$(this).is(':checked')){
		        var div = $('#smsFormDiv');
		        div.find('input').val('');
		        div.find('tr').css('background','#fff');
		        $('#smsPriceText').hide();
		        var defaultCountryText = div.find('select > option[selected=selected]').val();
		        var defaultCountryId = div.find('select > option[selected=selected]').attr('id');
		        div.find('select').val(defaultCountryText);
		        div.find('span[id*=CountryPrefix]').html(defaultCountryId );
		    } else {
		    	$('#smsPriceText').show();
		    }
		});
		//funcionalidad para la caja de services options de upselling
		$('div[id^="service_"]').has('input[type=radio]:not(:checked)').fadeTo("fast", 0.40);

		$('div[id^="service_"]').find('input[type=radio]').bind('click', function(e){
		    $('div[id^="service_"]').has('input[type=radio]:not(:checked)').fadeTo("fast", 0.40);
		});

		$('div[id^="service_"]').mouseover(
		  function(){
		    if (!$(this).find('input[type="radio"]').is(':checked')){
		        $(this).fadeTo('fast', 1);
		    }
		  });
		$('div[id^="service_"]').mouseleave(function(){
		    if (!$(this).find('input[type="radio"]').is(':checked')){
		        $(this).fadeTo("fast", 0.40);
		    }
		});
		$("#standarBubble").hide();
		$('input[name=postsellServiceOptionSelection]').bind('click', function(e){
			if($('input[id=postsellServiceOptionSelection_B]').is(':checked')){
				$("#premiumBubble").hide();
				$("#standarBubble").show();
			}else if($('input[id=postsellServiceOptionSelection_S]').is(':checked')){
				$("#standarBubble").hide();
				$("#premiumBubble").show();
			}else{
				$("#standarBubble").hide();
				$("#premiumBubble").hide();
			}
		});
	});
}

// Test UX[15611] Passengers Page UX Improvements
//Funciones para la nueva version de la paginas de pasajeros
function updateLabel(id,value) {
    var elem = document.getElementById(id);

    if (elem) {
        elem.innerHTML = value;
    }
}

function fillBuyerFromPaxTest(ishotel) {
    for (var i = 0; i < paxBuyerSelect.length; i++) {
        if (paxBuyerSelect.options[i].selected) {
            doFillBuyerFromPaxTest(paxBuyerSelect.options[i].value,ishotel);
        }
    }
}
function doFillBuyerFromPaxTest(paxInd,ishotel) {
    var paxSecondSurname = "";
    var paxName, paxSurname,paxSecondSurnameField, paxEmail, paxIdentificationTypeName,paxIdentificationTypeNameField, paxIdentification,paxIdentificationField, paxAddress, paxCityName, paxStateName, paxZipCode, paxPhoneNumber1, paxPhoneNumber2;
    if (paxInd == "-1") {
        return;
    } else if (paxInd == "user") {
        //        this method (fillBuyerFormUser) is in JSP page to take advantage of JSP variables
        paxName = fillBuyerFormUser('paxName');
        paxSurname = fillBuyerFormUser('paxSurname');
        paxEmail = fillBuyerFormUser('paxEmail');
        paxIdentificationTypeName = "";
        paxIdentification = fillBuyerFormUser('paxIdentification');
        paxAddress = fillBuyerFormUser('paxAddress');
        paxCityName = fillBuyerFormUser('paxCityName');
        paxStateName = fillBuyerFormUser('paxStateName');
        paxZipCode = fillBuyerFormUser('paxZipCode');
        paxPhoneNumber1 = fillBuyerFormUser('paxPhoneNumber1');
        paxPhoneNumber2 = fillBuyerFormUser('paxPhoneNumber2');
    } else {
        if (!ishotel) {
            paxName = document.getElementById("name_" + paxInd).value;
            paxSurname = document.getElementById("firstLastName_" + paxInd).value;
            paxSecondSurnameField = document.getElementById("secondLastName_" + paxInd);

            for (var i = 0; document.getElementById(i+"identificationTypeId_" + paxInd); i++) {
                if (document.getElementById(i+"identificationTypeId_" + paxInd).checked) {
                    paxIdentificationTypeNameField = document.getElementById(i+"identificationTypeId_" + paxInd).value;
                    break;
                }
            }

            paxIdentificationField = document.getElementById("identification_" + paxInd);
        } else {
            //Hay que revisar que pasa en hoteles cuando se mueva el test al formulario de test.
            paxName = document.getElementById("name_Adult_0_" + paxInd).value;
            paxSurname = document.getElementById("firstLastName_Adult_0_" + paxInd).value;
            paxSecondSurnameField = document.getElementById("secondLastName_Adult_0_" + paxInd);
            //paxIdentificationTypeNameField = document.getElementById("identificationTypeName_Adult_0_" + paxInd);
            paxIdentificationField = document.getElementById("identification_Adult_0_" + paxInd);
        }
        if (paxSecondSurnameField) {
            paxSecondSurname = paxSecondSurnameField.value;
        }
        paxEmail = "";

        for (var i = 0; document.getElementById("buyerIdentificationTypeName" + i); i++) {
            if (document.getElementById("buyerIdentificationTypeName" + i).value == paxIdentificationTypeNameField) {
                //document.getElementById("buyerIdentificationTypeName_" + i).checked = true;
                document.getElementById("buyerIdentificationTypeName" + i).click();
            }
        }
        if (paxIdentificationField) {
            paxIdentification = paxIdentificationField.value;
        }
        paxAddress = "";
        paxCityName = "";
        paxStateName = "";
        paxZipCode = "";
        paxPhoneNumber1 = "";
        paxPhoneNumber2 = "";
    }

    var buyerNameField = document.getElementById("name");
    var buyerSurnameField = document.getElementById("lastNames");
    var buyerEmailField = document.getElementById("mail");
//    var buyerIdentificationTypeName = document.getElementById("buyerIdentificationTypeName");
    var buyerIdentification = document.getElementById("identification");
    var buyerAddress = document.getElementById("address");
    var buyerCityName = document.getElementById("cityName");
    var buyerStateName = document.getElementById("stateName");
    var buyerZipCode = document.getElementById("zipCode");
    var buyerPhoneNumber1 = document.getElementById("phoneNumber1");
    var buyerPhoneNumber2 = document.getElementById("phoneNumber2");

    buyerNameField.value = paxName;
    buyerSurnameField.value = paxSurname + paxSecondSurname;
    buyerEmailField.value = paxEmail;
//    for (var i = 0; i < buyerIdentificationTypeName.length; i++) {
//        if (buyerIdentificationTypeName.options[i].value == paxIdentificationTypeName) {
//            buyerIdentificationTypeName.options[i].selected = "selected";
//        }
//    }
    buyerIdentification.value = paxIdentification;
    buyerAddress.value = paxAddress;
    buyerCityName.value = paxCityName;
    buyerStateName.value = paxStateName;
    buyerZipCode.value = paxZipCode;
    buyerPhoneNumber1.value = paxPhoneNumber1;
    buyerPhoneNumber2.value = paxPhoneNumber2;
}

function validateIdentificationExpirationDateTest(paxInd) {
    var identificationExpirationDayField = document.getElementById('identificationExpirationDay_' + paxInd);
    var identificationExpirationMonthField = document.getElementById('identificationExpirationMonth_' + paxInd);
    var identificationExpirationYearField = document.getElementById('identificationExpirationYear_' + paxInd);

    var identificationExpirationDateFields = new Array(identificationExpirationDayField, identificationExpirationMonthField, identificationExpirationYearField);
    var expirationDateErrors = validateDateFields(identificationExpirationDayField, identificationExpirationMonthField, identificationExpirationYearField);
    var isValidDate = true;
    if (expirationDateErrors > 0) {
        isValidDate = false;
    }
    if (isValidDate) {
        var identificationExpirationDate = identificationExpirationDayField.value.toString() + identificationExpirationMonthField.value.toString() + identificationExpirationYearField.value.toString();
        var retDateYear = Number(document.getElementById('retDate').value.substr(0, 4));
        var retDateMonth = Number(document.getElementById('retDate').value.substr(4, 2));
        var retDateDay = Number(document.getElementById('retDate').value.substr(6, 2));
        var identificationExpirationYear = Number(identificationExpirationDate.substr(4, 4));
        var identificationExpirationMonth = Number(identificationExpirationDate.substr(2, 2));
        var identificationExpirationDay = Number(identificationExpirationDate.substr(0, 2));
        var identificationExpirationDateObject = new Date(identificationExpirationYear, identificationExpirationMonth - 1, identificationExpirationDay);
        var returnDateObject = new Date(retDateYear, retDateMonth - 1, retDateDay);
        var validExpirationDate = isFirstDateAfterSecondDate(identificationExpirationDateObject, returnDateObject);
        isValidDate = isValidDate && validExpirationDate;
        if (!isValidDate) {
            expirationDateErrors++;
        }
    }
    if (isValidDate) {
        changeToClass(identificationExpirationDateFields[0], "");
        changeToClass(identificationExpirationDateFields[1], "");
        changeToClass(identificationExpirationDateFields[2], "");
    } else {
        changeToClass(identificationExpirationDateFields[0], "borderRed");
        changeToClass(identificationExpirationDateFields[1], "borderRed");
        changeToClass(identificationExpirationDateFields[2], "borderRed");
        showPaxAlertInDiv('invalidIdentificationExpirationDate', paxInd);
    }
    return expirationDateErrors;
}

function showToolFormTip(toolTipId, inputAnchorId, offsetX, offsetY, maxwidth) {
    var toolTipIdElement = document.getElementById(toolTipId);
    var inputAnchorIdElement = document.getElementById(inputAnchorId);
    var toolTipIframeShim = document.getElementById('iframe1Shim');

    if (toolTipIdElement && inputAnchorIdElement) {
        toolTipIdElement.style.display = 'block';
        toolTipIdElement.style.top = (findOffsetTop(inputAnchorIdElement) + offsetY) + 'px';
        toolTipIdElement.style.left = (findOffsetLeft(inputAnchorIdElement) + inputAnchorIdElement.clientWidth + offsetX) + 'px';

        if (toolTipIdElement.clientWidth > 290) {
            toolTipIdElement.style.width = '280px';
        }

        if (maxwidth) {
            toolTipIdElement.style.width = maxwidth + 'px';
        }

        if ( $.browser.msie ) {
          if (parseInt($.browser.version, 10) < 7) {
            toolTipIframeShim.style.display = 'block';
            toolTipIframeShim.style.top = toolTipIdElement.style.top;
            toolTipIframeShim.style.left = toolTipIdElement.style.left;
            toolTipIframeShim.style.width = toolTipIdElement.style.width;
            toolTipIframeShim.style.height = toolTipIdElement.clientHeight;
          }
        }
    }
}

function hideToolFormTip(toolTipId) {
    var toolTipIdElement = document.getElementById(toolTipId);
    var toolTipIframeShim = document.getElementById('iframe1Shim');

    if (toolTipIdElement) {
        toolTipIdElement.style.display = 'none';
        toolTipIframeShim.style.display = 'none';
    }
}

function changeVisibilityPromotionalCode(isChecked){
    var promotionElement = document.getElementById("promotionCodeDiv");

    if (promotionElement) {
        if (isChecked) {
            promotionElement.style.display = "block";
        } else {
            promotionElement.style.display = "none";
            clearPromotionalCodes();
        }
    }
}

function getFocus(idField, isSelect) {
    var element = $("#" + idField);
    var l_element = $("#L_" + idField);
    var r_element = $("#R_" + idField);

    var styleInput = "inputFormBox";
    var styleInputFocus = "inputFormBox_F";
    var styleInputError = "inputFormBox_E";
    if (isSelect) {
        styleInput = "inputFormBoxS";
        styleInputFocus = "inputFormBoxS_F";
        styleInputError = "inputFormBoxS_E";
    }

    element.removeClass(styleInputError).removeClass(styleInput).addClass(styleInputFocus);
    l_element.removeClass("inputFormBoxL_E").removeClass("inputFormBoxL").addClass("inputFormBoxL_F");
    if (!isSelect) {
        r_element.removeClass("inputFormBoxR_E").removeClass("inputFormBoxR").addClass("inputFormBoxR_F");
    }
}

function lostFocus(idField, isSelect) {
    var element = $("#" + idField);
    var l_element = $("#L_" + idField);
    var r_element = $("#R_" + idField);

    var styleInput = "inputFormBox";
    var styleInputFocus = "inputFormBox_F";
    if (isSelect) {
        styleInput = "inputFormBoxS";
        styleInputFocus = "inputFormBoxS_F";
    }

    element.addClass(styleInput).removeClass(styleInputFocus);
    l_element.addClass("inputFormBoxL").removeClass("inputFormBoxL_F");
    if (!isSelect) {
        r_element.addClass("inputFormBoxR").removeClass("inputFormBoxR_F");
    }
}

function btnSecOver(idBtn) {
    var element = $("#" + idBtn);
    var l_element = $("#L_" + idBtn);
    var r_element = $("#R_" + idBtn);

    element.addClass("btnSec_O").removeClass("btnSec");
    l_element.addClass("btnSec_L_O").removeClass("btnSec_L");
    r_element.addClass("btnSec_R_O").removeClass("btnSec_R");
}

function btnSecOut(idBtn) {
    var element = $("#" + idBtn);
    var l_element = $("#L_" + idBtn);
    var r_element = $("#R_" + idBtn);

    element.removeClass("btnSec_O").addClass("btnSec");
    l_element.removeClass("btnSec_L_O").addClass("btnSec_L");
    r_element.removeClass("btnSec_R_O").addClass("btnSec_R");
}

function cleanNonDigitsIdentificationB(number, idField) {
    try {
        var idVal = $('input:checked[name="' + idField + '"]').val();

        if ((idVal == "NIF") || (idVal == "NIE") || (idVal == "CIF")) {
            return number.replace(/[^0-9a-zA-Z]/gi, "");
        } else {
            return number;
        }
    } catch (e) {
        return number;
    }
}
// Test UX[15611] Passengers Page UX Improvements - end

function findSmsPhoneErrrors() {
	var smsNotification = document.getElementById('smsNotification');
	var phonesIntroduced = [];
	var arePhoneErrors = false;
	if(smsNotification!= null && smsNotification.checked){ //validate that any phone was introduced despite the smsNotification is checked.

		if (!anyPhoneIntroduced(phonesIntroduced)) {
			arePhoneErrors = true;
		} else {
			//Validate the phones introduced
			for (var i = 0; i < phonesIntroduced.length; ++i) {
				smsPhoneData = phonesIntroduced[i];
				if(!checkSmsNumber(smsPhoneData[0].value,smsPhoneData[0],smsPhoneData[1])){
					changeToClass( smsPhoneData[0], "borderRed");
					showPaxAlertInDiv('validMobile', smsPhoneData[1]);
					arePhoneErrors = true;
				}
			}
		}
	}
	return arePhoneErrors;
}

function anyPhoneIntroduced(phonesIntroduced){
	var smsAdded = 0;
	var buyerPhone =  document.getElementById('smsPhoneNumberB');
	var buyerName =  document.getElementById('smsBuyerName');
	if (buyerPhone.value != '') {
		smsAdded++;
		phonesIntroduced.push([buyerPhone,buyerName.value]);
	}
	var smsTravellersPhone = $('input[id*="smsPhoneNumberT"]');
	var smsTravellersNames = $('input[id*="smsTravellerName"]');
	for (var i = 0; i < smsTravellersPhone.length; i++){
		smsTravellerPhone = smsTravellersPhone[i];
		smsTravellerName = smsTravellersNames[i];
		if (smsTravellerPhone.value != ''){
			phonesIntroduced.push([smsTravellerPhone,smsTravellerName.value]);
			smsAdded++
		}
	}
	if (smsAdded == 0){
		changeToClass(buyerPhone, "borderRed");
		showPaxAlertInDiv('validMobile', buyerName.value);
		return false;
	} else {
		return true;
	}
}

function resultsOWASRT(){
    var includeGreylistedOwasrt = document.getElementById("includeGreylistedOwasrt");
    if(includeGreylistedOwasrt){
        includeGreylistedOwasrt.value = 'true';
    }
    if (document.getElementById("swooshTabFareList")) {
        document.getElementById("swooshTabFareList").style.display = "block";
        document.getElementById("swooshTabFare").style.display = "block";
        document.body.style.overflow = "hidden";
    }
    document.getElementById("sorter").submit();
}
function trackResidents(form) {
    if ($('#isresidentTrue:checked').length == 1) {
        gaTrackEvent('form filter', form + '_residents', 'Yes');
    } else {
        gaTrackEvent('form filter', form + 'residents', 'No');
    }
}
function initItineraryResultsPage(isFullPriceEnabled) {	
	if (isFullPriceEnabled) {
		$(document).ready(function () {
	    	$('#numBaggage').change(function (e) {
	    		var value = 'false';
				var intNumBaggage = parseInt($(this).val(), 10);
				if (intNumBaggage > 0) {
				    value = 'true';
			    }
				$('#baggageEstimationNeeded').val(value);
			});
	    	
	    	$('#buttonItiExtras').click(function (e) {
	    		$('#collectionTypeEstimationNeeded, #applyAllTaxes').val('true');
	    	});
	    	
	    	var moreOrLessPaymentMethodsOption = $('[id^="moreOrLessPaymentMethods"]');
	    	if (moreOrLessPaymentMethodsOption.length > 0) {
	    		moreOrLessPaymentMethodsOption.click(function (e) {
	    			var id = $(this).attr('id').replace('moreOrLessPaymentMethods', '');
	    			var isMorePaymentMethodsSelected = $('#isMorePaymentMethods' + id);
	    			if (isMorePaymentMethodsSelected.val() == 'true') {
	    				$('#more' + id).addClass('displayNone');
	    				$('#less' + id).removeClass('displayNone');
	    				$('#moreLessImage'+id).removeClass('morePaymentMethods').addClass('lessPaymentMethods');
	    				$('#restOfPaymentMethods' + id).removeClass('displayNone');
	    				isMorePaymentMethodsSelected.val('false');
	    			} else {
	    				$('#less' + id).addClass('displayNone');
	    				$('#more' + id).removeClass('displayNone');
	    				$('#moreLessImage' + id).removeClass('lessPaymentMethods').addClass('morePaymentMethods');
	    				$('#restOfPaymentMethods' + id).addClass('displayNone');
	    				isMorePaymentMethodsSelected.val('true');
	    			}
	    		});
	    	}
		});
	}
}

