﻿/// <reference path="Enums.js" />

var CurrencyPrefixed = true;
var CurrentCurrencyFormat; //"R$ " or " PTS"
var StyleDivFunfo;

var PriceGroupsUC = undefined;
var HotelsUC = undefined;

var isB2B = function () { return CurrentPointOfSale.toUpperCase() == "BRADESCO" || CurrentPointOfSale.toUpperCase() == "AMEX" };
var isAir = function () { return PriceGroupsUC && !HotelsUC };
var isHotel = function () { return !PriceGroupsUC && HotelsUC };
var isAirHotel = function () { return PriceGroupsUC && HotelsUC };

function GetHTML(elementId) {
    var element = document.getElementById(elementId);

    var content = element.value;     // Like textarea.value.

    if (content == null || content == "")
        content = element.innerHTML; // Like textarea.innerHTML.

    return content.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
}

function GetActualItem(shoppingCart) {
    if (isAir)
        return shoppingCart.AirItems[0];
    else if (isHotel)
        return shoppingCart.HotelItems[0];
    else if (isAirHotel)
        return shoppingCart.AirHotelItems[0];
}

function GetActualItems(shoppingCart) {
    if (isAir)
        return shoppingCart.AirItems;
    else if (isHotel)
        return shoppingCart.HotelItems;
    else if (isAirHotel)
        return shoppingCart.AirHotelItems;
}

function StringToDateValues(str) {
    if (str != undefined && str != null && str != "")
        return {
            Year: str.split("/")[2],
            Month: str.split("/")[1],
            Day: str.split("/")[0],
            isValid: true
        };

    return {
        Year: 1,
        Month: 1,
        Day: 1,
        isValid: false
    };
}

function DateValuesToDate(objDate) {
    if (objDate.Year != undefined && objDate.Month != undefined && objDate.Day != undefined)
        return new Date(objDate.Year, objDate.Month - 1, objDate.Day, 01, 00, 00);

    return null;
}

function CompareDateValues(dOne, dTwo) {
    return (dOne && dTwo) && (dOne.Year == dTwo.Year) && (dOne.Month == dTwo.Month) && (dOne.Day == dTwo.Day);
}

function FormatCompleteDate(dt) {
    var returnDate = dt.Day + " de " + Months[dt.Month] + " de " + dt.Year + " " + (dt.Hour == 0 ? "0" : "") + dt.Hour + ":";

    if (dt.Minutes != undefined)
        returnDate += (dt.Minutes < 10 ? "0" : "") + dt.Minutes;

    return returnDate;
}

function GetDescriptionAgeBandType(type, qtd) {
    var strType;
    switch (type) {
        case 1:
            strType = 'Adulto';
            break;
        case 2:
            strType = 'Criança';
            break;
        case 3:
            strType = "Bebê";
            break;
        case 4:
            strType = "Idoso";
            break;
        case 5:
            strType = "Adolescente";
            break;
    }
    if (qtd > 1 || qtd == 0)
        strType += 's';
    return strType;
}
function FormatPointsB2B(value) {
    return Math.ceil(value);
}

function FormatCompleteDateDiference(dtStart, dtFinal) {

    var dtS = DateValuesToDate(dtStart);
    var dtF = DateValuesToDate(dtFinal);

    var dtD = (dtF - dtS);

    returnDate = dtD.Day + " de " + Months[dtD.Month] + " de " + dtD.Year + " " + dtD.Hour + ":";

    if (dtD.Minutes != undefined)
        returnDate += (dtD.Minutes < 10 ? "0" : "") + dtD.Minutes;

    return returnDate
}

function FormatSimpleDateTimeValues(dt) {
    return (dt.Day < 10 ? "0" : "") + parseFloat(dt.Day) + "/" + (dt.Month < 10 ? "0" : "") + parseFloat(dt.Month) + "/" + dt.Year + " " + (dt.Hour < 10 ? "0" : "") + dt.Hour + ":" + (dt.Minutes < 10 ? "0" : "") + dt.Minutes;
}

function FormatSimpleTimeValues(dt) {
    return (dt.Hour < 10 ? "0" : "") + dt.Hour + ":" + (dt.Minutes < 10 ? "0" : "") + dt.Minutes; ;
}

function FormatSimpleDateValues(dt) {
    return (dt.Day < 10 ? "0" : "") + parseFloat(dt.Day) + "/" + (dt.Month < 10 ? "0" : "") + parseFloat(dt.Month) + "/" + dt.Year;
}

function FormatUSDSimpleDateValues(dt) {
    return (dt.Month < 10 ? "0" : "") + parseFloat(dt.Month) + "/" + (dt.Day < 10 ? "0" : "") + parseFloat(dt.Day) + "/" + dt.Year;
}

function FormatDecimalPointsB2B(value) {
    var strNumber = Math.ceil(value).toString();
    while (strNumber.match(/^\d{4}/)) {
        strNumber = strNumber.replace(/(\d)(\d{3}(\.|$))/, '$1.$2');
    }
    return strNumber;
}

function FormatTripTypeCode(TripType) {

    if (TripType == 0)
        return "None";

    if (TripType == 1)
        return "OW";

    if (TripType == 2)
        return "RT";
}

//Para campos não aceitarem caracter especial só incluir a classe sem-caracter-especial
$('.sem-caracter-especial').live('keypress', function (e) {
    var aceitos = "ABCDEFGHIJKLMNOPQRSTUVXZWYabcdefghijklmnopqrstuvxzwyÇçãÃõÕóÓòÒáÁàÀéèÉÈíìÍÌ";

    if (e.which > -1 && e.which < 33)
        return true;

    if (aceitos.indexOf(String.fromCharCode(e.which)) == -1)
        e.preventDefault();
});

$('.sem-caracter-especial2').live('blur', function (e) {
    $(this).val($(this).val().RemoveDiacritics());
    if ($(this).val().replace(/[^a-zA-Z]+/g, '').length != $(this).val().length)
        $(this).val('');
});

$('.sem-caracter-especial-mantem-espacos').live('blur', function (e) {
    $(this).val($(this).val().RemoveDiacritics());
    if ($(this).val().replace(/[^a-zA-Z ]+/g, '').length != $(this).val().length)
        $(this).val('');
});

$('.sem-caracter-especial-location').live('blur', function (e) {
    $(this).val($(this).val().RemoveDiacritics());
    if ($(this).val().replace(/[^a-zA-Z \/,().'¸`-]+/g, '').length != $(this).val().length)
        $(this).val('');
});

$('.somente-numeros').live('blur', function (e) {
    var ctrl = $(this);

    if (ctrl.val().replace(/[^0-9]+/g, '').length != ctrl.val().length)
        ctrl.val('');
});

$('.data-valida').live('blur', function (e) {
    if (!isValidDate(this.value))
        this.value = '';
});

$().mousemove(function (e) {
    var XMousePosition = e.pageX;
    var YMousePosition = e.pageY;
});

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"dom", "seg", "ter", "qua", "qui", "sex", "sab",
		"Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sabado"
	],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
	]
};

Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

Date.prototype.addDays = function (days) {
    this.setDate(this.getDate() + days);
}

ContainsSpecialCharacters = function (value) {

    var strValue = value.toString();
    var SpecialCharacters = ["#", "@", "!", "?", "=", "*", "%", "¨", "$", "+", "[", "]", "{", "}"];

    for (var x = 0; x < strValue.length; x++)
        if (InArray(strValue.charAt(x), SpecialCharacters))
            return true;

    return false;
}



String.prototype.replaceAll = function (OldValue, NewValue) {
    var returnValue = this;
    while (returnValue.indexOf(OldValue) >= 0) {
        returnValue = returnValue.replace(OldValue, NewValue);
    }
    return returnValue.toString();
};

String.prototype.capitalize = function () {
    return this.replace(/\S+/g, function (a) {
        return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase();
    });
};

String.prototype.initialLowerCase = function () {
    return this.replace(/\S+/g, function (a) {
        return a.charAt(0).toLowerCase() + a.slice(1);
    });
}

function getNumericTime(dateIn) {
    var NumericTime = dateIn.Hour + (dateIn.Minutes < 10 ? "0" : "") + dateIn.Minutes;
    return parseFloat(NumericTime);
}

function FormatDateUTC(hr) {
    var d = new Date();
    var res = "";

    d.setUTCDate(hr);

    res = d.getFullYear() != 1 ? d.format("dd/mm/yyyy HH:MM") : "";

    return res;
}

function FormatDateWhithoutTimezone(dt) {
    var d = dt;

    // Soma os minutos equivalentes ao timezone. EX: GMT -0200 = 120 minutos
    d.setMinutes(dt.getTimezoneOffset());

    return d.getFullYear() != 1 ? d.format("dd/mm/yyyy") : "";
}

