﻿$(document).ready(function () {

    DatePicker();
    CheckTripType();

    $("#TripType").change(function () {
        ChangeTripType();
    });

    $("[id=btnTripContinue]").click(function () {

        var travellers = $("[id$=TravellerQuantity]").val();
        var relationship = $("[id$=GroupType]").val();

        if (travellers == 0) {
            alert("There should be at least 1 traveller");
            return false;
        }
        if ((relationship == "Individual") && (travellers > 1)) {
            alert("There can be only 1 traveller when 'Individual' is selected");
            return false;
        }
        if (relationship == 'Couple' && (travellers != 2)) {
            alert("There must be 2 adults on a 'Couple' policy");
            return false;
        }
        if (relationship == 'GroupOfPeople' && (travellers < 2)) {
            alert("Number of travellers should be more than one");
            return false;
        }
    });

    $("[id$=GroupType]").change(function () {
        var groupType = $("[id$=GroupType]").val();
        var travellerQuantity = $("[id$=TravellerQuantity]").val();
        if (groupType == "Individual") {
            $("#TravellerQuantity option[value='1']").attr("disabled", false);
            $("#TravellerQuantity option[value='1']").attr("selected", "selected");
            $("#TravellerQuantity").attr("disabled", true);
        }
        else if (groupType == "Couple") {
            $("#TravellerQuantity option[value='1']").attr("disabled", false);
            $("#TravellerQuantity option[value='2']").attr("disabled", false);
            $("#TravellerQuantity option[value='2']").attr("selected", "selected");
            $("#TravellerQuantity").attr("disabled", true);
        }
        else if (groupType == "Family") {
            $("#TravellerQuantity option[value='1']").attr("disabled", true);
            $("#TravellerQuantity option[value='2']").attr("disabled", false);
            $("#TravellerQuantity option[value='3']").attr("disabled", false);
            $("#TravellerQuantity option[value='3']").attr("selected", "selected");
            $("#TravellerQuantity").attr("disabled", false);
        }
        else if (groupType == "GroupOfPeople") {
            $("#TravellerQuantity").attr("disabled", false);
            if (travellerQuantity == 1) {
                $("#TravellerQuantity option[value='1']").attr("disabled", true);
                $("#TravellerQuantity option[value='2']").attr("disabled", false);
                $("#TravellerQuantity option[value='3']").attr("disabled", false);
                $("#TravellerQuantity option[value='3']").attr("selected", "selected");
            }
        }
        travellerQuantity = $("[id$=TravellerQuantity]").val();
        CreateAgeBoxes(travellerQuantity);
    })

    $("#TravellerQuantity").change(function () {

        var travellerQuantity = $("#TravellerQuantity").val();

        if (travellerQuantity == 1) {
            $("#Policy_GroupType option[value='Individual']").attr("selected", "selected");
        }
        else if (travellerQuantity == 2) {
            $("#Policy_GroupType option[value='Couple']").attr("selected", "selected");
        }
        else if (travellerQuantity == 3) {
            $("#Policy_GroupType option[value='Family']").attr("selected", "selected");
        }
        else if (travellerQuantity > 3) {
            $("#Policy_GroupType option[value='GroupOfPeople']").attr("selected", "selected");
        }

        var qRequired = parseInt($(this).val());
        CreateAgeBoxes(qRequired);
    });

    $("[id=btnMedicalContinue]").click(function () {
        $("[id$=quoteform-trip]").hide();
        $("[id$=quoteform-medical]").hide();
        $("[id$=quoteform-travellers]").show();
    });

    $("[id=btnMedicalContinue]").click(function () {
        $("[id$=quoteform-trip]").hide();
        $("[id$=quoteform-medical]").hide();
        $("[id$=quoteform-travellers]").show();
    });

    $("[id=btnBackTravellers]").click(function () {
        $("[id$=quoteform-travellers]").hide();
        var hasMedical = $("[id$=MedicalCondition]").val();
        if (hasMedical == "true") {
            $("[id$=quoteform-medical]").show();
        }
        else {
            $("[id$=quoteform-trip]").show();
        }
    });

    $("[id=btnBackMedical]").click(function () {
        $("[id$=quoteform-trip]").show();
        $("[id$=quoteform-medical]").hide();
        $("[id$=quoteform-travellers]").hide();
    });

    $("#navigation li:last-child a").css("border", "none");
    $("#navigation li:first-child a").css("padding-left", "0");
    $("#footer-navigation li:last-child a").css("border", "none");
    $("#footer-navigation li:first-child a").css("padding-left", "0");

    //    $('.qdestination').CreateBubblePopup({

    //        position: 'left',
    //        align: 'middle',

    //        innerHtml: '<strong>Europe (inc Egypt, Morocco, Turkey &amp; Tunisia):</strong><br />Albania, Andorra, Armenia, Austria, Azerbaijan, Belgium, Belarus, Bosnia-Herzegovina, Bulgaria, Channel \
    //                            Islands, Croatia, Cyprus, Czech Republic, Denmark (including Faeroe Islands), Egypt, Estonia, Finland, France (including \
    //                            Corsica), Georgia, Germany, Greece (including Greek Isles), Hungary, Iceland, Ireland, Italy (including Aeolian Islands, \
    //                            Sardinia, Sicily), Latvia, Liechtenstein, Lithuania, Luxembourg, Macedonia, Malta, Moldova, Monaco, Netherlands, \
    //                            Norway (including Jan Mayen, Svalbard Is), Poland, Portugal (including Azores, Madeira Islands), Romania, Russia \
    //                            (European), San Marino, Serbia/Montenegro (including Kosovo), Slovakia, Slovenia, Spain (including Balearic Islands, \
    //                            Canary Islands), Sweden, Switzerland, Turkey, Ukraine, UK Area and Vatican City.<br /> \
    //                            <br /><strong>Australia and New Zealand.</strong><br />Australia and New Zealand.<br /> \
    //                            <br /><strong>Worldwide (excl USA Canada, Bermuda &amp; Caribbean):</strong><br />All countries worldwide, excluding the United States, Canada, Bermuda and the Caribbean.<br /> \
    //                            <br /><strong>Worldwide (incl USA Canada, Bermuda &amp; Caribbean):</strong><br />All countries worldwide.',

    //        width: '500px',

    //        innerHtmlStyle: {
    //            color: '#181818',
    //            'text-align': 'left',
    //            'font-family': 'Arial, Helvetica, sans-serif',
    //            'line-height': '1.1'
    //        },

    //        themeName: 'all-yellow',
    //        themePath: '/Content/jquerybubblepopup-theme'
    //    });

    //    $('.qstartdate').CreateBubblePopup({

    //        position: 'left',
    //        align: 'middle',

    //        innerHtml: '<strong>Policy Start Date</strong><br/>For single trip policies, from the date you buy your policy, you\'ll have cancellation cover, regardless of whether the policy has started \
    //        Therefor, it is important to buy your travel insurance as early in advance as possible - as soon as you have booked your trip<br /><br />Annual policies cover you for 12 months from the start date. Therefor, \
    //        if you buy an annual policy today to start next month, and there is a problem, you wont be covered',

    //        width: '500px',

    //        innerHtmlStyle: {
    //            color: '#181818',
    //            'text-align': 'left',
    //            'font-family': 'Arial, Helvetica, sans-serif',
    //            'line-height': '1.1'
    //        },

    //        themeName: 'all-yellow',
    //        themePath: '/Content/jquerybubblepopup-theme'
    //    });

    if ($.browser.msie) {
        $('#Destination')
                    .bind('focus mouseover', function () { $(this).addClass('expand').removeClass('clicked'); })
                    .bind('click', function () { $(this).toggleClass('clicked'); })
                    .bind('mouseout', function () { if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); } })
                    .bind('blur', function () { $(this).removeClass('expand clicked'); });
    }

});

