function showLabel(event, spanId) {
    var posx = 0;
    var posy = 0;
    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 + "px";
    mySpan.style.left = posx + "px";
}
function hideLabel(spanId) {
    document.getElementById(spanId).style.display = 'none';
}
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, pais, 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_" + pais + " " + 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_" + pais + " " + 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) {
    var iframeParams = document.getElementById("iframeParams").value;
    if (kind != "flightsSearch" && kind != "trainsSearch" && kind != "pauschalreisenSearch" && kind != "vacanzeSearch") {
        window.location.href = url;
    } else {
        var sflightsSearchSpan,spauschalreisenSearchSpan,strainsSearchSpan,svacanzeSearchSpan;
        if (document.getElementById("sflightsSearch")) {
            sflightsSearchSpan = document.getElementById("sflightsSearch");
        }
        if (document.getElementById("strainsSearch")) {
            strainsSearchSpan = document.getElementById("strainsSearch");
        }
        if (document.getElementById("svacanzeSearch")) {
            svacanzeSearchSpan = document.getElementById("svacanzeSearch");
        }
        if (document.getElementById("spauschalreisenSearch")) {
            spauschalreisenSearchSpan = document.getElementById("spauschalreisenSearch");
        }
        var engineIfr = document.getElementById("engineIfr");
        if (kind == "trainsSearch" && selectedKind != "trainsSearch") {
            sflightsSearchSpan.className = "";
            if (svacanzeSearchSpan) {
                svacanzeSearchSpan.className = "";
            }
            if (spauschalreisenSearchSpan) {
                spauschalreisenSearchSpan.className = "";
            }
            strainsSearchSpan.className = "bold";

            engineIfr.src = "/engine/searchEngines/trains/homeTrainsSearchEngine.jsp";
            document.getElementById("messageDreamito").style.background = "url(/images/shared/new/modulo_azul_tre.gif) no-repeat";
            clearErrors();
        } else if (kind == "flightsSearch" && selectedKind != "flightsSearch") {
            sflightsSearchSpan.className = "bold";
            if (svacanzeSearchSpan) {
                svacanzeSearchSpan.className = "";
            }
            if (spauschalreisenSearchSpan) {
                spauschalreisenSearchSpan.className = "";
                document.getElementById("pauschalreisenSearchDiv").style.display = "none";
            }
            if (strainsSearchSpan) {
                strainsSearchSpan.className = "";
            }

            engineIfr.src = "/engine/searchEngines/flights/homeFlightsSearchEngine.jsp"+iframeParams;
            document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_vue_" + lang + ".gif) no-repeat";
            clearErrors();
        } else if (kind == "pauschalreisenSearch" && selectedKind != "pauschalreisenSearch") {
            sflightsSearchSpan.className = "";
            spauschalreisenSearchSpan.className = "bold";
            if (strainsSearchSpan) {
                strainsSearchSpan.className = "";
            }
            if (svacanzeSearchSpan) {
                svacanzeSearchSpan.className = "";
            }
            //engineIfr.src = "/engine/searchEngines/pauschalreisen/pauschalreisenEngine.jsp";
            document.getElementById("messageDreamito").style.background = "url(/images/newhome/mod_azul/mod_azul_pau_de.gif) no-repeat";
            engineIfr.src = "/engine/static-content/html/blank.html";
            document.getElementById("pauschalreisenSearchDiv").style.display = "block";
            clearErrors();
        } else if (kind == "vacanzeSearch" && selectedKind != "vacanzeSearch") {
            sflightsSearchSpan.className = "";
            strainsSearchSpan.className = "";
            svacanzeSearchSpan.className = "bold";
            engineIfr.src = "http://edreams.phoneandgo.it/se/edreams.html";
            document.getElementById("messageDreamito").style.background = "url(/images/shared/new/modulo_azul_tre.gif) no-repeat";
            clearErrors();
        }
        selectedKind = kind;
    }
}