function FormatTimeSlider(hr) {

    hr = Math.round(hr).toString();

    var res = "";
    var Hour;
    var Minute;

    if (hr.length == 4) {
        Hour = hr.substr(0, 2);
        Minute = hr.substr(2, 2);
    }
    else if (hr.length == 3) {
        Hour = hr.substr(0, 1);
        Minute = hr.substr(1, 2);
    }
    else if (hr.length == 2) {
        Hour = 0;
        Minute = hr;
    }

    if (Hour > 24)
        Hour = 24;

    if (Minute > 59)
        Minute = 59;

    if (isNaN(Hour))
        Hour = 0;

    if (isNaN(Minute))
        Minute = 0;

    return Hour + ":" + Minute;
}
function VerifyPointsValue(p) {
    var a = new String(p).split('.');
    if (a.length > 1)
        return false;
    else
        return true;
}
function FormatPriceSlider(p) {
    return CurrencyPrefixed ? CurrentCurrencyFormat + p.FormatCurrency() : p;
}

function convertSerializableDate(d) {
    var returnDate = new Date();
    if (typeof d == "string") {
        d = d.replace("/Date(", "").replace(")/", "");
        returnDate = new Date(parseFloat(d));
    }
    return returnDate;
}

//Formatação de Data
function FormatDate(dt) {
    if (dt != undefined) {
        if (typeof dt == "object" && dt.Year)
            dt = new Date(dt.Year, dt.Month, dt.Day);
        if ((typeof dt == "Date") || (typeof dt == "object"))
            if (dt.getFullYear() != 1)
                return dt.format("dd/mm/yyyy");
    }

    return "";
}

function FormatDateValue(dt) {
    var retorno = "";
    if (dt != undefined && dt != "") {
        var data = new Date(dt);
        retorno = data.format("dd/mm/yyyy");
    }

    return retorno;
}

function FormatDateWeek(dt) {
    return DaysOfWeek[dt.DayOfWeek] + ", " + FormatSimpleDateValues(dt);
}

function FormatDateWeek2(dt) {
    return FormatSimpleDateValues(dt) + " (" + DaysOfWeek[dt.DayOfWeek] + ")";
}

function DateDif(initial, end) {
    return ((end - initial) / (24 * 60 * 60 * 1000)).toFixed(0);
}

function NumberOfDays(month, year) {

    return 32 - new Date(year, month - 1, 32).getDate();

    //    if ((month < 8 && year % 2 == 1) || (month > 7 && month % 2 == 0)) return 31;
    //    if (month != 2) return 30;
    //    if (year % 4 == 0) return 29;
    //    return 28;
}

function SumDays(date, days) {
    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear();

    days = days + day;

    while (days > NumberOfDays(month, year)) {
        days = days - NumberOfDays(month, year);
        month++;

        if (month > 12) {
            month = 1;
            year++;
        }
    }

    return (new Date(year, (month - 1), days));
}

var DaysOfWeek = { "0": "dom", "1": "seg", "2": "ter", "3": "qua", "4": "qui", "5": "sex", "6": "sab" };

var Months = { "1": "Janeiro", "2": "Fevereiro", "3": "Março", "4": "Abril", "5": "Maio", "6": "Junho", "7": "Julho", "8": "Agosto", "9": "Setembro", "10": "Outubro", "11": "Novembro", "12": "Dezembro" };

function FormatDateWeekMonth(dt) {
    return DaysOfWeek[dt.DayOfWeek] + ", " + dt.Day + " " + Months[dt.Month] + " " + dt.Year;
}

function formatMinutesInHourMinute(minutes) {
    var resto = minutes % 60;
    var horas = (minutes - resto) / 60;
    var horasString;
    var minutesString;

    horasString = horas.toString();
    minutesString = Math.round(resto).toString();

    if (horas < 10)
        horasString = "0" + horasString;

    if (resto < 10)
        minutesString = "0" + minutesString;


    return horasString + ":" + minutesString;
}

function formatMinutesInHourMinuteLong(minutes) {
    var rest = minutes % 60;
    var hours = (minutes - rest) / 60;
    var horasString;
    var minutesString;
    var returnString;

    hoursString = hours.toString();
    minutesString = rest.toString();

    return (hours > 0 ? hoursString + (hours > 1 ? " horas " : " hora ") : "") + (rest > 0 ? minutesString + (rest > 1 ? " minutos" : " minuto") : "")
}


//Formatação de Hora
function FormatHour(hr) {

    var res = "";

    var hour = hr.Hour;

    if (hour < 10)
        res = "0";

    res += hour;

    res += ":";
    if (hr.Minutes < 10)
        res += "0";

    res += hr.Minutes;

    return res;
}


function Clone_Object(obj) {

    if (typeof obj !== 'object' || obj == null) {
        return obj;
    }

    var c = obj instanceof Array ? [] : {};

    for (var i in obj) {
        var prop = obj[i];

        if (typeof prop == 'object') {
            if (prop instanceof Array) {
                c[i] = [];

                for (var j = 0; j < prop.length; j++) {
                    if (typeof prop[j] != 'object') {
                        c[i].push(prop[j]);
                    } else {
                        c[i].push(Clone_Object(prop[j]));
                    }
                }
            } else if (prop instanceof Date) {
                c[i] = new Date(prop.getTime());
            } else {
                c[i] = Clone_Object(prop);
            }
        } else {
            c[i] = prop;
        }
    }

    return c;
}

function toggleAnimateDIV(sender, IdDIV) {
    var ctrl = $(IdDIV);
    ctrl.is(":hidden") ? ctrl.slideDown("fast") : ctrl.slideUp("fast");
}

function CalculeFlightDuration(min) {
    var res = "";
    var hs = "";

    if (min > 60) {
        hs = parseInt(min / 60);
        min = min % 60;

        res += hs + (hs > 1 ? " hs " : " h ");

        res += (min > 9 ? "" : "0") + min + " min";
    }
    else {
        res = min + " min";
    }

    return res;
}

function ltrim(str) {
    l = new Number(str.length);
    if (l > 0) {
        while (str.charAt(0) == " " || str.charAt(0) == "\t")
            str = str.substr(1, l - 1);
    }
    return str;
}

function rtrim(str) {
    l = new Number(str.length);
    if (l > 0) {
        while (str.charAt(l - 1) == " " || str.charAt(l - 1) == "\t") {
            str = str.substr(0, l - 1);
            l = str.length;
        }
    }
    return str;
}

function lmpStr(strVal, StrCar) {

    strResult = '';
    for (iCont = 0; iCont < strVal.length; iCont++) {
        if (strVal.charAt(iCont) != StrCar) {
            strResult += strVal.charAt(iCont);
        }
    }
    return strResult;
}

function trim(str) {
    return (str == undefined || str == null) ? "" : ltrim(rtrim(str));
}

function soNumero(event) {
    var iKey = KeyStroke(event);
    return ((iKey > 47 && iKey < 58) || iKey == 0 || iKey == 8 || iKey == 13);
}

function soCaracter(event) {
    var iKey = KeyStroke(event);
    return ((iKey >= 97 && iKey <= 122) || (iKey >= 65 && iKey <= 90) || iKey == 0 || iKey == 8 || iKey == 13 || iKey == 32 || iKey == 199 || iKey == 89 || iKey == 231);
}

function soNumSinal(iKeyPerm, event) {
    var iKey = KeyStroke(event);
    return ((iKey > 47 && iKey < 58) || (iKey == 0 || iKey == 8 || iKey == 13 || iKey == 44 || iKey == iKeyPerm));
}

function soNumSinalsemVirgula(iKeyPerm, event) {
    var iKey = KeyStroke(event);
    return ((iKey > 47 && iKey < 58) || (iKey == 0 || iKey == 8 || iKey == 13 || iKey == iKeyPerm));
}

function soNaoSinal(iKeyPerm, event) {
    return !(KeyStroke(event) == iKeyPerm);
}

function KeyStroke(event) {
    var ikey = 0;
    if (event.which == undefined) {
        ikey = window.event.keyCode;
    }
    else {
        ikey = event.which;
    }
    return ikey;
}

function KeyIns(event, iKey) {
    if (event.which == undefined) {
        window.event.keyCode = iKey;
    }
    else {
        event.keyCode = iKey;
    }
}

function Formata(campo, tammax, teclapres, decimal) {
    var tecla = teclapres.keyCode;
    vr = Limpar(campo.value, "0123456789");
    tam = vr.length;
    dec = decimal

    if (tam < tammax && tecla != 8) { tam = vr.length + 1; }

    if (tecla == 8)
    { tam = tam - 1; }

    if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105) {
        if (tam <= dec)
        { campo.value = vr; }

        if ((tam > dec) && (tam <= 5)) {
            campo.value = vr.substr(0, tam - 2) + "," + vr.substr(tam - dec, tam);
        }
        if ((tam >= 6) && (tam <= 8)) {
            campo.value = vr.substr(0, tam - 5) + "." + vr.substr(tam - 5, 3) + "," + vr.substr(tam - dec, tam);
        }
        if ((tam >= 9) && (tam <= 11)) {
            campo.value = vr.substr(0, tam - 8) + "." + vr.substr(tam - 8, 3) + "." + vr.substr(tam - 5, 3) + "," + vr.substr(tam - dec, tam);
        }
        if ((tam >= 12) && (tam <= 14)) {
            campo.value = vr.substr(0, tam - 11) + "." + vr.substr(tam - 11, 3) + "." + vr.substr(tam - 8, 3) + "." + vr.substr(tam - 5, 3) + "," + vr.substr(tam - dec, tam);
        }
        if ((tam >= 15) && (tam <= 17)) {
            campo.value = vr.substr(0, tam - 14) + "." + vr.substr(tam - 14, 3) + "." + vr.substr(tam - 11, 3) + "." + vr.substr(tam - 8, 3) + "." + vr.substr(tam - 5, 3) + "," + vr.substr(tam - 2, tam);
        }
    }
}