function CreateAgeBoxes(boxesToCreate) {
    var qRequired = boxesToCreate;
    var qRendered = $('.travellerage').size();
    var qToRender = qRequired - qRendered;
    var html = "";
    if (qToRender > 0) {
        for (i = qRendered + 1; i < qRendered + qToRender + 1; i++) {
            html = html + '<div id="traveller' + i + '" class="group travellerage"><label for="traveller' + i + 'age" id="traveller' + 1 + 'agelabel" class="travellerquantity">' + i + ':</label><input name="traveller' + i + 'age" id="traveller' + i + 'age"" type="text" class="travelleragebox inputbox inputboxtiny"  /></div>'
        }
        $(html).insertAfter(".travellerage:last");
    }
    else if (qToRender < 0) {
        var qToRemove = Math.abs(qToRender);
        for (i = qRendered; i > (qRendered - qToRemove); i--) {
            $('#traveller' + i).remove();
        }
    }
}

this.DatePicker = function () {
    var maximumDate;
    var tripType = $("[id$=TripType]").val();

    $.datepicker.setDefaults({
        showOn: 'both',
        buttonImageOnly: true,
        buttonImage: '/Content/Img/Site/calendar.png',
        buttonText: 'Calendar',
        dateFormat: 'dd/mm/yy',
        minDate: 0,
        maxDate: 365
    });

    $("[id$=StartDate]").datepicker();
    $("[id$=EndDate]").datepicker();

    $("[id$=StartDate]").val($.datepicker.formatDate('dd/mm/yy', addDays(new Date(), 0)));
    $("[id$=EndDate]").val($.datepicker.formatDate('dd/mm/yy', addDays(new Date(), 7)));

    $(".ui-datepicker-trigger").css('cursor', 'pointer');
    $(".ui-datepicker-trigger").css('margin-top', '-4px');
    $(".ui-datepicker-trigger").css('margin-left', '5px');

    $(".ui-datepicker-trigger").hover(function () {
        $(this).css('cursor', 'hand');
        $(this).attr("src", "/Content/Img/Site/calendar-over.png");
    }, function () {
        $(this).attr("src", "/Content/Img/Site/calendar.png");
    });
}