var countriesDivOpened = false;
function displayCountriesDiv() {
    var countriesDiv = document.getElementById("countriesDiv");
    if (!countriesDivOpened) {
        countriesDiv.style.display = "block";
        countriesDivOpened = true;
    } else {
        countriesDiv.style.display = "none";
        countriesDivOpened = false;
    }
}
var isFlexible = false;
function showFrameBox(address, obj, iframe, left, top, train) {
    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;
        }
    }
    //alert(parent.document.getElementById(iframe))
    var docScope;
    var engineFrOffsetTop, engineFrOffsetLeft;
    if (document.getElementById(iframe)) {
        docScope = document;
        engineFrOffsetTop = 0;
        engineFrOffsetLeft = 0;
    } else if (parent.document.getElementById(iframe)) {
        docScope = parent.document;
        engineFrOffsetTop = findOffsetTop(docScope.getElementById('engineIfr'));
        engineFrOffsetLeft = findOffsetLeft(docScope.getElementById('engineIfr'));
    }
    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 (styleLeft < 100) {
        styleLeft = 100;
    }
    aBox.style.top = styleTop + 'px';
    aBox.style.left = styleLeft + 'px';
    aBox.style.display = 'block';
    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;

}

function findOffsetLeft(element) {
    return findOffset(element, "offsetLeft");
}

function findOffsetTop(element) {
    return findOffset(element, "offsetTop");
}

function findOffset(element, type) {
    var os = 0;
    while (element) {
        os += element[type];
        element = element.offsetParent;
    }
    return os;
}
var cityLoad = false;
var dateLoad = false;
var airlinesLoad = false;
var scalesLoad = false;
var detailLoad = false;
var desgloseLoad = false;
var notesInfoLoad = false;
var creditCardInfoLoad = false;
var cardsInfoBoxLoad = false;
var conditionsload = false;
var conditionsLowLoad = false;
var conditionsPhotoLoad = false;
var emailFormLoad = false;
var isIframe = false;
var forgotLoad = false;
var nLConditionsLoad = false;
var farePerPaxLoad = false;
var notesPayment = false;
var securityInfoLoad = false;
var photoIdLoad = false;
var infoCardsLoad = false;
var infoCardsLoad = false;

function close_layers() {
    //    search engine on iframe and pickers on parent
    var varsScope;
    varsScope = (isIframe) ? parent : this;
    if (varsScope.dateLoad) {
        varsScope.document.getElementById("ifCalendarBox").style.display = 'none';
        varsScope.dateLoad = false;
    }
    if (varsScope.cityLoad) {
        varsScope.document.getElementById("ifCountriesBox").style.display = 'none';
        varsScope.cityLoad = false;
    }
    //    end
    if (airlinesLoad) {
        document.getElementById("ifAirlinesBox").style.display = 'none';
        airlinesLoad = false;
    }
    if (scalesLoad) {
        document.getElementById("ifScalesBox").style.display = 'none';
        scalesLoad = false;
    }
    if (detailLoad) {
        document.getElementById("ifDetailBox").style.display = 'none';
        detailLoad = false;
    }
    //    alert("desgloseLoad: "+desgloseLoad);
    if (desgloseLoad) {
        document.getElementById("ifDesgloseBox").style.display = 'none';
        desgloseLoad = false;
    }
    if (emailFormLoad) {
        document.getElementById("ifEmailFormBox").style.display = 'none';
        emailFormLoad = false;
    }
    if (forgotLoad) {
        document.getElementById("ifForgotBox").style.display = 'none';
        forgotLoad = false;
    }
    if (nLConditionsLoad) {
        document.getElementById("ifNLConditionsBox").style.display = 'none';
        nLConditionsLoad = false;
    }
    if (notesInfoLoad) {
        document.getElementById("ifNotesInfoBox").style.display = 'none';
        notesInfoLoad = false;
    }
    if (creditCardInfoLoad) {
        document.getElementById("ifCreditCardInfoBox").style.display = 'none';
        creditCardInfoLoad = false;
    }
    if (securityInfoLoad) {
        document.getElementById("ifSecurityInfoBox").style.display = 'none';
        securityInfoLoad = false;
    }
    if (cardsInfoBoxLoad) {
        document.getElementById("ifCardsInfoBox").style.display = 'none';
        cardsInfoBoxLoad = false;
    }
    if (conditionsload) {
        document.getElementById("ifConditionsBox").style.display = 'none';
        conditionsload = false;
    }
    if (conditionsLowLoad) {
        document.getElementById("ifConditionsLowCostBox").style.display = 'none';
        conditionsLowLoad = false;
    }
    if (conditionsPhotoLoad) {
        document.getElementById("ifConditionsPhotoBox").style.display = 'none';
        conditionsPhotoLoad = false;
    }
    if (farePerPaxLoad) {
        document.getElementById("ifFarePerPaxBox").style.display = 'none';
        farePerPaxLoad = false;
    }
    if (notesPayment) {
        document.getElementById("ifNotesInfoBox").style.display = 'none';
        notesPayment = false;
    }
    if (securityInfoLoad) {
        document.getElementById("ifSecurityInfoBox").style.display = 'none';
        securityInfoLoad = false;
    }
    if (photoIdLoad) {
        document.getElementById("ifConditionsPhotoBox").style.display = 'none';
        photoIdLoad = false;
    }
    if (infoCardsLoad) {
        document.getElementById("ifInfoCardsBox").style.display = 'none';
        infoCardsLoad = false;
    }
    if ((document.getElementById("defCityBox")) && (document.getElementById("defCityBox").style.display == 'block')) {
        document.getElementById("defCityBox").style.display = 'none';
    }
}
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) {
    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") {
            parent.window.location.href = "/engine/flights/multi.jsp";
        } else if (value == "SHUTTLE") {
            parent.window.location.href = "/engine/itineraries/shuttle/index.jsp";
        }
    }
}

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 = "/engine/itineraries/shuttle/index.jsp";
        }
    }
}

