﻿var bookingEnginePath = '';
var productCodeId = '';
var arrDateLabel = '';
var depDateLabel = '';
var showUnits;
var showAdults;
var showChildren;
var showOther;
var currentOptGrp = '';
var currentOpt = '';

$(document).ready(function() {
    $.ajax({
        url: configurationFileUrl,
        success: function(data) {
            buildForm(data);
        }
    });
    $('#btnGo').attr('src', btnGoSrc);
    $("#arrivalDate").datepicker({
        minDate: '0',
        showOn: 'focus',
        onSelect: function(dateText, inst) { setMinDepartureDate(dateText, inst); }
    });
    $("#arrivalDate").change(function() { setMinDepartureDate($("#arrivalDate").val(), $("#arrivalDate")); });

    $("#departureDate").datepicker({
        minDate: '0',
        showOn: 'focus',
        onSelect: function(dateText, inst) { setMaxArrivalDate(dateText, inst); }
    });
    $("#departureDate").change(function() { setMaxArrivalDate($("#departureDate").val(), $("#departureDate")); });

    $("#arrivalMonthVisible").monthpicker({
        showMonthNamesOnly: true,
        altField: '#arrivalMonth',
        altFormat: 'm/d/yy',
        minDate: -31,
        maxDate: null,
        dateFormat: 'M, yy',
        showAnim: 'fadeIn'
    });

    $('#arrivalDate').focus(function() {
        if (this.value == arrDateLabel) {
            this.value = '';
        }
    }).blur(function() {
        if (this.value == '') {
            this.value = arrDateLabel;
        }
    });
    $('#departureDate').focus(function() {
        if (this.value == depDateLabel) {
            this.value = '';
        }
    }).blur(function() {
        if (this.value == '') {
            this.value = depDateLabel;
        }
    });
    $('#arrivalMonthVisible').focus(function() {
        if (this.value == arrDateLabel) {
            this.value = '';
        }
    }).blur(function() {
        if (this.value == '') {
            this.value = arrDateLabel;
        }
    });
    $('#aGoBook').click(function() {
        if ($('#selMain').val() == '') {
            alert("Please select a booking option");
        }
        else {
            return goBook();
        }
    });

    $('label[for=SailingMonth]').css('cursor', 'pointer').qtip({
        content: { title: "Sailing Month", text: "In what month would you like to depart?" },
        show: "mouseover",
        hide: "mouseout",
        style:
        {
            name: "cream",
            tip: "bottomMiddle",
            width: 200,
            textAlign: "center"
        },
        position:
        {
            corner:
            {
                target: "topMiddle",
                tooltip: "bottomMiddle"
            }
        }
    });

    $('label[for=TripLength]').css('cursor', 'pointer').qtip({
        content: { title: "Trip Duration", text: "How many days will you be renting the houseboat?" },
        show: "mouseover",
        hide: "mouseout",
        style:
        {
            name: "cream",
            tip: "bottomMiddle",
            width: 200,
            textAlign: "center"
        },
        position:
        {
            corner:
            {
                target: "topMiddle",
                tooltip: "bottomMiddle"
            }
        }
    });



    $('label[for=GroupCode]').css('cursor', 'pointer').qtip(
    {
        content: { title: "Group Code", text: "If you are a member of a group and have been given a Group Code, enter it here." },
        show: "mouseover",
        hide: "mouseout",
        style:
        {
            name: "cream",
            tip: "bottomMiddle",
            width: 200,
            textAlign: "center"
        },
        position:
        {
            corner:
            {
                target: "topMiddle",
                tooltip: "bottomMiddle"
            }
        }
    });

    $('label[for=CorporateCode]').css('cursor', 'pointer').qtip(
    {
        content: { title: "Promo Code", text: "If you have a promo code, enter it here." },
        show: "mouseover",
        hide: "mouseout",
        style:
        {
            name: "cream",
            tip: "bottomMiddle",
            width: 200,
            textAlign: "center"
        },
        position:
        {
            corner:
            {
                target: "topMiddle",
                tooltip: "bottomMiddle"
            }
        }
    });


    $('label[for=AgentCode]').css('cursor', 'pointer').qtip(
    {
        content: { title: "IATA Number", text: "If you are a travel agent and have an IATA number, enter it here." },
        show: "mouseover",
        hide: "mouseout",
        style:
        {
            name: "cream",
            tip: "bottomMiddle",
            width: 200,
            textAlign: "center"
        },
        position:
        {
            corner:
            {
                target: "topMiddle",
                tooltip: "bottomMiddle"
            }
        }
    });

    $('#aBookingAdvanced').click(function(ev) {
        ev.preventDefault();
        $('#hideSearch').toggle();
        $('#advancedSearchWrapper').toggle();
    });
});