function adjustDate(ObjText) {
    valor = '';
    valor = trim(ObjText.value);
    valor = lmpStr(valor, '/');
    iDia = 0;
    iMes = 0;
    iAno = 0;
    mask = '';
    var today = new Date();
    var today_year = today.getFullYear();
    var today_mes = today.getMonth();
    var today_dia = today.getDay();

    if (trim(valor).length != 0) {
        if (valor.length >= 1) {
            iDia = parseFloat(valor.substring(0, 2));
            if (iDia < 01) { iDia = 01 }
            if (iDia > 31) { iDia = 31 }
        }
        else {
            iDia = today_dia;
        }
        if (valor.length >= 3) {
            iMes = parseFloat(valor.substring(2, 4));
            if (iMes < 01) { iMes = 01 }
            if (iMes > 12) { iMes = 12 }

        }
        else {
            iMes = today_mes + 1;
        }
        if (valor.length > 4) {
            iAno = parseFloat(valor.substring(4, 8));
            if (iAno < 100) { iAno = iAno + 2000 }
        }
        else {
            iAno = today_year;
        }

        if (iAno < 1500 || iAno > 2500)
            iAno = today_year;

        ObjText.value = '';

        //
        //Validacao de dias por mes
        //
        if (iMes == 4 && iDia > 30) { iDia = 30 }
        if (iMes == 6 && iDia > 30) { iDia = 30 }
        if (iMes == 9 && iDia > 30) { iDia = 30 }
        if (iMes == 11 && iDia > 30) { iDia = 30 }
        if (iMes == 2 && iDia > 29) { iDia = 29 }

        //
        //Bissexto
        //
        if (iMes == 2 && iDia >= 28) {
            iBiSexto = iAno / 4;
            iDia = iBiSexto.toString().length == 3 ? 29 : 28;
        }

        //
        //Dia
        //
        var iDiaToString = iDia.toString();
        ObjText.value += (iDiaToString.length < 2 ? '0' : '') + iDiaToString + '/';

        //
        //Mes e Ano
        //
        var iMesToString = iMes.toString();
        ObjText.value += (iMesToString.length < 2 ? '0' : '') + iMesToString + '/' + iAno.toString();
    }
}

function MascData(ObjText, event) {
    valor = '';
    valor = trim(ObjText.value);
    valor = lmpStr(valor, '/');
    iKey = KeyStroke(event);
    strDia = '';
    strMes = '';

    if (valor.length > 0 && ((iKey >= 48 && iKey <= 57) || (iKey >= 96 && iKey <= 105))) {
        mask = '';
        if (valor.length > 0 && valor.length <= 2) {
            mask = valor;
            if (valor.length == 2) {
                if (parseFloat(valor.substring(0, 2)) > 31) {
                    mask = '31';
                }
            }
        }
        if (valor.length > 2 && valor.length <= 4) {
            if (parseFloat(valor.substring(0, 2)) > 31)
            { strDia = '31' }

            else
            { strDia = valor.substring(0, 2) }

            if (valor.length == 4) {
                var valorSubString = valor.substring(2, 4);
                if (parseFloat(valorSubString) > 12) {
                    strMes = '12'
                }
                else {
                    strMes = valorSubString
                }
            }
            else {
                strMes = valor.substring(2, 4);
            }
            mask = mask + strDia + '/' + strMes;
        }
        if (valor.length > 4) {
            if (parseFloat(valor.substring(0, 2)) > 31)
            { strDia = '31' }

            else
            { strDia = valor.substring(0, 2) }

            if (valor.length > 4) {
                if (parseFloat(valor.substring(2, 4)) > 12)
                { strMes = '12' }

                else
                { strMes = valor.substring(2, 4) }
            }
            else {
                strMes = valor.substring(2, 4);
            }
            mask = mask + strDia + '/' + strMes + '/' + valor.substring(4, 8);
        }
        ObjText.value = mask;
    }
}

function vdHora(ObjText) {
    valor = '';
    valor = trim(ObjText.value);
    valor = lmpStr(valor, ':');
    iHora = 0;
    iMinuto = 0;
    mask = '';
    var today = new Date();
    var today_Hora = today.getHours();
    var today_Minuto = today.getMinutes();

    if (trim(valor).length != 0) {
        if (valor.length >= 1) {
            iHora = parseFloat(valor.substring(0, 2));
            if (iHora < 00) { iHora = 00 }
            if (iHora > 23) { iHora = 23 }
        }
        else {
            iHora = today_Hora;
        }
        if (valor.length >= 3) {
            iMinuto = parseFloat(valor.substring(2, 4));
            if (iMinuto < 00) { iMinuto = 00 }
            if (iMinuto > 59) { iMinuto = 59 }

        }
        else {
            iMinuto = today_Minuto;
        }

        ObjText.value = '';

        var iHoraToString = iHora.toString();
        ObjText.value += (iHoraToString.length < 2 ? "0" : "") + iHoraToString;

        ObjText.value += ":";

        var iMinutoToString = iMinuto.toString();
        ObjText.value += (iMinutoToString.length < 2 ? "0" : "") + iMinutoToString;
    }
}

function MascHora(ObjText, event) {
    valor = '';
    valor = trim(ObjText.value);
    valor = lmpStr(valor, ':');
    iKey = KeyStroke(event);
    strHora = '';
    strMinuto = '';

    if (valor.length > 0 && ((iKey >= 48 && iKey <= 57) || (iKey >= 96 && iKey <= 105))) {
        mask = '';
        if (valor.length > 0 && valor.length <= 2) {
            mask = valor;
            if (valor.length == 2) {
                if (parseFloat(valor.substring(0, 2)) > 23) {
                    mask = '23';
                }
            }
        }

        if (valor.length > 2 && valor.length <= 4) {
            if (parseFloat(valor.substring(0, 2)) > 23)
            { strHora = '23' }

            else
            { strHora = valor.substring(0, 2) }

            if (valor.length == 4) {
                if (parseFloat(valor.substring(2, 4)) > 59)
                { strMinuto = '59' }

                else
                { strMinuto = valor.substring(2, 4) }
            }
            else {
                strMinuto = valor.substring(2, 4);
            }
            mask = mask + strHora + ':' + strMinuto;
        }

        ObjText.value = mask;
    }
}
function MascaraCPF_CNPJ(inputCPF_CNPJ, event) {
    if (inputCPF_CNPJ.value.length > 14)
        return fnMascaraCNPJ(inputCPF_CNPJ, event);
    else
        return fnMascaraCPF(inputCPF_CNPJ, event);
}

function fnlmpCNPJ(strCNPJ) {
    strResult = '';
    for (iCont = 0; iCont < strCNPJ.length; iCont++) {
        if (strCNPJ.charAt(iCont) != '.' && strCNPJ.charAt(iCont) != '-' && strCNPJ.charAt(iCont) != '/') {
            strResult += strCNPJ.charAt(iCont);
        }
    }
    return strResult;
}

function fnMascaraCNPJ(sCNPJ, event) {
    valor = '';
    valor = trim(fnlmpCNPJ(sCNPJ.value));
    Key = KeyStroke(event);
    if (valor.length > 0 && ((Key >= 48 && Key <= 57) || (Key >= 96 && Key <= 105))) {
        mask = '';
        if (valor.length > 0) {
            mask = valor;
            if (valor.length >= 2)
                mask = valor.substring(0, 2) + '.' + valor.substring(2, 5);
            if (valor.length >= 5)
                mask = valor.substring(0, 2) + '.' + valor.substring(2, 5) + '.' + valor.substring(5, 8);
            if (valor.length >= 8)
                mask = valor.substring(0, 2) + '.' + valor.substring(2, 5) + '.' + valor.substring(5, 8) + '/' + valor.substring(8, 12);
            if (valor.length >= 12)
                mask = valor.substring(0, 2) + '.' + valor.substring(2, 5) + '.' + valor.substring(5, 8) + '/' + valor.substring(8, 12) + '-' + valor.substring(12, 14);
        }
        sCNPJ.value = mask;
    }
}