function clearErrors(ind) {
    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";
    }
}
var isDynpackSearch = false;
function checkHomeFlightsForm(formId, isDynpack) {
    var errors = 0;
    clearErrors();
    var product;
    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'))errors ++;
    if (!validateCity(formId, 'arrival'))errors ++;
    if (!validateDate(formId, 'departure', errors, isDynpackSearch))errors ++;
    if (isFlexible) {
        return false;
    }
    if (isDynpackSearch) {
        if (!validateThirtyDaysStay())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())errors ++;
    }
    if (errors < 1) {

        showFlightsSearchEnginePopUnder ();

        parent.initSwoosh("paso1", product, formId);

        return true;
    } else {
        return false;
    }
}
function checkSimpleFlightsForm(formId) {
    var errors = 0;
    clearErrors();

    if (!validateCity(formId, 'departure'))errors ++;
    if (!validateCity(formId, 'arrival'))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 checkTrainsForm(formId) {
    var errors = 0;
    clearErrors();
    var isInternational = document.getElementById("trenAuxPickerInternational").checked;
    var form = document.getElementById(formId);
    if (!validateCity(formId, 'departureTrain'))errors ++;
    if (!validateCity(formId, 'arrivalTrain'))errors ++;
    if (!validateDate(formId, 'departure', errors))errors ++;
    if (!isOneWay) {
        if (!validateDate(formId, 'return', errors))errors ++;
    }
    if (!validatePassengers(formId))errors ++;
    if (errors < 1) {
        if (!isInternational) {
            if (isIframe) {
                parent.initSwoosh("paso1", "trenes", formId);
            } else {
                initSwoosh("paso1", "trenes", formId);
            }
        } else {
            form.action = "/engine/searchEngines/trains/launchSearchOutside.jsp";
            form.target = "_blank";
        }
        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())errors ++;
    if (errors < 1) {
        initSwoosh("paso1", "multidestino", "flightsSearch_multi", lang);
        return true;
    } else {
        return false;
    }
}
function checkLinearFlightsForm(formId) {
    var errors = 0;
    clearErrors();
    var product;

    if (!validateCity(formId, 'departure'))errors ++;
    if (!validateCity(formId, 'arrival'))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";
        }
        initSwoosh("paso1", product, formId);

        return true;
    } else {
        return false;
    }
}
function checkChooseAirport(formId, numSegments, lang) {
    var errors = 0;
    clearErrors();
    var segmentsNum = Number(numSegments) + 1;
    if (!validateChooseAirport(formId, segmentsNum))errors ++;
    if (errors < 1) {
        if (segmentsNum <= 1) {

            var elem = document.getElementById("isBDSearch");

            if (elem) {
                var elemArrival = document.getElementById("");

                if (elemArrival) elemArrival.value = "...";
            }

            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'))errors ++;
    if (!validateCity(formId, 'arrival'))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) {
    clearErrors(ind);
    if (!validateItinerary(formId, ind))return false;
    initSwoosh("paso2", "vuelos");
    submitInterval = setInterval("isFlashReady('" + formId + "')", 100);
}
function isFlashReady(formId){
    if(hasLoadedFlash){
        document.getElementById(formId).submit();
        clearInterval(submitInterval);
    }
}
function checkLogin(emailId, passId) {
    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 checkUserData(kind) {
    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) {

    var a = document.getElementsByName(obj.name);

    for (var i = 0; i < a.length; i++) {
        a[i].checked = false;
    }

    obj.checked = true;
}

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';
}

// Dependencias: librerias yui para usar el autocomplete
//    /edreams/static-content/yui/yahoo-dom-event/yahoo-dom-event.js
//    /edreams/static-content/yui/connection/connection-min.js
//    /edreams/static-content/yui/animation/animation-min.js
//    /edreams/static-content/yui/datasource/datasource-min.js
//    /edreams/static-content/yui/autocomplete/autocomplete-min.js
function eDreamsFlightsAutocomplete(inputElement, elementContainer) {
    //
    this.inputElement = inputElement;
    this.elementContainer = elementContainer;

    // Use an XHRDataSource
    var oDataSource = new YAHOO.util.XHRDataSource("/engine/AutoComplete/flight");
    // Set the responseType
    oDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;

    // Define the schema of the JSON results
    oDataSource.responseSchema = {
        resultsList : "cities",
        fields : ["matchName", "cityName", "type", "country", "airportName", "airportCode", "geoNodeId"]
    };

    //number of responses you want held in the cache
    oDataSource.maxCacheEntries = 100;

    //Post
    oDataSource.connMethodPost = true;

    // Instantiate the AutoComplete
    var oAutoComplete = new YAHOO.widget.AutoComplete(this.inputElement, this.elementContainer, oDataSource);

    // configure the autocomplete
    oAutoComplete.useIFrame = true;
    oAutoComplete.minQueryLength = 3;
    oAutoComplete.animVert = false;
    oAutoComplete.animHoriz = false;
    oAutoComplete.maxResultsDisplayed = 200;
    oAutoComplete.minQueryDelay = 0;
    oAutoComplete.allowBrowserAutocomplete = false;

    // Match results of query strings that are cached *subsets* of the current query string
    oAutoComplete.resultTypeList = false;
    oAutoComplete.queryMatchSubset = true;
    oAutoComplete.applyLocalFilter = true;

    oAutoComplete.filterResults = function(sQuery, oFullResponse, oParsedResponse, oCallback) {
        // If AC has passed a query string value back to itself, grab it
        if (oCallback && oCallback.argument && oCallback.argument.query) {
            sQuery = oCallback.argument.query;
        }

        // Only if a query string is available to match against
        if (sQuery && sQuery !== "") {
            // First make a copy of the oParseResponse
            oParsedResponse = YAHOO.widget.AutoComplete._cloneObject(oParsedResponse);

            var oAC = oCallback.scope,
                    oDS = this,
                    allResults = oParsedResponse.results, // the array of results
                    filteredResults = [], // container for filtered results,
                    nMax = oAC.maxResultsDisplayed, // max to find
                    bMatchCase = (oDS.queryMatchCase || oAC.queryMatchCase), // backward compat
                    bMatchContains = (oDS.queryMatchContains || oAC.queryMatchContains); // backward compat

            // Loop through each result object...
            for (var i = 0, len = allResults.length; i < len; i++) {
                var oResult = allResults[i];

                // Grab the data to match against from the result object...
                var sResult = null;

                // Result object is a simple string already
                if (YAHOO.lang.isString(oResult)) {
                    sResult = oResult;
                }
                // Result object is an array of strings
                else if (YAHOO.lang.isArray(oResult)) {
                    sResult = oResult[0];

                }
                // Result object is an object literal of strings
                else if (this.responseSchema.fields) {
                        var key = this.responseSchema.fields[0].key || this.responseSchema.fields[0];
                        sResult = oResult[key];
                    }
                    // Backwards compatibility
                    else if (this.key) {
                            sResult = oResult[this.key];
                        }

                if (YAHOO.lang.isString(sResult)) {

                    var sKeyIndex = (bMatchCase) ?
                                    sResult.indexOf(decodeURIComponent(sQuery).replaceLatinChar()) :
                                    sResult.toLowerCase().indexOf(decodeURIComponent(sQuery).toLowerCase().replaceLatinChar());

                    // A STARTSWITH match is when the query is found at the beginning of the key string...
                    if ((!bMatchContains && (sKeyIndex === 0)) ||
                        // A CONTAINS match is when the query is found anywhere within the key string...
                        (bMatchContains && (sKeyIndex > -1))) {
                        // Stash the match
                        filteredResults.push(oResult);
                    }
                }

                // Filter no more if maxResultsDisplayed is reached
                if (len > nMax && filteredResults.length === nMax) {
                    break;
                }
            }
            oParsedResponse.results = filteredResults;


            if (oParsedResponse.results.length >= 8) {
                YAHOO.util.Dom.getFirstChild(oAC.getContainerEl()).style.height = '11em';
                YAHOO.util.Dom.getFirstChild(oAC.getContainerEl()).style.maxHeight = '11em';
            } else {
                YAHOO.util.Dom.getFirstChild(oAC.getContainerEl()).style.height = '';
                YAHOO.util.Dom.getFirstChild(oAC.getContainerEl()).style.maxHeight = '';
            }
        }

        return oParsedResponse;
    };

    // redefining the request generation
    var acGenerateRequest = function(sQuery) {
        try {
            if (sQuery != '') {
                var str = decodeURIComponent(sQuery);
                sQuery = encodeURIComponent(str.replaceLatinChar());
            }
        } catch(e) {

        }

        return "searchKey=" + sQuery;
    };

    // overloading the request generation
    oAutoComplete.generateRequest = acGenerateRequest;

    // This function returns markup that bolds the original query,
    // and also displays to additional pieces of supplemental data.
    var acFormatResult = function(oResultData, sQuery, sResultMatch) {
        var rType = oResultData.type;
        var sItem = "";

        if (rType == 'CITY') {
            sItem = "<span style='font-weight:bold;'>" + oResultData.cityName.substr(0, sQuery.length) + "</span>" + oResultData.cityName.substr(sQuery.length) + " (" + oResultData.country + ") " + " - " + oResultData.airportName + " " + oResultData.airportCode;
        } else if (rType == 'AIRPORT') {
            sItem = oResultData.cityName + " (" + oResultData.country + ") " + " - " + "<span style='font-weight:bold;'>" + oResultData.airportName.substr(0, sQuery.length) + "</span>" + oResultData.airportName.substr(sQuery.length) + " " + oResultData.airportCode;
        } else if (rType == 'IATA') {
            sItem = oResultData.cityName + " (" + oResultData.country + ") " + " - " + oResultData.airportName + " " + "<span style='font-weight:bold;'>" + oResultData.airportCode + "</span>";
        } else {
            sItem = oResultData.cityName + " (" + oResultData.country + ") " + " - " + oResultData.airportName + " " + oResultData.airportCode + " ";
        }

        return sItem;
    };

    // overloading the format result generation
    oAutoComplete.formatResult = acFormatResult;

    //define your itemSelect handler function:
    var itemSelectHandler = function(sType, aArgs) {
        var oMyAcInstance = aArgs[0];                   // your AutoComplete instance
        //var elListItem = aArgs[1];                      // the <li> element selected in the suggestion container
        var oData = aArgs[2];                           // object literal of data for the result

        var inputElId = document.getElementById(oMyAcInstance.getInputEl().id);

        if (oData.type == 'CITY') {
            inputElId.value = oData.cityName;
        } else if (oData.type == 'AIRPORT') {
            inputElId.value = oData.airportName;
        } else {
            inputElId.value = oData.cityName;
        }

        //Tratamiento especial para el caso de multidestinos.
        var aux = parseInt(inputElId.id.substring(inputElId.id.length - 1, inputElId.id.length));
        var auxId = inputElId.name.substring(0, inputElId.id.length - 1);
        if (!isNaN(aux)) {
            document.getElementById(auxId + "GeoNodeId" + aux).value = oData.geoNodeId;
        } else {
            document.getElementById(oMyAcInstance.getInputEl().id + "GeoNodeId").value = oData.geoNodeId;
        }
    };

    //define your textboxKey handler function:
    var textboxKeyEventhandler = function(sType, aArgs) {
        var oMyAcInstance = aArgs[0];                   // your AutoComplete instance
        var inputElId = document.getElementById(oMyAcInstance.getInputEl().id);

        //Tratamiento especial para el caso de multidestinos.
        var aux = parseInt(inputElId.name.substring(inputElId.name.length - 1, inputElId.name.length));
        if (!isNaN(aux)) {
            document.getElementById(oMyAcInstance.getInputEl().id + "GeoNodeId" + aux).value = "";
        } else {
            document.getElementById(oMyAcInstance.getInputEl().id + "GeoNodeId").value = "";
        }
    };

    //subscribe handlers to the events
    try {
        oAutoComplete.itemSelectEvent.subscribe(itemSelectHandler);
    } catch(errorObject) {
        // capturamos el error
    }

    try {
        oAutoComplete.textboxKeyEvent.subscribe(textboxKeyEventhandler);
    } catch(errorObject) {
    }
}
function cleanTrainCities() {
    document.getElementById("departureLocation").value = "";
    document.getElementById("arrivalLocation").value = "";
    document.getElementById("intCityCode").value = "";
}
function addFlightsToTrains() {
    var toFlights = document.getElementById("toFlights");
    var searchMainProductTypeName = document.getElementById("searchMainProductTypeName");
    if (toFlights.checked) {
        searchMainProductTypeName.value = "FLIGHT";
    } else {
        searchMainProductTypeName.value = "TRAIN";
    }
}
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 closeOfferCitiesBox() {
    if (document.getElementById("defCityBox")) document.getElementById("defCityBox").style.display = 'none';
    if (document.getElementById("defCityBoxShim")) document.getElementById("defCityBoxShim").style.display = 'none';
}
function selectOfferCity(des, page) {
    setOfferCityCookie('dfCityOffers', des, 30, '/');
    window.location.href = page;
}
function setOfferCityCookie(cookieName, cookieValue, nDays, path, domain) {
    var today = new Date();
    var expire = new Date();
    if (nDays == null || nDays == 0) nDays = 1;
    expire.setTime(today.getTime() + 3600000 * 24 * nDays);
    var cookieString = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toUTCString();
    if (domain) {
        cookieString += ";domain=" + domain;
    }
    if (path) {
        cookieString += ";path=" + path;
    }
    //alert(cookieString);
    document.cookie = cookieString;
}
function setSeachCookie(currentValue, product) {
    var cookieName, myPath, depNodeCode, arrNodeCode;
    if (product == "FLIGHT") {
        cookieName = "fsearch";
        depNodeCode = "";
        myPath = "/";
    } else if (product == "TRAIN") {
        cookieName = "tsearch";
        myPath = "/";
    }
    var tripType = (document.getElementById('tripTypeName').checked) ? 'ROUND_TRIP' : 'ONE_WAY';
    var depLoc = document.getElementById('departureLocation').value;
    var arrLoc = document.getElementById('arrivalLocation').value;
    var adults = document.getElementById('numAdults').value;
    var children = document.getElementById('numChilds').value;
    var 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 = "";
    }
    var cookieValue = tripType + "|" + depLoc + "|" + arrLoc + "|" + adults + "|" + children + "|" + infants + "|" + depDate + "|" + retDate + "|" + depNodeCode + "|" + arrNodeCode;
    //        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'))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;
    }
}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};