function buildForm(data) {

    // clear the select first
    $('#selMain').empty();
    // add the default 'plan your fun' option
    var optFirst = document.createElement("option");
    $(optFirst).text($(data).find('BookingWidget Select:first').attr('defaultValue'));
    $(optFirst).attr('value', '');

    var showDefaultDropdown = true;

    if (startNode != '') {

        var startNodeParts = startNode.split("|");
        // don't build the entire dropdown; instead default to a certain
        // starting point based on the property passed into the control
        if (startNodeParts.length == 2) {
            // this is the rare case (Reserve Denali) that has a default opt group
            // as well as a default sub field value
            if ($(data).find('BookingWidget Select Group Option[id=' + startNodeParts[0] + ']').find('Type Item[value=' + startNodeParts[1] + ']').length == 1) {
                // we do have a sub field default option

                var optXml = $(data).find('BookingWidget Select Group Option[id=' + startNodeParts[0] + ']');
                // build an option and add it to the main dropdown
                buildOption(optXml, $('#selMain'));

                // get the parent option group and build the object in memory
                var optParent = $(optXml).parent();
                window[$(optParent).attr('id')] = buildOptionGroupObject($(optParent));

                // now we have our dropdown with just the one product offering
                // so we need to manually trigger the onchange event to get
                // the rest of the form to show up
                $('#selMain').trigger('change');

                // now we should have all of our subfields set in a select box
                // but we need to remove all except for the selected default one.
                // a bit of a kludge.
                //$('#' + window[currentOpt].subFields[0].formFieldId).find('option').not($('#' + window[currentOpt].subFields[0].formFieldId + " option[value='" + startNodeParts[1] + "']")).remove();
                $('#Type').find('option').not($("#Type option[value='" + startNodeParts[1] + "']")).remove();

                showDefaultDropdown = false;
            }
        }
        else {
            if ($(data).find('BookingWidget Select Group[id=' + startNode + ']').length == 1) {
                // showing an entire option group
                // add the default option
                $('#selMain').append($(optFirst));
                var thisGroup = $(data).find('BookingWidget Select Group[id=' + startNode + ']');
                buildOptionGroup($(thisGroup), $('#selMain'));
                showDefaultDropdown = false;
            }
            else if ($(data).find('BookingWidget Select Group Option[id=' + startNode + ']').length == 1) {
                // showing just a single option
                var optXml = $(data).find('BookingWidget Select Group Option[id=' + startNode + ']');
                // build an option and add it to the main dropdown
                buildOption(optXml, $('#selMain'));

                // get the parent option group and build the object in memory
                var optParent = $(optXml).parent();
                window[$(optParent).attr('id')] = buildOptionGroupObject($(optParent));

                // now we have our dropdown with just the one product offering
                // so we need to manually trigger the onchange event to get
                // the rest of the form to show up
                $('#selMain').trigger('change');
                showDefaultDropdown = false;
            }
        }
    }
    if (showDefaultDropdown) {
        // build the dropdown based on the entire XML config document
        // add the default option
        $('#selMain').append($(optFirst));

        // find each optgroup in the XML and add to the select
        $(data).find('BookingWidget Select Group').each(function() {
            buildOptionGroup($(this), $('#selMain'));
        });
    }

    // hide the 'loading' message and show the form
    $('#loadingContainer').hide();
    $('#bookingTypeContainer').show();
}
function buildOptionGroup(xml, parent) {
    // build an object out of this xml
    window[$(xml).attr('id')] = buildOptionGroupObject($(xml));

    var og = document.createElement('optgroup');
    $(og).attr('label', $(xml).attr('label'));
    $(og).attr('id', $(xml).attr('id'));

    // now find all of the option elements for this optgroup
    $(xml).find('Option').not($(xml).find('SubField Option')).each(function() {
        buildOption($(this), $(og));
    });

    // append this option group to the main dropdown
    $(parent).append($(og));
}
function buildOption(xml, parent) {
    var o = document.createElement('option');
    $(o).attr('value', $(xml).attr('value'));
    $(o).attr('id', $(xml).attr('id'));
    $(o).text($(xml).attr('name'));
    $(parent).append($(o));

    // build the object to store in memory
    //window[$(xml).attr('value')] = buildOptionObject($(xml));
    window[$(xml).attr('id')] = buildOptionObject($(xml));
}
function changeForm() {
    if ($('#selMain').val() == '') {
        // no value, reset the form
        hideSubForm();
    }
    else {
        var sel = $('#selMain :selected');

        var optObj = window[$('#selMain :selected').attr('id')];

        // that object should have a reference to its parent
        var pid = optObj.parentId;
        // now we can get the parent object which will have its label
        var lbl = window[pid].label;

        currentOptGrp = pid;
        //currentOpt = $('#selMain').val();
        currentOpt = $('#selMain :selected').attr('id');

        // get this parent object out of memory
        bookingEnginePath = window[pid].bookingUrl;
        productCodeId = window[pid].formFieldId;
        arrDateLabel = window[pid].arrDateLabel;
        depDateLabel = window[pid].depDateLabel;

        // set the label to the text of the selected item's group
        $('#bookingTypeLabel').html(lbl);

        resetSubForm(false);
        $('#formWrapper').show();
    }
}
function hideSubForm() {
    $('#bookingTypeLabel').html('&nbsp;');
    bookingEnginePath = '';
    productCodeId = '';
    $('#formWrapper').hide();
    resetSubForm(true);
}
function resetSubForm(resetDropdowns) {
    if (resetDropdowns) {
        $('#UnitCount').val('1');
        $('#Adults').val('2');
        $('#Children').val('0');
        $('#Other').val('0');
    }
    $('#arrivalDate').val(arrDateLabel);
    $('#departureDate').val(depDateLabel);
    $('#arrivalMonthVisible').val(arrDateLabel);


    var typeArray = window[currentOpt].typeArray;
    if (typeArray.length > 0) {
        $('#Type').html(''); // clear inner elements
        for (var i in typeArray) {
            $('#Type').append(typeArray[i]);
        }
        $('#wrapType').show();
    }
    else {
        $('#Type').html(''); // clear inner elements
        $('#wrapType').hide();
    }

    if (window[currentOptGrp].showUnits === 'true') {
        $('#wrapUnits').show();
    }
    else {
        $('#wrapUnits').hide();
    }
    if (window[currentOptGrp].showAdults === 'true') {
        $('#wrapAdults').show();
    }
    else {
        $('#wrapAdults').hide();
    }
    if (window[currentOptGrp].showChildren === 'true') {
        $('#wrapChildren').show();
    }
    else {
        $('#wrapChildren').hide();
    }
    if (window[currentOptGrp].showOther === 'true') {
        $('#wrapOther').show();
        $('#otherLabel').html(window[currentOptGrp].otherLabel);
    }
    else {
        $('#wrapOther').hide();
    }
    if (window[currentOptGrp].useMonthPicker === 'true') {
        $('#monthPickerContainer').show();
        $('#datePickerContainer').hide();
    }
    else {
        $('#monthPickerContainer').hide();
        $('#datePickerContainer').show();
    }

    // get rid of any sub fields
    $('#subFieldContainer').children().remove();

    for (var i = 0; i < window[currentOpt].subFields.length; i++) {
        var thisSubField = window[currentOpt].subFields[i];
        // create the wrapper
        // TODO: assuming a dropdown
        var selWrapper = document.createElement("div");
        selWrapper.className = "selWrapper";

        // add the label wrapper
        var selLabel = document.createElement("div");
        selLabel.className = "selLabel";
        selLabel.innerHTML = thisSubField.label;
        selWrapper.appendChild(selLabel);

        // the field wrapper
        var selField = document.createElement("div");
        selField.className = "selField";
        // add the select field
        var sel = document.createElement("select");
        sel.id = thisSubField.formFieldId;

        for (var opt = 0; opt < thisSubField.options.length; opt++) {
            var thisOpt = thisSubField.options[opt];
            var selOpt = document.createElement("option");
            $(selOpt).attr('value', thisOpt.value);
            $(selOpt).text(thisOpt.text);
            $(sel).append($(selOpt));
        }
        selField.appendChild(sel);
        selWrapper.appendChild(selField);

        $('#subFieldContainer').append(selWrapper);

        var br = document.createElement("br");
        br.style.clear = "both";
        $('#subFieldContainer').append(br);
    }

}
function setMinDepartureDate(dateText, datepicker) {
    var dt = new Date(dateText);
    dt.setDate(dt.getDate() + 1);
    $('#departureDate').datepicker('option', 'minDate', dt);
}
function setMaxArrivalDate(dateText, datepicker) {
    var dt = new Date(dateText);
    dt.setDate(dt.getDate() - 1);
    $('#arrivalDate').datepicker('option', 'maxDate', dt);
}
function goBook() {

    var dtNow = new Date();
    dtNow.setHours(0, 0, 0, 0);

    var oArrive = document.getElementById("arrivalDate");
    var dtArrive = new Date(oArrive.value);
    var oDepart = document.getElementById("departureDate");
    var dtDepart = new Date(oDepart.value);
    var oMonth = document.getElementById("arrivalMonthVisible");
    var dtMonth = new Date(oMonth.value);

    if (window[currentOptGrp].useMonthPicker === 'true') {
        if (oMonth.value == '' || oMonth.value == arrDateLabel || dtMonth < dtNow) {
            alert("Please select an arrival month.");
            oMonth.focus();
            return false;
        }
    }
    else {
        if (oArrive.value == '' || oArrive.value == arrDateLabel || dtArrive < dtNow) {
            alert("Please select a future arrival date.");
            oArrive.focus();
            return false;
        }

        if (oDepart.value == '' || oDepart.value == depDateLabel || dtDepart < dtNow) {
            alert("Please select a future departure date.");
            oDepart.focus();
            return false;
        }

        if (dtArrive > dtDepart) {
            alert("Please select an arrival date that is before the departure date");
            oArrive.focus();
            return false;
        }
    }

    /*
    var postForm = document.createElement("form");
    postForm.method = "post";
    postForm.action = bookingEngineUrlRoot + bookingEnginePath
    postForm.target = "_blank";
    */
    var postForm = document.createElement("form");
    postForm.setAttribute("action", bookingEngineUrlRoot + bookingEnginePath);
    postForm.setAttribute("method", "post");
    postForm.setAttribute("name", "frmGoBook2");
    postForm.setAttribute("id", "frmGoBook2");
    postForm.setAttribute("style", "display:none;");
    postForm.setAttribute("target", "obe");
    postForm.setAttribute("onSubmit", "pageTracker._linkByPost(this); window.open('about:blank', 'obe', 'width=1024,height=680,scrollbars=yes,resizable=yes')");

    addFormField(postForm, productCodeId, $('#selMain').val());

    if ($("#Type").html().length > 0) {
        var utc = $("#Type option:selected").val();
        addFormField(postForm, "UnitTypeCode", utc);
    }

    if (window[currentOptGrp].showUnits === 'true') {
        addFormField(postForm, "UnitCount", $('#UnitCount').val());
    }
    if (window[currentOptGrp].showAdults === 'true') {
        addFormField(postForm, "Adults", $('#Adults').val());
    }
    if (window[currentOptGrp].showChildren === 'true') {
        addFormField(postForm, "Children", $('#Children').val());
    }
    if (window[currentOptGrp].showOther === 'true') {
        addFormField(postForm, "Other", $('#Other').val());
    }


    if (window[currentOptGrp].useMonthPicker === 'true') {
        addFormField(postForm, "ArrivalMonth", $('#arrivalMonthVisible').val());
        addFormField(postForm, "ArrivalMonthVisible", $('#arrivalMonthVisible').val());
        addFormField(postForm, "TripLength", $('#TripLength').val());
    }
    else {
        if (!isNaN(dtArrive.getMonth())) {
            addFormField(postForm, "ArrivalDate", (dtArrive.getMonth() + 1) + "/" + dtArrive.getDate() + "/" + dtArrive.getFullYear());
        }
        if (!isNaN(dtDepart.getMonth())) {
            addFormField(postForm, "DepartureDate", (dtDepart.getMonth() + 1) + "/" + dtDepart.getDate() + "/" + dtDepart.getFullYear());
        }
    }

    //add advanced fields
    addFormField(postForm, "GroupCode", $('#GroupCode').val());
    addFormField(postForm, "CorporateCode", $('#CorporateCode').val());
    addFormField(postForm, "AgentCode", $('#AgentCode').val());

    // does the selected option group type have any sub fields?
    if (window[currentOpt].subFields.length > 0) {
        for (var i = 0; i < window[currentOpt].subFields.length; i++) {
            var thisSubField = window[currentOpt].subFields[i];

            // TODO: assuming for now it's a select field
            addFormField(postForm, thisSubField.formFieldId, $('#' + thisSubField.formFieldId).val());
        }
    }

    document.body.appendChild(postForm);
    // GA
    //pageTracker._linkByPost(postForm);
    //postForm.submit();

    var newSubmitButton = document.createElement("input");
    newSubmitButton.setAttribute("type", "submit");
    newSubmitButton.setAttribute("name", "btnSubmit");
    newSubmitButton.setAttribute("value", "Go");
    postForm.appendChild(newSubmitButton);
    newSubmitButton.click();

    return false;
}
function buildOptionGroupObject(xml) {
    var obj = {
        bookingUrl: $(xml).attr('actionUrl'),
        formFieldId: $(xml).attr('formFieldId'),
        arrDateLabel: $(xml).attr('arrDateLabel'),
        depDateLabel: $(xml).attr('depDateLabel'),
        useMonthPicker: $(xml).attr('useMonthPicker'),
        showUnits: $(xml).attr('showUnits'),
        showChildren: $(xml).attr('showChildren'),
        showAdults: $(xml).attr('showAdults'),
        showOther: $(xml).attr('showOther'),
        otherLabel: $(xml).attr('otherLabel'),
        label: $(xml).attr('label')
    }

    return obj;

}