function MascaraCEP(sender, event) {
    valor = sender.value;
    valor = valor.replace("-", "");

    Key = KeyStroke(event);

    if (valor.length > 0 && ((Key >= 48 && Key <= 57) || (Key >= 96 && Key <= 105))) {
        mask = '';
        if (valor.length > 0) {
            mask = valor;
            if (valor.length >= 5)
                mask = valor.substring(0, 5) + '-' + valor.substr(5, 3);
        }
        sender.value = mask;
    }
}

function fnMascaraCPF(sCPF, event) {
    valor = '';
    valor = trim(fnlmpCPF(sCPF.value));
    Key = KeyStroke(event);
    if (valor.length > 0 && ((Key >= 48 && Key <= 57) || (Key >= 96 && Key <= 105))) {
        mask = '';
        if (valor.length > 0) {
            mask = valor;
            if (valor.length >= 3)
                mask = valor.substring(0, 3) + '.' + valor.substring(3, 6);
            if (valor.length >= 6)
                mask = valor.substring(0, 3) + '.' + valor.substring(3, 6) + '.' + valor.substring(6, 9);
            if (valor.length >= 9)
                mask = valor.substring(0, 3) + '.' + valor.substring(3, 6) + '.' + valor.substring(6, 9) + '-' + valor.substring(9, 11);
        }
        sCPF.value = mask;
    }
}

function fnlmpCPF(strCPF) {
    strResult = '';
    for (iCont = 0; iCont < strCPF.length; iCont++) {
        if (strCPF.charAt(iCont) != '.' && strCPF.charAt(iCont) != '-') {
            strResult += strCPF.charAt(iCont);
        }
    }
    return strResult;
}

function fnMascaraCEP(sCEP, event) {
    valor = '';
    valor = trim(fnlmpCEP(sCEP.value));
    Key = KeyStroke(event);
    if (valor.length > 0 && ((Key >= 48 && Key <= 57) || (Key >= 96 && Key <= 105))) {
        mask = '';
        if (valor.length > 0) {
            mask = valor;
            if (valor.length >= 5)
                mask = valor.substring(0, 5) + '-' + valor.substring(5, 8);
        }
        sCEP.value = mask;
    }
}

function fnlmpCEP(strCEP) {
    strResult = '';
    for (iCont = 0; iCont < strCEP.length; iCont++) {
        if (strCEP.charAt(iCont) != '-') {
            strResult += strCEP.charAt(iCont);
        }
    }
    return strResult;
}

function CurrencyFormatted(amount) {
    var i = parseFloat(amount);

    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    var str = new String(i);
    var indexOfDot = str.indexOf('.');
    if (indexOfDot < 0) { str += '.00'; }
    if (indexOfDot == (str.length - 2)) { str += '0'; }
    str = minus + str;
    return str.replace(".", ",");
}

function NumberFormatted(number) {
    return CurrencyFormatted(number);
}