String.prototype.ltrim = function() {
    return this.replace(/^\s+/, "");
};

String.prototype.rtrim = function() {
    return this.replace(/\s+$/, "");
};

String.prototype.startsWith = function(str) {
    return (this.match("^" + str) == str);
};

String.prototype.endsWith = function(str) {
    return (this.match(str + "$") == str);
};

String.prototype.replaceLatinChar = function() {
    return output = this.replace(/Ã¡|Ã©|Ã­|Ã³|Ãº|Ã¤|Ã«|Ã¯|Ã¶|Ã¼|Ã£|Ãµ/ig, function (str, offset, s) {
        var str = str == "Ã¡" ? "a" : str == "Ã©" ? "e" : str == "Ã­" ? "i" : str == "Ã³" ? "o" : str == "Ãº" ? "u" : str;
        str = str == "Ã " ? "a" : str == "Ã¨" ? "e" : str == "Ã¬" ? "i" : str == "Ã²" ? "o" : str == "Ã¹" ? "u" : str;
        str = str == "Ã¤" ? "a" : str == "Ã«" ? "e" : str == "Ã¯" ? "i" : str == "Ã¶" ? "o" : str == "Ã¼" ? "u" : str;
        str = str == "Ã¢" ? "a" : str == "Ãª" ? "e" : str == "Ã¯" ? "i" : str == "Ã´" ? "o" : str == "Ã»" ? "u" : str;
        str = str == "Ã¢" ? "a" : str == "Ãª" ? "e" : str == "Ã¯" ? "i" : str == "Ã´" ? "o" : str == "Ã»" ? "u" : str;
        str = str == "Ã£" ? "a" : str == "Ãµ" ? "o" : str;
        return (str);
    })
}

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) {
    var errors = 0;
    clearErrors();
    var selectTravellerAndBuyerForm = document.getElementById("selectTravellerAndBuyer");

    if (!checkTravellers(selectTravellerAndBuyerForm))errors++;
    if (!checkBuyer())errors++;
    if (isInvoiceRequired) {
        if (!checkInvoiceData())errors++;
    }
    if (errors < 1) {
        initSwoosh('paso3', 'vuelos', formId);
        return true;
    } else {
        return false;
    }
}
function checkInvoiceData() {
    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++;
    if (!isFieldFilled(idField))errors++;
    if (!isFieldFilled(addressField))errors++;
    if (!isFieldFilled(cityField))errors++;
    if (!isFieldFilled(zipCodeField))errors++;
    if (!validateEmail(emailField))errors++;
    return (errors < 1);
}
function checkBuyer() {
    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");
    if (!lengthHigher(2, nameField)) {
        errors++;
    } else {
        if (!validateJustLetters(nameField))errors++;
    }
    if (!lengthHigher(2, lastNamesField)) {
        errors++;
    } else {
        if (!validateJustLetters(lastNamesField))errors++;
    }
    if (!validateEmail(emailField))errors++;
    if (!isFieldFilled(idField))errors++;
    if (idTypeField.value == "NIF" || idTypeField.value == "NIE") {
        if (!isValidID(idField, idTypeField.value))errors++;
    }
    if (!isFieldFilled(addressField))errors++;
    if (!isFieldFilled(cityField))errors++;
//    if (!isFieldFilled(regionField))errors++;
    if (!isFieldFilled(zipCodeField))errors++;
    if (!isFieldFilled(phoneNumber1Field)) {
        errors++;
    } else {
        if (!validateMobile(phoneNumber1Field))errors++;
    }

    return (errors < 1);
}
var frequentFlyerAirlineCodesSetFieldValue = "";
function checkTravellers(selectTravellerAndBuyerForm) {
    initFrequentFlyerAirlineCodesSetFieldValue();
    var errors = 0;
    var dayOfBirthValue, monthOfBirthValue, yearOfBirthValue, elementId, identificationExpirationDay, identificationExpirationMonth, identificationExpirationYear;
    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") {
                    if (PaxFieldId != "companyMemberNum" && PaxFieldId != "secondLastName") {
                        if (!isFieldFilled(PaxFieldId, PaxInd)) {
                            errors++;
                        } else {
                            if (PaxFieldId == "name" || PaxFieldId == "firstLastName") {
                                if (!lengthHigher(2, PaxFieldId, PaxInd)) {
                                    errors++;
                                } else {
                                    if (!validateJustLetters(PaxFieldId, PaxInd))errors++;
                                }
                            }
                            if (PaxFieldId == "identification") {
                                var identificationTypeName = document.getElementById("identificationTypeName_" + PaxInd);
                                if (identificationTypeName.value == "NIF" || identificationTypeName.value == "NIE") {
                                    if (!isValidID(PaxFieldId, identificationTypeName.value, PaxInd))errors++;
                                }
                            }
                        }
                    }
                    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);
                        }
                    }

                    if (PaxFieldId == "yearOfBirth")yearOfBirthValue = field.value;
                    if (PaxFieldId == "companyMemberNum") {
                        handleFrequentFlyerAirlineCodesSet(PaxFieldId, PaxInd);
                    }
                } else if (tagName == "SELECT") {
                    if (PaxFieldId == "dayOfBirth")dayOfBirthValue = field.value;
                    if (PaxFieldId == "monthOfBirth")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 (!isDayWithinMonth(dayOfBirthValue, monthOfBirthValue, yearOfBirthValue, PaxFieldId, PaxInd)) {
                            errors++;
                            //                        } else if(){

                        } else {
                            if (!isYearBeforeToday(yearOfBirthValue, PaxFieldId, PaxInd)) {
                                errors++;
                            } else {
                                if (isInputYearthisYear) {
                                    if (!isMonthBeforeToday(monthOfBirthValue, PaxFieldId, PaxInd))errors++;
                                }
                            }
                        }
                        //                        if(paxType!="ADULT"){
                        if (!isPaxTypeAge(paxType, returnDate, dayOfBirthValue, monthOfBirthValue, yearOfBirthValue, PaxFieldId, PaxInd))errors++;
                        //                        }
                    }
                }
            }
        }
    }
    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() {
    for(var i=0; i<invalidSmsNums.length; ++i){
        invalidSmsNums[i].value = "";
    }
    var errors = 0;
    clearErrors();
    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");
        return false;
    }

    switch (selectedCollectionMethodTypeName) {
    case "creditPaymentMethod":
        if (!checkCreditCardMethod())errors++;
        break;
    case "ELVPaymentMethod":
        if (!checkELVMethod())errors++;
        break;
    case "paypalPaymentMethod":
        break;
    case "bankTransferPaymentMethod":
        break;
    }

    if (document.getElementById("closeBookingFromPayment")["radioButtonInsurance"]) {
        if (!validateInsurances())errors++;
    }
    if (!validateConditions(acceptedconditions, 'payment'))errors++;
    if (errors < 1) {
        initSwoosh('paso4', 'vuelos', 'closeBookingFromPayment');
        check_waitingTime(true);
    }
    //
    return false;
}
function checkCreditCardMethod() {
    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 cardSecNum = document.getElementById("cardSecNum");
    if (!validateNotEmptySelect(cardTypeCodeSelect))errors++;
    if (!isFieldFilled(cardOwner)) {
        errors++;
    } else {
        if (!validateJustLetters(cardOwner))errors++;
    }
    if (!isFieldFilled(cardNumber)) {
        errors++;
    } else {
        if (!validateCardNumber(cardNumber, cardNumber.value, cardTypeCodeSelect.value))errors++;
    }
    if (!isFieldFilled(cardExpirationMonth)) {
        errors++;
        expirationErrors++;
    }

    if (!isFieldFilled(cardExpirationYear)) {
        errors++;
        expirationErrors++;
    }
    if (expirationErrors < 1) {
        if (!validateExpirationDate(cardExpirationMonth, cardExpirationYear))errors++;
    }
    if (!isFieldFilled(cardSecNum)) {
        errors++;
    } else {
        if (!validateSecurityCode(cardSecNum, cardTypeCodeSelect.value))errors++;
    }

    return (errors < 1);
}
function checkELVMethod() {
    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++;
    if (!isFieldFilled(ELVAccount))errors++;
    if (!isFieldFilled(ELVSurname))errors++;
    if (!isFieldFilled(ELVBank))errors++;
    if (!isFieldFilled(ELVCredit))errors++;

    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) {
    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 + "')", warning1Time);
    }
    if (warning2Time >= minimumTimeInPage) {
        warningInterval2 = setInterval("fireWarning('" + (maxTime - secondTimeToLimit) + "', '" + maxTime + "', '" + 2 + "')", warning2Time);
    }
    finalWarningInterval = setInterval("fireFinalWarning('" + maxTime + "', '" + formId + "')", closeWarningTime);
}
function fireWarning(timeToAlert, maxTime, warningIntervalInd) {
    var warInterval = eval("warningInterval" + warningIntervalInd);
    var timeLeft = maxTime - timeToAlert;
    alertSessionTimeoutWarning(timeToAlert, timeLeft);
    clearInterval(warInterval);
}
function fireFinalWarning(maxTime, formId) {
    //    alert("FinalWarning");
    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 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 == 'none') {
        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 numOfPopUnders = 0;
    var hasLiligoPopUnder = document.getElementById("hasLiligoPopUnder");
    if(hasLiligoPopUnder != null && hasLiligoPopUnder.value=='true'){
        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.fr/edreams/siteunder_ta.jsp?FROM=' + depCode + '&TO=' + retCode + '&DEPART_DD=' + depDay + '&DEPART_MM=' + depMonth + '&DEPART_YYYY=' + depYear + '&RETOUR_DD=' + retDay + '&RETOUR_MM=' + retMonth + '&RETOUR_YYYY=' + retYear;
        window.open(url,'','width=650,height=415,scrollbars=yes');
        window.self.focus();
     }
    return numOfPopUnders;
}

