$(function() {
    $("#txtGenericSearch").focus(function() {
        if ($(this).val() == "PESQUISAR") {
            $(this).val("");
        }
    });

    $("#txtGenericSearch").blur(function() {
        if ($(this).val() == "") {
            $(this).val("PESQUISAR");
        }
    });

    $("#txtNewsletterEmail").focus(function() {
        if ($(this).val() == "Inserir e-mail") {
            $(this).val("");
        }
    });

    $("#txtNewsletterEmail").blur(function() {
        if ($(this).val() == "") {
            $(this).val("Inserir e-mail");
        }
    });

    $("#frmNewsletterRegistration").submit(function(e) {
        e.preventDefault();

        $("#divNewsletterRegistration").hide();
        $("#divNewsletterRegistration_message").hide();
        $("#divNewsletterRegistration_loading").show();

        $.post($("#frmNewsletterRegistration").attr("action"), $("#frmNewsletterRegistration").serialize(), function(response, status, xhr) {
            $("#divNewsletterRegistration_message").html(response);

            $("#divNewsletterRegistration_loading").hide();
            $("#divNewsletterRegistration_message").show();

            if ($("#divNewsletterRegistration_message div.msgOk").length > 0) {
                $("#txtNewsletterEmail").val("Inserir e-mail");
            }

            $("#divNewsletterRegistration").show();
        });
    });

    $("#butNewsletterRegistration").click(function(e) {
        e.preventDefault();

        $("#frmNewsletterRegistration").submit();
    });

    $("#divEngines .motoresmenu ul li a").click(function(e) {
        e.preventDefault();

        $("#divEngines .motoresmenu ul li a").removeClass("active");

        $(this).addClass("active");

        $("#divEngines .motorformhp").hide();
        $("#divEngine" + $(this).attr("id").replace("linkEngine", "")).show();
    });

    $("#chkEngineAirIsOneWayTrip").click(function(e) {
        if ($(this).is(":checked")) {
            $("#divEngineAirReturnDate").css("visibility", "hidden");
            if ($("#divEngineAirReturnSchedules") != null)
                $("#divEngineAirReturnSchedules").css("visibility", "hidden");
        }
        else {
            $("#divEngineAirReturnDate").css("visibility", "visible");
            if ($("#divEngineAirReturnSchedules") != null)
                $("#divEngineAirReturnSchedules").css("visibility", "visible");
        }
    });

    if ($("#chkEngineAirIsOneWayTrip").is(":checked")) {
        $("#divEngineAirReturnDate").css("visibility", "hidden");
        if ($("#divEngineAirReturnSchedules") != null)
            $("#divEngineAirReturnSchedules").css("visibility", "hidden");
    }
});

function SubmitAirEngine() {
    if (ValidateAirEngine()) {
        $("#frmEngineAir").submit();
    }
}

function ValidateAirEngine() {
    if ($("#txtEngineAirDepartureCity").val() == "") {
        alert("Tem que preencher a cidade de partida.");
        $("#txtEngineAirDepartureCity").focus();
        return false;
    }

    if ($("#txtEngineAirDestinationCity").val() == "") {
        alert("Tem que preencher a cidade de destino.");
        $("#txtEngineAirDestinationCity").focus();
        return false;
    }

    if ($("#txtEngineAirDepartureDate").val() == "") {
        alert("Tem que preencher a data de partida.");
        $("#txtEngineAirDepartureDate").focus();
        return false;
    }

    if (!IsDateValid($("#txtEngineAirDepartureDate").val())) {
        alert("A data de partida é inválida.");
        $("#txtEngineAirDepartureDate").focus();
        return false;
    }

    if ($("#chkEngineAirIsOneWayTrip:checked").length == 0) {
        if ($("#txtEngineAirReturnDate").val() == "") {
            alert("Tem que preencher a data de regresso.");
            $("#txtEngineAirReturnDate").focus();
            return false;
        }

        if (!IsDateValid($("#txtEngineAirReturnDate").val())) {
            alert("A data de regresso é inválida.");
            $("#txtEngineAirReturnDate").focus();
            return false;
        }
    }

    return true;
}