Array.prototype.remove = function (from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

Number.prototype.FormatCurrency = function () {
    return CurrencyFormatted(this);
}

Number.prototype.FormatNumber = function () {
    return NumberFormatted(this);
}

this.CloseHintBoxy = function (sender) {
    var oDiv = (typeof sender == "string") ? window.document.getElementById(sender) : sender;

    var $oDiv = $(oDiv);

    if ($oDiv.attr("CreateHintBoxy") == true || oDiv.getAttribute("CreateHintBoxy") == true)
        window.document.body.removeChild(oDiv);
    else
        $oDiv.css("display", "none").css("visibility", "hidden").hide();

    var createHintBoxyFundo = window.document.getElementById("CreateHintBoxyDIVFundo");
    if (createHintBoxyFundo != null) {
        window.document.body.removeChild(createHintBoxyFundo);
    }
}

function ScrollToElement(elementIdToScroll) {
    if (elementIdToScroll == undefined)
        return;

    var theElement = elementIdToScroll;

    if (elementIdToScroll.type == undefined)
        theElement = $("#" + elementIdToScroll)[0];

    var selectedPosX = 0;
    var selectedPosY = 0;

    while (theElement != null) {
        selectedPosX += theElement.offsetLeft;
        selectedPosY += theElement.offsetTop;
        theElement = theElement.offsetParent;
    }

    window.scrollTo(selectedPosX, selectedPosY);
}

this.CreateHintBoxy = function (mensagem, sender, bolAutomaticClose, position, doNotCenter, toRight, toLeft) {
    var xPosition;
    var yPosition;
    var bolCenter = false;

    if (bolAutomaticClose == undefined)
        bolAutomaticClose = true;

    if (sender != undefined && $(sender).length > 0) {
        xPosition = $(sender).position().left;
        yPosition = $(sender).position().top;
        width = $(sender).outerWidth(true);
        height = $(sender).outerHeight(true);
        if (toRight)
            xPosition += width;

        //yPosition += height;
    }
    else {

        if (self.innerHeight) {
            xPosition = self.innerWidth;
            yPosition = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) {
            xPosition = document.documentElement.clientWidth;
            yPosition = document.documentElement.clientHeight;
        } else if (document.body) {
            xPosition = document.body.clientWidth;
            yPosition = document.body.clientHeight;
        }

        yPosition = yPosition <= 5 ? YMousePosition : yPosition / 2;

        xPosition = xPosition / 2;
    }

    if (position == undefined) position = "fixed";

    //FUNDO
    var oDivFundo = window.document.createElement("div");
    oDivFundo.id = "CreateHintBoxyDIVFundo";
    oDivFundo.style.filter = "Alpha(Opacity=40)";

    if (StyleDivFunfo == 1) {
        oDivFundo.style.opacity = "0.7";
        oDivFundo.style.backgroundColor = "#222";
    }
    else {
        oDivFundo.style.opacity = "0.4";
        oDivFundo.style.backgroundColor = "#CCC";
    }

    if (window.scrollMaxY == 0)
        oDivFundo.style.height = "100%";
    else
        oDivFundo.style.height = $(document).height() + 100 + "px";

    oDivFundo.style.width = "100%";
    oDivFundo.style.position = isOLD_Navigator() ? "absolute" : "fixed";
    oDivFundo.style.zIndex = "500";
    oDivFundo.style.top = "0px";
    oDivFundo.style.left = "0px";

    if ($("#CreateHintBoxyDIVFundo").length == 0)
        window.document.body.appendChild(oDivFundo);

    if (typeof mensagem == "string") {

        var oDiv = window.document.createElement("div");

        if (bolAutomaticClose) {
            oDiv.style.cursor = "pointer";
            oDiv.onclick = function () { CloseHintBoxy(this); };
            //oDiv.setAttribute("onClick", "CloseHintBoxy(this);"); Nao funciona no IE7
        }

        oDiv.style.backgroundColor = "#FFF";
        oDiv.style.position = position;

        oDiv.innerHTML = mensagem;

        $(oDiv).attr("CreateHintBoxy", true);

        bolCenter = true;
    }
    else {
        oDiv = mensagem;
    }

    if (oDiv.jquery == undefined) {

        oDiv.style.display = "none";
        oDiv.style.visibility = "visible";
        window.document.body.appendChild(oDiv);

        //PRECISA SER DEPOIS DO APPEND PARA DESCOBRIR O TAMANHO DO ELEMENTO CRIADO
        var $oDiv = $(oDiv);
        if (bolCenter) {
            xPosition -= ($oDiv.width() / 2);
            yPosition -= ($oDiv.height() / 2);

            if (yPosition < 0)
                yPosition = yPosition * -1;
        }

        if (($.browser.msie) && (parseInt($.browser.version, 10) < 8)) {
            oDiv.style.left = "550px";
            oDiv.style.top = "200px";
            oDiv.style.right = "620px";
        }
        else {
            if (toLeft)
                xPosition -= $oDiv.width();
            oDiv.style.left = xPosition + "px";
            oDiv.style.top = yPosition + "px";
        }

        oDiv.style.zIndex = "1000";
        oDiv.style.position = position;
        $oDiv.fadeIn(200);

    }
    else {

        oDiv[0].style.display = "none";
        oDiv[0].style.visibility = "visible";
        window.document.body.appendChild(oDiv[0]);

        var $oDiv = $(oDiv);
        if (!doNotCenter) {
            xPosition -= ($oDiv.width() / 2);
            yPosition -= ($oDiv.height() / 2);

            if (yPosition < 0)
                yPosition = yPosition * -1;
        }

        if (toLeft)
            xPosition -= $oDiv.width();

        if (oDiv[0] != undefined) {
            oDiv[0].style.left = xPosition + "px";
            oDiv[0].style.top = yPosition + "px";
            oDiv[0].style.position = position;
            oDiv[0].style.zIndex = "1000";
            oDiv.fadeIn(200);
        }
    }
}

function GetIATA(Type) {
    var IATA = "";
    var Type = trim(Type);

    if (Type.indexOf('--') > 0)
        IATA = Type.substr(Type.indexOf('--') + 2, 3);
    else if (Type.indexOf('(') > 0)
        IATA = Type.substr(Type.indexOf('(') + 1, 3);
    else if (Type.length == 3)
        IATA = Type;

    return IATA.toUpperCase();
}

function GetIATAFromURI(Key) {

    IATA = "";
    URI = "";
    arrURI = undefined;

    URI = decodeURIComponent(window.location.search);
    arrURI = URI.split('&');

    if (arrURI != null && arrURI != undefined) {
        for (var i = 0; i < arrURI.length; i++) {
            Element = arrURI[i].split('=');
            if (Element[0] == Key) {
                if (Element[1].indexOf('--') > 0)
                    IATA = Element[1].substr(Element[1].indexOf('--') + 2, 3);
                else
                    IATA = Element[1].substr(Element[1].indexOf('(') + 1, 3);

                break;
            }
        }
    }
    return IATA;
}

function QueryString(Key, Index) {
    if (!Index) Index = 0;

    var Element = "";
    var arrURI = window.location.search.substring(1).split("&");

    Key = Key.toLowerCase();

    for (var i = 0, leng = arrURI.length; i < leng; i++) {
        Element = arrURI[i].split("=");
        if (Element[0].toLowerCase() == Key) {
            if (Index == 0)
                return Element[1];
            else
                Index--;
        }
    }
}

function checkDate(dia, mes, ano) {
    var dateRegExp = /^(19|20)\d\d-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$/;
    if (!dateRegExp.test(ano + "-" + mes + "-" + dia)) return false; // formato invÃƒÂ¡lido
    if (dia == 31 && (/^0?[469]$/.test(mes) || mes == 11)) {
        return false; // dia 31 de um mes de 30 dias
    } else if (dia >= 30 && mes == 2) {
        return false; // mais de 29 dias em fevereiro
    } else if (mes == 2 && dia == 29 && !(ano % 4 == 0 && (ano % 100 != 0 || ano % 400 == 0))) {
        return false; // dia 29 de fevereiro de um ano nÃ£o bissexto
    } else {
        return true; // Data vÃ¡lida
    }
}

function checkTime(h, m, s) {
    if (!s) s = '00';
    var horarioRegExp = /^(0?\d|1\d|2[0-3]):[0-5]?\d:[0-5]?\d$/;
    return horarioRegExp.test(h + ":" + m + ":" + s);
}

function isValidDate(data, formato) {
    if (!formato) {

        var mes = 2;
        var dia = 1;
        var ano = 3;
    }
    else {
        // SerÃ¡ usado o formato passado no segundo argumento
        formato = formato.toLowerCase().replace(/[^dmy]/g, '');
        var dia = formato.indexOf('d') + 1;
        var mes = formato.indexOf('m') + 1;
        var ano = formato.indexOf('y') + 1;
    }


    var matches = data.match(/^\b(\d+)\D(\d+)\D(\d+)\b\b(?:\s+(\d{1,2})\D(\d{2})\D*((\d{2})?))?\b$/);

    if (!matches)
        return false;

    matches.clearUndefined();

    matches.clearStringEmpty();

    // validando a data 
    if (!checkDate(matches[dia], matches[mes], matches[ano])) {
        return false;
    }
    else if (matches.length >= 5) {
        return checkTime(matches[4], matches[5], (matches[6] ? matches[6] : false));
    }
    else {
        return true;
    }

}

function setDateRegionalString(DateString) {
    var oDate;
    if (DateString && DateString.indexOf("/") >= 0) {
        var dateStringSplit = DateString.split("/");
        if (dateStringSplit.length == 3) {
            var Day = dateStringSplit[0];
            var Month = dateStringSplit[1] - 1;
            var Year = dateStringSplit[2];

            //para o dia new Date(1975, 9, 19) há um bug, ele volta para o dia new Date(1975, 9, 18) por isso tem de ficar igual abaixo:
            oDate = new Date();
            oDate.setFullYear(Year, Month, Day);
        }
    }
    return oDate;
}

function isEmail(Email) {
    if (Email != null && Email != undefined)
        Email = Email.replaceAll(" ", "");

    var emailDetector = new RegExp(/^[\d\w_.-]+@([\d\w_-]+\.){1,}[\w\d]+$/);
    return emailDetector.test(Email);
}

function VerificaCodigoSeguranca(codSeg, type) {
    var retorno = true;

    if (type == 'VI') { retorno = codSeg.length <= 3 }
    if (type == 'MC') { retorno = codSeg.length <= 3 }
    if (type == 'MS') { retorno = codSeg.length <= 3 }
    if (type == 'AX') { retorno = codSeg.length == 4 }
    if (type == 'DI') { retorno = codSeg.length <= 3 }
    if (type == 'AU') { retorno = codSeg.length == 0 }
    if (type == 'GE') { retorno = codSeg.length <= 3 }

    return retorno;
}

function ValidaCartaoCredito(inNumber, type) {

    var total = 0;
    var tmp = 0;
    var number = "";

    // Verificacao de numeros na string inNumber
    for (i = 0, len = inNumber.length; i < len; i++) {
        var inNumberCharAt = inNumber.charAt(i);
        if (inNumberCharAt >= "0" && inNumberCharAt <= "9")
            number += inNumberCharAt;
        else
            return false
    }

    // Se numero for curto demais para qualquer tipo
    if (number.length < 13)
        return false;

    first = "" + number.charAt(0);
    second = "" + number.charAt(1);
    third = "" + number.charAt(2);
    firstTwo = first + second;
    firstFour = firstTwo + third + number.charAt(3);

    // MASTERCARD
    if (type == "MC") {//"Credicard/MasterCard"
        if (first != "5" || second < "1" || second > "5")
            return false;
        if (number.length != 16)
            return false;
    }

    // MASTERCARD Submarino
    if (type == "MS") {//"MasterCard Submarino"
        if (number.substring(0, 4).indexOf("5324") == -1)
            return false;
        if (number.length != 16)
            return false;
    }

    //AURA
    else if (type == "AU" || type == "submarino") {
        if (checkCCAura(number) != 0 || number.substring(6, 8).indexOf("18") == -1 || number.substring(0, 6).indexOf("507860") == -1)
            return false;
    }

    // Hipercard
    else if (type == "GE") {
        if (number.length == 19) {
            if ((number.substring(0, 6) != "384100") ||
                ((number.substr(6, 1) != '1') &&
                (number.substr(6, 1) != '4') &&
                (number.substr(6, 1) != '6'))) {
                return false;
            }
            else {
                return true;
            }
        }
        else if (number.length == 16) {
            if (number.substring(0, 6) == "606282")
                return true;
            else
                return false;
        }
        else {
            return false;
        }
    }

    // VISA
    else if (type == "VI") { //"Visa"
        if (first != "4")
            return false;
        if (number.length != 13 && number.length != 16)
            return false;
    }
    // AMERICAN EXPRESS
    else if (type == "AX") { //"American Express"
        if (first != "3" || (second != "4" && second != "7"))
            return false;
        if (number.length != 15)
            return false;
    }
    // DINERS
    else if (type == "DI") { //"Diners"
        if (firstTwo != "36" && firstTwo != "38" && (firstTwo != "30" || (third < "0" || third > "5")))
            return false;
        if (number.length != 14)
            return false;
    }
    // JCB CARDS
    else if (type == "JCB Cards") {
        if (firstFour != "2131" && firstFour != "1800" && (first != "3"))
            return false;
        if (number.length != 16 && first == "3")
            return false;
        if (number.length != 15 && first != "3")
            return false;
    }

    // Fazendo o check sum
    for (loc = number.length - 2; loc >= 0; loc -= 2) {
        total += 1 * number.charAt(loc + 1);
        tmp = number.charAt(loc) * 2;
        if (tmp > 9)
            total += 1;
        total += tmp % 10;
    }
    if (number.length % 2 > 0)
        total += 1 * number.charAt(0);

    return (total % 10 == 0);
}

function checkCCAura(ccnumber) {
    var re;
    re = / /gi;

    ccnumber = ccnumber.replace(re, '');

    if (ccnumber.charAt(0) == '0')
        ccnumber = ccnumber.substr(1, ccnumber.length);

    ccprefix = '507860';

    prefixvalid = false;
    lengthvalid = false;

    if (ccnumber.indexOf(ccprefix) == 0)
        prefixvalid = true;

    if (ccnumber.length == 19)
        lengthvalid = true;

    var result = 0;
    if (!prefixvalid)
        result += 1;

    if (!lengthvalid)
        result += 2;

    qsum = 0;

    for (var x = 0; x < ccnumber.length; x++) {
        ch = ccnumber.substr(ccnumber.length - x - 1, 1);
        if (x % 2 != 0) {
            sum = 2 * parseFloat(ch, 10);
            qsum += (sum % 10);
            if (sum > 9)
                qsum += 1;
        }
        else
            qsum += parseFloat(ch, 10);
    }

    if (qsum % 10 != 0)
        result += 4;

    return result;
}

function validCPF_CNPJ(theCPF) {

    theCPF = trim(fnlmpCNPJ(theCPF));

    theCPF = theCPF.replace(/[^0-9]/g, '');

    if (theCPF == "") {
        return (false);
    }
    if (((theCPF.length == 11) && (theCPF == 11111111111) || (theCPF == 22222222222) || (theCPF == 33333333333) || (theCPF == 44444444444) || (theCPF == 55555555555) || (theCPF == 66666666666) || (theCPF == 77777777777) || (theCPF == 88888888888) || (theCPF == 99999999999) || (theCPF == 00000000000))) {
        return (false);
    }


    if (!((theCPF.length == 11) || (theCPF.length == 14))) {
        return (false);
    }

    var checkOK = "0123456789";
    var checkStr = theCPF;
    var allValid = true;
    var allNum = "";
    for (i = 0; i < checkStr.length; i++) {
        ch = checkStr.charAt(i);
        for (j = 0; j < checkOK.length; j++)
            if (ch == checkOK.charAt(j))
                break;
        if (j == checkOK.length) {
            allValid = false;
            break;
        }
        allNum += ch;
    }

    if (!allValid) {
        return (false);
    }

    var chkVal = allNum;
    var prsVal = parseFloat(allNum);
    if (chkVal != "" && !(prsVal > "0")) {
        return (false);
    }

    if (theCPF.length == 11) {
        var tot = 0;

        for (i = 2; i <= 10; i++)
            tot += i * parseFloat(checkStr.charAt(10 - i));

        if ((tot * 10 % 11 % 10) != parseFloat(checkStr.charAt(9))) {
            return (false);
        }

        tot = 0;

        for (i = 2; i <= 11; i++)
            tot += i * parseFloat(checkStr.charAt(11 - i));

        if ((tot * 10 % 11 % 10) != parseFloat(checkStr.charAt(10))) {
            return (false);
        }
    }
    else {
        var tot = 0;
        var peso = 2;

        for (i = 0; i <= 11; i++) {
            tot += peso * parseFloat(checkStr.charAt(11 - i));
            peso++;
            if (peso == 10) {
                peso = 2;
            }
        }

        if ((tot * 10 % 11 % 10) != parseFloat(checkStr.charAt(12))) {
            return (false);
        }

        tot = 0;
        peso = 2;

        for (i = 0; i <= 12; i++) {
            tot += peso * parseFloat(checkStr.charAt(12 - i));
            peso++;
            if (peso == 10) {
                peso = 2;
            }
        }

        if ((tot * 10 % 11 % 10) != parseFloat(checkStr.charAt(13))) {
            return (false);
        }
    }
    return (true);
}

function RetiraAcentos(word) {
    var Acentos = "áàãââÁÀÃÂéêÉÊíÍóõôÓÔÕúüÚÜçÇabcdefghijklmnopqrstuvxwyz";
    var Traducao = "aaaaaAAAAeeEEiIoooOOOuuUUcCABCDEFGHIJKLMNOPQRSTUVXWYZ";
    var Posic, Carac;
    var TempLog = "";
    var value = word.toUpperCase();

    for (var i = 0, len = word.length; i < len; i++) {

        Carac = value.charAt(i);
        Posic = Acentos.indexOf(Carac);

        if (Posic > -1)
            TempLog += Traducao.charAt(Posic);
        else
            TempLog += Carac;
    }

    return TempLog;
}

function SearchTerm(word) {
    var j = 0;
    var res = [];

    word = word.toLowerCase();

    for (i = 0; i < cities.length; i++) {
        if (cities[i].toLowerCase().indexOf(word, 0) != -1) {
            res[j] = cities[i];
            j++;
        }
    }
    return res;
}

function SearchTermWithPost(request, response) {
    var term = SearchTerm(request.term.RemoveDiacritics());

    if (term.length > 1) {
        response(term);
    }
    else {
        $.ajax({
            type: "POST",
            url: "/Produtos/UserControls/asmx/PesqInc.asmx/RetornarLocalidade",
            data: "{'prefixText':'" + request.term + "','count':10,'contextKey':'PesquisarLocalidade=0;PesquisarCidade=1;PesquisarEstado=1;PesquisarPais=1;PesquisarContinente=0;PesquisarAeroporto=1;PesquisarIata=1;QuantidadeItensRetorno=20;MostrarLocalidade=0;MostrarCidadeEstado=1;MostrarPais=1;MostrarAeroportoIata=1;MostrarContinente=0'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                response(data);
            }
        });
    }
}

