$(document).ready(function () {
    TripType();
    DatePicker();
    ToolTip();
    $("[id$=TripType]").change(function () {
        TripType();
    });
});

this.ToolTip = function () {

    var destination = $("[id$=Destination]").val();
    var tripType = $("[id$=TripType]").val();
    var groupType = $("[id$=GroupType]").val();
    var content;

    $.fn.qtip.styles.bigbluetip = { // Last part is the name of the style
        border: {
            width: 2,
            radius: 6,
            color: '#3399CC'
        },
        color: '#3d3d3d',
        padding: 10,
        textAlign: 'left',
        tip: true,
        name: 'blue'
    }

    content = GetDestinationInfo(destination);
    $("#Destination").qtip({
        position: {
            corner: {
                target: 'topLeft',
                tooltip: 'rightTop'
            }
        },
        content: content,
        style: 'bigbluetip'
    });

    content = GetTripTypeInfo(tripType);
    $("#TripType").qtip({
        position: {
            corner: {
                target: 'topLeft',
                tooltip: 'rightTop'
            }
        },
        content: content,
        style: 'bigbluetip'
    });

    content = GetGroupTypeInfo(groupType);
    $("#GroupType").qtip({
        position: {
            corner: {
                target: 'topLeft',
                tooltip: 'rightTop'
            }
        },
        content: content,
        style: 'bigbluetip'
    });

    $("#Destination").change(function () {
        var destination = $(this).val();
        var content = GetDestinationInfo(destination);
        $(this).qtip("api").updateContent(content);
    });

    $("#TripType").change(function () {
        var tripType = $(this).val();
        var content = GetTripTypeInfo(tripType);
        $(this).qtip("api").updateContent(content);
    });

    $("#GroupType").change(function () {
        var groupType = $(this).val();
        var content = GetGroupTypeInfo(groupType);
        $(this).qtip("api").updateContent(content);
    });
}


this.DatePicker = function () {

    var maximumDate;
    var tripType = $("[id$=TripType]").val();

    if (tripType != "Annual") {
        maximumDate = 548;
    }
    else {
        maximumDate = 31;
    }

    $.datepicker.setDefaults({
        showOn: 'both',
        buttonImageOnly: true,
        buttonImage: '/styles/images/calendar.gif',
        buttonText: 'Calendar',
        dateFormat: 'dd/mm/yy',
        minDate: 1,
        maxDate: maximumDate
    });

    $("[id$=StartDate]").datepicker();
    $("[id$=EndDate]").datepicker();

    $("[id$=StartDate]").val($.datepicker.formatDate('dd/mm/yy', AddDays(new Date(), 1)));
    $("[id$=EndDate]").val($.datepicker.formatDate('dd/mm/yy', AddDays(new Date(), 8)));

    $(".ui-datepicker-trigger").css('margin-left', '6px');

    $(".ui-datepicker-trigger").hover(function () {
        $(this).css('cursor', 'hand');
        $(this).attr("src", "/styles/images/calendar_over.gif");
    }, function () {
        $(this).attr("src", "/styles/images/calendar.gif");
    });
}

this.TripType = function () {

    var hostUrl = window.location.pathname;
    var tripType = $("#TripType").val();
    var dropTripType = document.getElementById("TripType");

    if (hostUrl.match("annual") != null) {
        $("#TripType option[value='Annual']").attr("selected", "selected");
        $("#TripType option[value='SingleTrip']").remove();
        tripType = "Annual";
    }
    if (hostUrl.match("single") != null) {
        $("#TripType option[value='SingleTrip']").attr("selected", "selected");
        $("#TripType option[value='Annual']").remove();
        tripType = "SingleTrip";
    }
    if (hostUrl.match("golf") != null) {
        $("#TripType option:not(:contains(Golf))").each(function () {
            $(this).append(" (with Golf cover)");
        });
        $("#PolicyOption").val("golf");
    }
    if (hostUrl.match("business") != null) {
        $("#TripType option:not(:contains(Business))").each(function () {
            $(this).append(" (with Business cover)");
        });
        $("#PolicyOption").val("business");
    }
    if (hostUrl.match("winter") != null) {
        $("#TripType option:not(:contains(Winter))").each(function () {
            $(this).append(" (with Winter Sports cover)");
        });
        $("#PolicyOption").val("winter");
    }
    if (tripType == 'Annual') {
        $("#EndDateRow").css('display', 'none');
        $("#DepartDate").text('Start Date:');
        $(".Adult7579").css('visibility', 'hidden');
    }
    else {
        $("#EndDateRow").css('display', 'block');
        $("#DepartDate").text('Departure Date:');
        $(".Adult7579").css('visibility', 'visible');
    }
}