function buildSubField(xml, parent) {
    var obj = {};

    switch ($(xml).attr('fieldType')) {
        case "select":
            obj.fieldType = "select";
            obj.formFieldId = $(xml).attr('formFieldId');
            obj.label = $(xml).attr('label');
            obj.options = new Array();
            $(xml).find('Option').each(function() {
                obj.options.push(buildOptionObject($(this)));
            });
            break;
    }

    return obj;
}

function buildOptionObject(xml) {

    // Adds the type options for each item into memory
    var tArray = new Array();
    if ($(xml).find('Type').attr('id') != undefined) {
        var tid = $(xml).find('Type').attr('id');

        $(xml).find("Type[id='" + tid + "'] Item").each(function() {
            var option = '<option value="' + $(this).attr('value') + '">' + $(this).attr('name') + '</option>';
            tArray.push(option);
        });
    }

    var obj = {
        id: $(xml).attr('id'),
        parentId: $(xml).parent().attr('id'),
        value: $(xml).attr('value'),
        text: $(xml).attr('name'),
        subFields: new Array(),
        typeArray: tArray
    }

    if ($(xml).find('SubField').length > 0) {
        $(xml).find('SubField').each(function() {
            var sf = buildSubField($(this));
            obj.subFields.push(sf);
        });
    }
    return obj;

}