function isOLD_Navigator() {
    return (navigator.userAgent.indexOf("MSIE 6.") != -1) || (navigator.userAgent.indexOf("MSIE 5.") != -1) || (navigator.userAgent.indexOf("MSIE 4.") != -1);
}

function getBrazilianDateInternal(date) {

    var DayUTC = date.getUTCDate();
    var MonthUTC = date.getUTCMonth();
    var YearUTC = date.getUTCFullYear();
    var HourUTC = date.getUTCHours() - 3;
    var MinUTC = date.getUTCMinutes();
    var SecUTC = date.getUTCSeconds();
    var TMZ = date.getTimezoneOffset();

    //HourUTC = (HourUTC - ((180 - TMZ) / 60));

    var dateUTC = new Date(YearUTC, MonthUTC, DayUTC, HourUTC, MinUTC, SecUTC);
    dateUTC.setUTCHours(date.getUTCHours() - ((180 - TMZ) / 60));

    return dateUTC;
}

function addDayServerDate(DateObjet, DayAdd) {

    var iMes = parseFloat(DateObjet.Month);
    var iDia;

    iDia = 31;

    //
    //Validacao de dias por mes
    //
    if (iMes == 4 && iDia > 30) { iDia = 30 }
    if (iMes == 6 && iDia > 30) { iDia = 30 }
    if (iMes == 9 && iDia > 30) { iDia = 30 }
    if (iMes == 11 && iDia > 30) { iDia = 30 }
    if (iMes == 2 && iDia > 29) { iDia = 29 }

    //
    //Bisexto
    //
    if (iMes == 2 && iDia >= 28) {
        iBiSexto = iAno / 4;
        if (iBiSexto.toString().length == 3) {
            iDia = 29;
        }
        else {
            iDia = 28;
        }
    }

    DateObjet.Day = parseFloat(DateObjet.Day) + DayAdd;

    if (DateObjet.Day > iDia) {
        DateObjet.Month = parseFloat(DateObjet.Month) + 1;
        DateObjet.Day = 1;
    }
    else if (DateObjet.Day < 1) {
        DateObjet.Month = parseFloat(DateObjet.Month) - 1;

        if (DateObjet.Month > 0) {
            var iMes = parseFloat(DateObjet.Month);
            //
            //Validacao de dias por mes
            //
            if (iMes == 4 && iDia > 30) { iDia = 30 }
            if (iMes == 6 && iDia > 30) { iDia = 30 }
            if (iMes == 9 && iDia > 30) { iDia = 30 }
            if (iMes == 11 && iDia > 30) { iDia = 30 }
            if (iMes == 2 && iDia > 29) { iDia = 29 }

            //
            //Bisexto
            //
            if (iMes == 2 && iDia >= 28) {
                iBiSexto = iAno / 4;
                if (iBiSexto.toString().length == 3) {
                    iDia = 29;
                }
                else {
                    iDia = 28;
                }
            }

            DateObjet.Day = iDia;
        }
    }

    if (DateObjet.Month > 12) {
        DateObjet.Month = 1;
        DateObjet.Year = parseFloat(DateObjet.Year) + 1;
    }
    else if (DateObjet.Month < 1) {
        DateObjet.Day = 31;
        DateObjet.Month = 12;
        DateObjet.Year = parseFloat(DateObjet.Year) - 1;
    }


    return DateObjet;
}

function isValidPhoneType(Phone, Type) {
    if (Phone.length < 8) {
        return false;
    }
    else if (isNaN(Phone)) {
        return false;
    }
    else if (Type == "FIXO") {
        var prefix = Phone.substring(0, 1);
        prefix = parseInt(prefix);
        if (prefix > 5)
            return false
    }
    else if (Type == "MOVEL") {
        var prefix = Phone.substring(0, 1);
        prefix = parseInt(prefix);
        if (prefix < 6)
            return false

    }

    return true;
}

function EquipmentResolver(Type) {
    if (Type == 0)
        return "Avião";
    else if (Type == 1)
        return "Onibus";
    else if (Type == 2)
        return "Trem";
    else if (Type == 3)
        return "Carro";
    else if (Type == 4)
        return "Caminhão";
    else if (Type == 5)
        return "Barco";
    else if (Type == 6)
        return "Helicoptero";
    else
        return "Avião";
}

//
//ERROR
//
function ClientError() {
    this.Data;
    this.Namespace;
    this.ExplicitOriginalTarget;
    this.Message;
    this.Method;
    this.JSONData;
    this.UserBrowser = navigator.userAgent;
    this.PointOfSale;

    this.GetRequest = function () {

        if (CurrentPointOfSale != undefined)
            this.PointOfSale = CurrentPointOfSale;

        return {
            "Data": this.Data,
            "Namespace": this.Namespace,
            "ExplicitOriginalTarget": this.ExplicitOriginalTarget,
            "Message": this.Message,
            "Method": this.Method,
            "JSONData": this.JSONData,
            "UserBrowser": this.UserBrowser,
            "PointOfSale": this.PointOfSale
        };
    }

}