function IsDateValid(strInput, splitter) {
    if (splitter == null) {
        splitter = "/";
    }

    var strDate = Trim(strInput);
    var arrDate = strDate.split(splitter);

    if (arrDate.length != 3) {
        return false;
    }
    else {
        var day = arrDate[0];
        var month = arrDate[1];
        var year = arrDate[2];

        if (!IsNumberValid(day) || !IsNumberValid(month) || !IsNumberValid(year)) {
            return false;
        }
        else {
            if (String(year).length != 4) {
                return false;
            }
            else {
                return ValidateDate(day, month, year);
            }
        }
    }
}

function IsNumberValid(strInput) {
    var str = Trim(strInput);
    var currChar;

    for (var i = 0; i < str.length; i++) {
        currChar = str.charAt(i);

        if (currChar < "0" || "9" < currChar)
            return false;
    }

    return true;
}

function Trim(str) {
    return str.replace(/^\s+|\s+$/, '');
}

function ValidateDate(day, month, year) {
    var totalDaysInFeb = (IsRegularYear(year) ? 28 : 29);

    if (month < 1 || month > 12)
        return false;

    if (month == 2)
        return (day <= totalDaysInFeb);
    else
        return (day <= GetDaysInMonth(month));
}

function IsRegularYear(year) {
    return !(((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0);
}

function GetDaysInMonth(month) {
    var minDaysInMonth = 30;
    var maxDaysInMonth = 31;
    if (month < 8)
        return (minDaysInMonth + (month % 2));
    return (maxDaysInMonth - (month % 2));
}

function RemoveSpaces(strInput) {
    var strOuput = String(strInput);

    return strOuput.replace(/ /g, "");
}

function NumberFormat(number, decimalDigits, decimalSeparator, groupSeparator) {
    // Formats a number with grouped thousands
    //
    // *     example 1: NumberFormat(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: NumberFormat(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: NumberFormat(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: NumberFormat(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: NumberFormat(1000);
    // *     returns 5: '1,000'
    // *     example 6: NumberFormat(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: NumberFormat(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: NumberFormat(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: NumberFormat(0.9, 0);
    // *     returns 9: '1'
    // *     example 10: NumberFormat('1.20', 2);
    // *     returns 10: '1.20'
    // *     example 11: NumberFormat('1.20', 4);
    // *     returns 11: '1.2000'
    // *     example 12: NumberFormat('1.2000', 3);
    // *     returns 12: '1.200'

    var n = number, prec = decimalDigits;

    var toFixedFix = function(n, prec) {
        var k = Math.pow(10, prec);
        return (Math.round(n * k) / k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof groupSeparator === 'undefined') ? '.' : groupSeparator;
    var dec = (typeof decimalSeparator === 'undefined') ? ',' : decimalSeparator;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0, i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep + '$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length - decPos - 1) < prec) {
        s += new Array(prec - (s.length - decPos - 1)).join(0) + '0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec + new Array(prec).join(0) + '0';
    }

    return s;
}

/* ======================================================================
FUNCTION:	isCreditCardValid(strCC_Number, strCC_Type)
INPUT:		strCC_Number - A string representing a credit card number
strCC_Type - A string representing a credit card type
(Visa, American Express, Master Card, ...)
RETURNS:		true, if the credit card is valid (number, and type)
false, otherwise.
====================================================================== */
function isCreditCardValid(strCC_Number, strCC_Type) {
    var CCTypeValidation;
    var strCC_Number_len = strCC_Number.length;
    var strCC_Type_Upper = String(RemoveSpaces(strCC_Type.toUpperCase()));

    // O Número precisa de ter pelo menos 4 digitos para se efectuar as validações
    if (strCC_Number_len < 4)
        return false;

    var firstDigit = parseInt(strCC_Number.substr(0, 1), 10);
    var secondDigit = parseInt(strCC_Number.substr(1, 1), 10);
    var first4Digits = strCC_Number.substr(0, 4);

    switch (strCC_Type_Upper) {
        case "VISA":
            // Sample number: 4111 1111 1111 1111 (16 digits)
            if (((strCC_Number_len == 16) || (strCC_Number_len == 13))
				&& (firstDigit == 4))
                CCTypeValidation = true;
            else
                CCTypeValidation = false;
            break;
        case "MASTERCARD":
        case "EUROCARD":
            // Sample number: 5500 0000 0000 0004 (16 digits)
            if ((strCC_Number_len == 16) && (firstDigit == 5)
				&& ((secondDigit >= 1) && (secondDigit <= 5)))
                CCTypeValidation = true;
            else
                CCTypeValidation = false;
            break;
        case "AMEX":
        case "AMERICANEXPRESS":
            // Sample number: 340000000000009 (15 digits)
            if ((strCC_Number_len == 15) && (firstDigit == 3)
				&& ((secondDigit == 4) || (secondDigit == 7)))
                CCTypeValidation = true;
            else
                CCTypeValidation = false;
            break;
        case "DINERSCLUB":
        case "CARTEBLANCHE":
        case "EBLANCHE":
            // Sample number: 30000000000004 (14 digits)
            if ((strCC_Number_len == 14) && (firstDigit == 3)
				&& ((secondDigit == 0) || (secondDigit == 6) || (secondDigit == 8)))
                CCTypeValidation = true;
            else
                CCTypeValidation = false;
            break;
        case "DISCOVER":
            // Sample number: 6011000000000004 (16 digits) 
            if ((strCC_Number_len == 16) && (first4Digits == "6011"))
                CCTypeValidation = true;
            else
                CCTypeValidation = false;
            break;
        case "ENROUTE":
            // Sample number: 201400000000009 (15 digits)
            if ((strCC_Number_len == 15) &&
				((first4Digits == "2014") || (first4Digits == "2149")))
                CCTypeValidation = true;
            else
                CCTypeValidation = false;
            break;
        case "JCB":
            // Sample number:
            if ((strCC_Number_len == 16)
				&& ((first4Digits == "3088")
				|| (first4Digits == "3096")
				|| (first4Digits == "3112")
				|| (first4Digits == "3158")
				|| (first4Digits == "3337")
				|| (first4Digits == "3528")))
                CCTypeValidation = true;
            else
                CCTypeValidation = false;
            break;
        default:
            CCTypeValidation = true;
            break;
    }

    if (CCTypeValidation)
        return isCreditCardNumberValid(strCC_Number);
    else
        return false;
}

/* ======================================================================
FUNCTION:	isCreditCardNumberValid(strCC_Number)
INPUT:		strCC_Number - A string representing a credit card number
RETURNS:		true, if the credit card number passes the Luhn Mod-10 test. 
false, otherwise.
====================================================================== */
function isCreditCardNumberValid(strCC_Number) {
    var auxDigit, i, tproduct, sum, mul, strCC_Number_len;

    sum = 0;
    mul = 1;
    strCC_Number_len = strCC_Number.length;

    // Encoding only works on cards with less than 19 digits
    if (strCC_Number_len > 19)
        return false;

    for (i = 0; i < strCC_Number_len; i++) {
        auxDigit = strCC_Number.substr(strCC_Number_len - i - 1, 1);
        tproduct = parseInt(auxDigit, 10) * mul;

        if (tproduct >= 10)
            sum += (tproduct % 10) + 1;
        else
            sum += tproduct;

        if (mul == 1)
            mul++;
        else
            mul--;
    }

    if (sum % 10 == 0)
        return true;
    else
        return false;
}
function setCountry(region,country){
    loadCountries(region);
    regionControl = document.getElementById("ddEngineVacationsZone");
    for(i=0; i<regionControl.length; i++)
    {
        if(regionControl.options[i].value == region)
        {
            regionControl.selectedIndex = i;
            break;
         }
    }
    countryControl = document.getElementById("ddEngineVacationsCountry");
    for(i=0; i<countryControl.length; i++)
    {
        if(countryControl.options[i].value == region + "|" + country)
        {
            countryControl.selectedIndex = i;
            break;
         }
    }
}