function CheckTripType() {

    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 = "Annual";
    }
    if (hostUrl.match("single") != null) {
        $("#TripType option[value='SingleTrip']").attr("selected", "selected");
        tripType = "SingleTrip";
    }
    if (hostUrl.match("backpackers") != null) {
        $("#TripType option[value='LongStay']").attr("selected", "selected");
        tripType = "LongStay";
    }
    if (hostUrl.match("golf") != null) {
        $("#TripType option:not(:contains(Golf))").each(function () {
            $(this).append(" (with Golf cover)");
        });
        $("#Option").val("gol");
    }
    if (hostUrl.match("business") != null) {
        $("#TripType option:not(:contains(Business))").each(function () {
            $(this).append(" (with Business cover)");
        });
        $("#Option").val("bus");
    }
    if (hostUrl.match("wedding") != null) {
        $("#TripType option[value='SingleTrip']").append(" (with Wedding cover)");
        $("#TripType option[value='Annual']").attr("disabled", true);
        $("#Option").val("wdg");
    }
    if (hostUrl.match("winter") != null || hostUrl.match("ski") != null) {
        $("#TripType option:not(:contains(Winter))").each(function () {
            $(this).append(" (with Winter Sports cover)");
        });
        $("#Option").val("wsc");
    }
    if (hostUrl.match("backpacker") != null) {
        $("#TripType option[value='LongStay']").attr("selected", "selected");
    }
    if (tripType == 'Annual') {
        $("#EndDateWrapper").css('visibility', 'hidden');
        $("#StartDateLabel").text('Start Date:');
    }
    else {
        $("#EndDateWrapper").css('visibility', 'visible');
        $("#StartDateLabel").text('Depart Date:');
    }
}

function ChangeTripType() {

    var tripType = $("#TripType").val();

    if (tripType == 'Annual') {
        var startDateString = $("#StartDate").get(0).value;
        var endDateString = CreateEndDate(startDateString);
        $("[id$=EndDate]").get(0).value = endDateString;
        $("#EndDateWrapper").css('visibility', 'hidden');
        $("#StartDateLabel").text('Start Date:');
    }
    else {
        $("#EndDateWrapper").css('visibility', 'visible');
        $("#StartDateLabel").text('Depart Date:');
    }
}