this.PublishStringClientError = function (stringClientError) {
    var clientError = new ClientError();

    if (typeof stringClientError == "string")
        clientError.Data = stringClientError;
    else {
        if (stringClientError.name == "InternalError")
            clientError.Data = stringClientError.message;
        else
            clientError.Data = stringClientError.message + " - " + stringClientError.stack;
    }
    //   if (view.progressHide)
    //      view.progressHide();
    //   else
    //       view.HideProgress();

    //   view.ShowMessage("Problemas de processamento", "ERRO");
    SendClientError(clientError);
}

this.SendClientError = function (clientError) {
    var req = clientError.GetRequest();
    var TimeOutServiceParameter = 18000000;
    var clientWS = new ServiceProxy(PathWebService);

    clientWS.invoke("Log", { req: req }, undefined, undefined, undefined, TimeOutServiceParameter);
}

function CheckMaxValueToField(FieldValue, MaxValue) {
    return (FieldValue <= MaxValue);
}

function ValidatePhoneNumber(phoneNumber, phType) {
    var reg = null;

    switch (phType) {
        case PhoneType.Comercial:
        case PhoneType.Residencial:
            reg = /^[0-5]/;
            break;

        case PhoneType.Celular:
            reg = /^[6-9]/;
            break;

        default:
            return false;
    }

    return reg.test(phoneNumber);
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode: function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode: function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

var Cookies =
{
    setCookie: function (c_name, value, expiredays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie = c_name + "=" + escape(value) +
                            ((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
    },

    getCookie: function (c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) c_end = document.cookie.length;

                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    },

    clearCookie: function (c_name) {
        this.setCookie(c_name, '', -10);
    },

    checkCookie: function (c_name) {
        cook = this.getCookie(c_name);
        return cook != null && cook != "";
    },

    ///<summary>
    /// Retorna um objeto que foi serializado no cookie
    ///</summary>
    getCookieObject: function (c_name) {
        strCook = this.getCookie(c_name);
        p_start = strCook.toUpperCase().indexOf('JSON=');
        p_end = strCook.indexOf(';', p_start);

        if (p_end == -1) p_end = strCook.length;

        var obj = strCook.substring((p_start + 5), p_end);

        return $.evalJSON(obj);
    }
}

function isCCInternational(CCNumber) {

    return false;

    if (BinCCInternacional != undefined)
        for (var i = 0, len = BinCCInternacional.length; i < len; i++) {
            var itemLen = BinCCInternacional[i].toString().length;
            if (CCNumber.length < itemLen)
                return false;
            else if (BinCCInternacional[i] == CCNumber.substring(0, itemLen))
                return true;
        }

    return false;
}

function CreateStarsTypes(NumberOfGoldTypes) {

    var stars = ["silver", "silver", "silver", "silver", "silver"];
    var i = 0;
    for (i; i < NumberOfGoldTypes; i++)
        stars[i] = "gold";

    if (NumberOfGoldTypes < i)
        stars[i - 1] = "half";

    return stars;
}

function SetLocationName(location) {
    var resp = location.FullName;

    if (location.RegionCode && location.RegionCode != "")
        resp += " / " + location.RegionCode;

    if (location.Country && location.Country != "")
        resp += ", " + location.Country;

    return resp;
}

function AdjustIATA(str) {
    return str.replaceAll("---", ")").replaceAll("--", "(");
}

function SetLocationNameWithIATA(location) {
    var resp = location.FullName;

    if (location.RegionCode && location.RegionCode != "")
        resp += " / " + location.RegionCode;

    if (location.Country && location.Country != "")
        resp += ", " + location.Country;

    if (location.IATA && trim(location.IATA) != "")
        resp += " (" + location.IATA + ")";

    return resp;
}

var Sources = {
    None: 0,
    Amadeus: 1,
    Sabre: 2,
    Tam: 3,
    Gol: 4,
    Team: 5,
    OceanAir: 6,
    WebJet: 7,
    Total: 8,
    Trip: 9,
    Passaredo: 10,
    AirMinas: 11,
    TAF: 12,
    Rico: 13,
    Sete: 14,
    NHT: 15,
    Pantanal: 16,
    AeroStar: 17,
    Azul: 18,
    Sol: 19,
    H2W: 20,
    Tourico: 21,
    Travel: 22,
    Trend: 23,
    HotelBeds: 25,
    "0": "None",
    "1": "Amadeus",
    "2": "Sabre",
    "3": "Tam",
    "4": "Gol",
    "5": "Team",
    "6": "OceanAir",
    "7": "WebJet",
    "8": "Total",
    "9": "Trip",
    "10": "Passaredo",
    "11": "AirMinas",
    "12": "TAF",
    "13": "Rico",
    "14": "Sete",
    "15": "NHT",
    "16": "Pantanal",
    "17": "AeroStar",
    "18": "Azul",
    "19": "Sol",
    "20": "H2W",
    "21": "Tourico",
    "22": "Travel",
    "23": "Trend",
    "25": "HotelBeds"
}

window.onerror = function (msg, url, linenumber) {

    var clientError = new ClientError();

    if (typeof msg == "string")
        clientError.Data = msg + " - " + linenumber + " - " + url;
    else
        clientError.Data = msg.message + " - " + msg.stack;

    SendClientError(clientError);
    return true;
};

String.prototype.startsWith = function (str) {
    return (this.match("^" + str) == str);
}

String.prototype.endsWith = function (str) {
    return (this.match(str + "$") == str);
}

String.prototype.isEmpty = function (str) {
    return this.length == 0;
}

Array.prototype.isEmpty = function () {
    return this.length == 0;
};

Array.prototype.join = function (separator) {

    var leng = this.length;
    var resp = "";

    if (leng > 0) {
        resp = this[0];
        for (var i = 1; i < leng; i++)
            resp += separator + this[i];
    }

    return resp;
};

Array.prototype.where = function (test) {
    var resp = [];

    for (var i = 0, len = this.length; i < len; i++)
        if (test(this[i]))
            resp.push(this[i]);

    return resp;
};

Array.prototype.select = function (selector) {
    var resp = [];

    for (var i = 0, len = this.length; i < len; i++)
        resp.push(selector(this[i]));

    return resp;
};

Array.prototype.first = function (test) {
    for (var i = 0, len = this.length; i < len; i++)
        if (test(this[i]))
            return this[i];

    return undefined;
};

Array.prototype.contains = function (func) {
    for (var i = 0, len = this.length; i < len; i++) {
        if (typeof func === "string") {
            if (this[i] == func)
                return true;
        }
        else
            if (func(this[i]))
                return true;
    }

    return false;
};

Array.prototype.distinct = function () {
    var elements = {};
    var resp = [];

    for (var i = 0, len = this.length; i < len; i++) {
        if (!elements[this[i]]) {
            elements[this[i]] = true;
            resp.push(this[i])
        }
    }

    return resp;
};

Array.prototype.forEach = function (exec) {
    for (var i = 0, len = this.length; i < len; i++)
        exec(this[i], i);
};

Array.prototype.count = function (test) {
    var count = 0;

    for (var i = 0, len = this.length; i < len; i++)
        if (test(this[i]))
            count++;

    return count;
}

String.prototype.RemoveDiacritics = function () {
    var Acentos = "áàãââÁÀÃÂéêÉÊíÍóõôÓÔÕúüÚÜçÇabcdefghijklmnopqrstuvxwyzABCDEFGHIJKLMNOPQRSTUVXWYZñòîÎìÌèÈ";
    var Traducao = "aaaaaAAAAeeEEiIoooOOOuuUUcCabcdefghijklmnopqrstuvxwyzABCDEFGHIJKLMNOPQRSTUVXWYZnoiIiIeE";
    var Posic, Carac;
    var TempLog = "";
    var value = this;

    for (var i = 0, len = this.length; i < len; i++) {

        Carac = value.charAt(i);
        Posic = Acentos.indexOf(Carac);

        TempLog += Posic > -1 ? Traducao.charAt(Posic) : Carac;
    }

    return TempLog;
}

Array.prototype.binarySearch = function binarySearch(find, comparator) {
    var low = 0, high = this.length - 1, i, comparison;
    var ret = -1;
    while (low <= high) {
        i = parseInt((low + high) / 2, 10);
        comparison = comparator(this[i], find);
        if (comparison > 0)
            low = i + 1;
        else if (comparison < 0)
            high = i - 1;
        else {
            ret = i;
            break;
        }
    }
    if (ret < 0)
        ret = undefined;

    return ret;
};

Array.prototype.any = function (test) {
    var functionTest = typeof test == "function" ? test : function (x) { return x == test; };

    for (var i = 0, len = this.length; i < len; i++)
        if (functionTest(this[i]))
            return true;

    return false;
};

Array.prototype.orderBy = function (test) {
    var len = this.length;
    if (len >= 2) {
        for (var i = 0; i < len; i++) {
            for (var j = 0; j < len; j++) {
                if (test(this[i]) < test(this[j])) {
                    var x = this[i];
                    this[i] = this[j];
                    this[j] = x;
                }
            }
        }
    }
}

Array.prototype.clearUndefined = function () {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == undefined) {
            this.remove(i);
            i--;
        }
    }

    return false;
};