function ValidateForm(thisform) {

    var adults = 0;
    var dependents = 0;
    var travellers = 0;
    var relationship = $("[id$=GroupType]").val();
    var destination = $("[id$=Destination]").val();
    var tripType = $("[id$=TripType]").val();

    $("[id^=Adult]").each(function () {
        try {
            var value = parseInt($(this).val());
            adults = adults + value;
        }
        catch (err) {
            alert("Please, verify specified value for field");
        }
    });

    if ((parseInt($("[id^=Adult7579]").val()) > 0) && (tripType == "Annual")) {
        alert("Annual Policy is not available to people aged 75 and over");
        return false;
    }

    dependents = parseInt($("[id*=Infants]").val()) + parseInt($("[id*=Children]").val());
    travellers = adults + dependents;

    if (travellers == 0) {
        alert("There should be at least 1 traveller");
        return false;
    }
    if ((dependents > 0) && (adults < 0)) {
        alert("Adults number should be more than zero if number of children more than zero");
        return false;
    }
    if ((relationship == "Individual") && (travellers > 1)) {
        alert("There can be only 1 person on this policy");
        return false;
    }
    if (relationship == 'Couple' && !(adults == 2)) {
        alert("There must be 2 adults on a couple policy");
        return false;
    }
    if (relationship == 'SingleParentFamily' && !((adults) == 1 && children > 0)) {
        alert("There must be 1 adult and 1 or more children on a family policy");
        return false;
    }
    if (relationship == 'Family' && !((adults) == 2 && children > 0)) {
        alert("There must be 2 adults and 1 or more children on a family policy");
        return false;
    }
    if (relationship == 'GroupOfPeople' && !(travellers > 1)) {
        alert("Number of travellers should be more than one");
        return false;
    }

    //check the dates
    var startDate = $("[id$=StartDate]").val();
    var endDate = $("[id$=EndDate]").val();

    var reDate = /^(0?[1-9]|([12]\d)|(3[01]))\/(0?[1-9]|(1[012]))\/20\d{2}$/
    if (!startDate.match(reDate)) {
        alert('Departure date should be in following format DD/MM/YYYY. Please, check the date.');
        return false;
    }
    if (!endDate.match(reDate)) {
        alert('Return date should be in following format DD/MM/YYYY. Please, check the date.');
        return false;
    }

    var a = startDate.split('/');
    var d1 = new Date(a[2], a[1] - 1, a[0], 0, 0, 0, 0);

    a = endDate.split('/');
    var d2 = new Date(a[2], a[1] - 1, a[0], 0, 0, 0, 0);

    var d = new Date();
    d = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0);

    if (d1.getTime() < AddDays(d, 1)) {
        alert('Departure date cannot be before tomorrow');
        return false;
    }

    if (d2.getTime() < d1.getTime()) {
        alert('Return date cannot be before departure');
        return false;
    }

    return true;
}


function GetDestinationInfo(destination) {
    var content;
    if (destination == "Europe") {
        content = "Andorra, Austria, Azores, Balearics, Belgium, Bosnia-Herzegovina, Bulgaria, Canary Islands, Corfu, Corsica, Crete, Croatia, Cyprus, Czech Republic, Denmark, Egypt, Eire, Estonia, Faroe Islands, Finland, France, Germany, Gibraltar, Greece, Greenland, Guernsey, Holland, Hungary, Ibiza, Iceland, Ireland, Isle of Man, Italy, Jersey, Kos (Greek Island), Lanzarote, Latvia, Liechtenstein, Lithuania, Luxembourg, Macedonia, Madeira, Majorca, Malta, Minorca, Monaco, Montenegro, Monserrat, Morocco, Netherlands, Netherlands Antilles, Northern Ireland, Norway, Poland, Portugal, Reunion, Rhodes, Romania, Russia, San Marino, Sardinia, Serbia, Slovakia, Slovenia, Spain, Sweden, Switzerland, Tenerife, Tunisia, Turkey, United Kingdom, Vatican City, Yugoslavia (Former)";
    }
    else if (destination == "ANZO") {
        content = "Australia and New Zealand only plus transfers and stopovers of up to 15% of trip duration";
    }
    else if (destination == "WorldwideUSA") {
        content = "All countries worldwide with the exception of those to which the FCO has advised the public not to travel";
    }
    return content;
}

function GetTripTypeInfo(tripType) {
    var content;
    if (tripType == "SingleTrip") {
        content = "A one-off holiday or trip. For example a two week summer holiday to Greece or a week skiing in Switzerland";
    }
    else if (tripType == "Annual") {
        content = "<strong>If you travel 2 or more times in a year this could save you money!</strong><br/>Travel as many times as you like during a 12 month period and each individual trip can last up to 31 days";
    }
    return content;
}

function GetGroupTypeInfo(groupType) {
    var content;
    if (groupType == "Individual") {
        content = "Any adult aged over 18";
    }
    else if (groupType == "Couple") {
        content = "Two adults who are either legally married or living together as common law partners (including same sex partners) for at least 6 months";
    }
    else if (groupType == "Family") {
        content = "Up to 2 adults and 4 dependent children under the age of 18";
    }
    else if (groupType == "SingleParentFamily") {
        content = "One adult and up to 4 of his/her dependent children under the age of 18";
    }
    else if (groupType == "GroupOfPeople") {
        content = "Any number of people insured on the same policy who are not defined as couple, family or single parent family";
    }
    return content;
}

function AddDays(myDate, days) {
    return new Date(myDate.getTime() + days * 24 * 60 * 60 * 1000);
}