function validateFormOnSubmit(thisform) {

    var errorCount = 0;
    var errorMessage = "";
    var travellers = 0;

    var travellers = 0;
    var relationship = $("#GroupType").val();
    var destination = $("#Destination").val();
    var tripType = $("#TripType").val();
    var residentcountry = $("#residentcountry").val();
    var medicalQuestionOne = $("#medical1").val();
    var medicalQuestionTwo = $("#medical2").val();

    var oldestTraveller = 0;
    $(".travelleragebox").each(function () {
        try {
            var newValue = parseInt($(this).val());

            if (isNaN(newValue)) {
                errorMessage = "Please enter an age";
                errorCount++;
            }

            if (newValue > oldestTraveller) {
                oldestTraveller = newValue;
            }
            travellers = travellers + 1;
        }
        catch (err) {
            errorMessage = "Please enter an age";
            errorCount++;
        }
    });

    if (errorCount > 0) {
        alert(errorMessage);
        return false;
    }

    if ((tripType == "Annual") && (oldestTraveller > 74)) {
        errorMessage = "Sorry, we cannot offer cover to people aged over 74";
        errorCount++;
    }

    if ((tripType == "SingleTrip") && (oldestTraveller > 74)) {
        errorMessage = "Sorry, we cannot offer cover to people aged over 74";
        errorCount++;
    }
    else if ((tripType == "LongStay") && (oldestTraveller > 45)) {
        errorMessage = "Sorry, we cannot offer cover Backpacker cover to people aged over 45";
        errorCount++;
    }

    if (travellers == 0) {
        errorMessage = "There should be at least 1 traveller";
        errorCount++;
    }
    if ((relationship == "Individual") && (travellers > 1)) {
        errorMessage = "There can be only 1 person on this policy";
        errorCount++;
    }
    if (relationship == 'Couple' && (travellers != 2)) {
        errorMessage = "There must be 2 adults on a couple policy";
        errorCount++;
    }
    if (relationship == 'GroupOfPeople' && (travellers < 2)) {
        errorMessage = "Number of travellers should be more than one";
        errorCount++;
    }

    //check the dates
    var reDate = /^(0?[1-9]|([12]\d)|(3[01]))\/(0?[1-9]|(1[012]))\/20\d{2}$/

    var startDate = $("[id$=StartDate]").val();
    if (!startDate.match(reDate)) {
        errorMessage = 'Departure date should be in following format DD/MM/YYYY. Please, check the date.';
        errorCount++;
    }

    var a = startDate.split('/');
    var d1 = new Date(a[2], a[1] - 1, a[0], 0, 0, 0, 0);

    if (tripType == "Annual") {
        var d2 = addDays(d1, 365);
    }
    else {
        var endDate = $("[id$=EndDate]").val();
        if (!endDate.match(reDate)) {
            errorMessage = 'Return date should be in following format DD/MM/YYYY. Please, check the date.';
            errorCount++;
        }
        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()) {
        errorMessage = 'Return date cannot be before departure';
        errorCount++;
    }

    if ((tripType == "Annual") && (d1.getTime() > addDays(d, 31))) {
        errorMessage = 'Sorry, Annual policies cannot start more than 31 days in advance';
        errorCount++;
    }
    else if ((tripType == "Annual") && (d1.getTime() > addDays(d, 1))) {
        alert("Please note: You will not be covered for holiday cancellation until your policy start date. Choose today’s date if you want cover as soon as possible.");
    }

    if ((medicalQuestionOne == "true") || (medicalQuestionTwo == "true")) {

        if (residentcountry != "United Kingdom") {
            errorMessage = "Sorry, cover for pre-existing medical conditions is not availble to EU customers";
            errorCount++;
        }
        else {
            errorMessage = "As you answered \"Yes\" to one or both of the \"Medical Details\" questions you must call 0845 676 0691 to buy your travel insurance";
            errorCount++;
        }
    }

    if (errorCount > 0) {
        alert(errorMessage);
        return false;
    }
    else {
        return true;
    }
}