Array.prototype.clearStringEmpty = function () {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == "" || this[i] == null || this[i] == undefined) {
            this.remove(i);
            i--;
        }
    }

    return false;
};

Array.prototype.min = function () {
    var minValue = undefined;

    for (var i = 0, len = this.length; i < len; i++) {
        if (!minValue || this[i] < minValue)
            minValue = this[i];
    }

    return !minValue ? 0 : minValue;
};

Array.prototype.max = function () {
    var maxValue = undefined;

    for (var i = 0; i < this.length; i++) {
        if (!maxValue || this[i] > maxValue)
            maxValue = this[i];
    }

    return !maxValue ? 0 : maxValue;
};

Array.prototype.sum = function (func) {

    if (func == undefined)
        func = function (r) { return r; };

    var sumValues = 0;

    for (var i = 0; i < this.length; i++) {
        sumValues += func(this[i]);
    }

    return sumValues;
};

Array.prototype.removeAll = function (test) {
    var newArray = [];

    for (var i = 0; i < this.length; i++) {
        if (!test(this[i]))
            newArray.push(this[i]);
    }

    return newArray;
};

function GenderCodeToGenderString(code) {
    switch (parseInt(code)) {
        case Gender.Masculino:
            return "Masculino";

        case Gender.Feminino:
            return "Feminino";
    }
}

function PaxTypeCodeToPaxTypeString(code) {
    switch (code) {
        case PaxType.Adulto:
            return "Adulto";

        case PaxType.Crianca:
            return "Criança";

        case PaxType.Bebe:
            return "Bebê";
    }
}

function CabinTypeCodeToCabinTypeString(code) {
    switch (code) {
        case CabinType.PrimeiraClasse:
            return "Primeira Classe";

        case CabinType.Executiva:
            return "Executiva";

        case CabinType.Economica:
            return "Economica";
    }
}

function GetCCExpireDateFromDate(date) {
    return date.format("MM/yyyy");
}

function ArrToString(objArr) {

    var ret = '';

    for (var idx in objArr) {
        ret += objArr[idx];
    }

    return ret;
}

function isValidDate(data, formato) {
    if (!formato) {

        var mes = 2;
        var dia = 1;
        var ano = 3;
    }
    else {
        // SerÃ¡ usado o formato passado no segundo argumento
        formato = formato.toLowerCase().replace(/[^dmy]/g, '');
        var dia = formato.indexOf('d') + 1;
        var mes = formato.indexOf('m') + 1;
        var ano = formato.indexOf('y') + 1;
    }


    var matches = data.match(/^\b(\d+)\D(\d+)\D(\d+)\b\b(?:\s+(\d{1,2})\D(\d{2})\D*((\d{2})?))?\b$/);

    if (!matches)
        return false;

    matches.clearUndefined();

    matches.clearStringEmpty();

    // validando a data
    if (!checkDate(matches[dia], matches[mes], matches[ano])) {
        return false;
    }
    else {
        return true;
    }

}

function checkDate(dia, mes, ano) {
    var dateRegExp = /^(19|20)\d\d-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$/;
    if (!dateRegExp.test(ano + "-" + mes + "-" + dia)) return false; // formato invÃƒÂ¡lido
    if (dia == 31 && (/^0?[469]$/.test(mes) || mes == 11)) {
        return false; // dia 31 de um mes de 30 dias
    } else if (dia >= 30 && mes == 2) {
        return false; // mais de 29 dias em fevereiro
    } else if (mes == 2 && dia == 29 && !(ano % 4 == 0 && (ano % 100 != 0 || ano % 400 == 0))) {
        return false; // dia 29 de fevereiro de um ano nÃ£o bissexto
    } else {
        return true; // Data vÃ¡lida
    }
}

function checkTime(h, m, s) {
    if (!s) s = '00';
    var horarioRegExp = /^(0?\d|1\d|2[0-3]):[0-5]?\d:[0-5]?\d$/;
    return horarioRegExp.test(h + ":" + m + ":" + s);
}

String.prototype.ReplaceStringMessage = function (PointOfSale) {
    if (PointOfSale == 'BRADESCO') {
        this.replaceAll('compra', 'resgate');
        this.replaceAll('reais', 'pontos');
        this.replaceAll('Problemas de processamento', 'Ocorreu um erro no processamento de seu resgate. Por favor refaça sua busca em alguns minutos.')
    }
}

String.prototype.ReplaceHyphens = function () {
    return this.replaceAll('---', ')').replaceAll('--', '(');
}

function verificarDataPesquisaVoo(obj) {
    //alert(isValidDate(obj.value));
    if (obj.value != "") {
        if (isValidDate(obj.value)) {
            adjustDate(obj);
            AirMotorUC.SearchRules(obj);
        }
        else
            obj.value = "";
    }
}

function InArray(needle, haystack) {

    for (var i = 0; i < haystack.length; i++)
        if (needle == haystack[i])
            return true;

    return false;
}

function getParamQueryString(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}

String.prototype.normalize = function () {
    return trim(this).RemoveDiacritics().toLowerCase();
}

function Reverse(value) {
    var pos = "";
    var item = value.split('');
    for (var i = item.length - 1; i > -1; i--)
        pos += item[i];
    return pos;
}

function PutPoint(value) {
    value = Reverse(value);
    value = value.replace(/(\d{3})()/g, '$1.$2');
    value = Reverse(value).replace(/^\./, '');
    return value;
}

function pluginDefaultBehavior(plugin, pluginName, args, contructorFunc) {

    if (!plugin.length)
        return plugin;

    var options = args[0];
    var args = Array.prototype.slice.call(args, 1);

    if (typeof options == 'string') {
        var obj = $(plugin[0]).data(pluginName + "Data");

        if (obj && obj[options])
            return obj[options].apply(plugin, args);
        else if (console)
            console.log("Unable to find method " + options + " in element " + pluginName);
    }
    else
        return plugin.each(function () {

            var obj = $(this).data(pluginName + "Data");

            if (!obj) {
                obj = contructorFunc();
                $(this).data(pluginName + "Data", obj);
            }

            obj.initialize(this, options);
        });
}

function openPopunder() {
    if (CurrentPointOfSale == "SUBMARINO" || CurrentPointOfSale == "AMERICANAS" || CurrentPointOfSale == "SHOPTIME") {
        TheNewWin = window.open('', 'name', 'height=359,width=615,top=0,left=0,close=yes,dialog=yes,minimizable=no,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no');
        TheNewWin.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-transitional.dtd"><html xmlns="http:\/\/www.w3.org\/1999\/xhtml">');
        TheNewWin.document.write('<head><title>Fale Conosco<\/title><\/head><body style="overflow:hidden" bgcolor="#ffffff"><img src="' + rootPath);
        TheNewWin.document.write('Styles/images/' + CurrentPointOfSale + '/img-popunder.jpg" \/><\/body><\/html>');
        TheNewWin.blur();
        window.focus();
    }
}

if (typeof Util == 'undefined') Util = {};

Util.JSONMinimumDeserializer = function (serializedObj) {

    if ($.isArray(serializedObj) && serializedObj.length == 2) {

        var getObject = function (value, currentType, types) {
            if (!currentType || value == undefined)
                return value;

            var obj = currentType.d || currentType.e ? [] : {};

            var innerType = types[currentType.i];

            if (currentType.d) {
                for (var i = 0; i < value.length; i += 2)
                    obj.push({ Key: value[i], Value: getObject(value[i + 1], innerType, types) });
            }
            else if (currentType.e) {
                for (var i = 0; i < value.length; i++)
                    obj.push(getObject(value[i], innerType, types));
            }

            else {
                for (var i = 0; i < currentType.p.length; i++)
                    obj[currentType.p[i].n] = getObject(value[i], types[currentType.p[i].i], types);
            }

            return obj;
        };

        return getObject(serializedObj[1], serializedObj[0][0], serializedObj[0]);
    }

    return serializedObj;
}

Util.GetMethodToInvoke = function (method) {
    return method + (typeof Global != 'undefined' && Global.UseJSONMinimum ? "JSONMinimum" : "");
}

function imgError(obj) {
    obj.attr("src", "Styles/images/icos_cias/companhia.png");
}

$(document).ready(function () {
    setInterval(function () {
        $('img.img-cias, img.icon-cia').unbind('error');
        $('img.img-cias, img.icon-cia').error(function () {
            imgError($(this));
        });
    }, 1000);
});

