/* Javascript to support the 'plan vacation' sub-form */
/*
 * jQuery form plugin
 * @requires jQuery v1.0.3
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 * Version: .97
 */
jQuery.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = jQuery.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? jQuery.merge(val, v) : val.push(v);
    }
    return val;
};

jQuery.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                // extra pain for IE...
                var v = jQuery.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};
/** Planner **/
// This creates a pseudo-module. The function is called immediately, and its
// results are assigned to planner. The results should be a simple object with
// a couple of exposed members / functions. Excellent javascript trick for
// modular-style programming.
//
// The module also defines document 'on-ready' actions to connect behaviors
// to DOM objects. These all support the 'plan your vacation' form on the
// home page.
//
// Jeff Shell for Bottlerocket, 2007.
// Based on original killington.com code.
var planner = (function($) {
    var RES_URL = "http://shop.killington.com/coris/vacationplanner/vacation.aspx?action=startres";
    
    // sum(values:list, start:integer=0) -> Integer
    //      Returns total of 'values' list, using parseInt to convert from strings
    //      if necessary. Supply a `start` value for values other than zero.
    var sum = function(values, start) {
        var total = start || 0;
        for(var i=0; i<values.length; i++) {
            total += parseInt(values[i], 10);
        }
        return total;
    };

    // calculate_party_size() -> Integer
    //   Gets the current values of all of the select boxes in the 'party ages'
    //   sub-form (in the pop-up window) and sums them up. Returns an integer.
    var calculate_party_size = function() {
        var values = $('#ages-content select').fieldValue();
        return sum(values);
    };
    
    // check_party_size() -> boolean
    //   Calls 'caculate_party_size() and compares the value against the current
    //   selection in the main form's 'party size' widget. Returns boolean based
    //   on whether or not they match.
    var check_party_size = function() {
        var party_size = calculate_party_size();
        return ($.fieldValue($('#planform-party')[0]) == party_size);
        // return ($('#planform-party').get(0)[party_size].selected);
    };
    
    // get_date_values() -> object with month, day, year attributes.
    //   Gets the month, day, and year values from the form and converts
    //   them to integer before returning a simple object structure.
    var get_date_values = function() {
        var values = $('#planform-month, #planform-day, #planform-year').fieldValue();
        return {
            month: parseInt(values[0], 10),
            day: parseInt(values[1], 10),
            year: parseInt(values[2], 10)
        };
    };

    // A more humane ``new Date(year, month day)`` function. Takes 1-based 
    // months instead of Javascript's 0-based. (In JS, January = 0, Feb = 1, 
    // etc..).  ``generate_date(3, 4, 2005)`` is equivalent to 
    // ``new Date(2005, 3, 3)``.
    var generate_date = function(month, day, year) {
        return new Date(year, (month-1), day);
    };
        
    // current_date() -> Date object with all time aspects set to zero so it
    //   can be compared against dates created by `generate_date`.
    var current_date = function() {
        var now = new Date();
        now.setHours(0);
        now.setMinutes(0);
        now.setSeconds(0);
        now.setMilliseconds(0);
        return now;
    };
    
    // coris_format(dt:Date) -> String 'MM/DD/YYYY'
    //   Takes a Javascript Date object and formats it to the style preferred
    //   by CORIS.
    var coris_format = function(dt) {
        return (dt.getMonth()+1) + '/' + dt.getDate() + '/' + dt.getFullYear();
    };
    
    // date_is_past(dt:Date) -> Boolean
    //      Returns true if dt is less than now. `now` is computed with 
    //      `current_date()`, which normalizes the current time to zero-based
    //      time values. Good for comparing days when not caring about hours.
    var date_is_past = function(dt) {
        var now = current_date();
        return (dt < now);
    };
    
    // go_quote() -> This is the submission handler. It checks the values, 
    // particularly the dates, and then calls `go_web_coris_with_dates(...)`
    // to go to the CORIS server.
    var go_quote = function() {
        var arrival_date = get_date_values();
        arrival_date = generate_date(arrival_date.month, arrival_date.day, arrival_date.year);
        if(date_is_past(arrival_date)) {
            alert("The arrival date is in the past!");
            return false;
        }
/* Removed BRG        
        if(!check_party_size()) {
            $('#ages-content').show();
            alert("Under 'Party Size/Ages' you must choose the number of "
                  + "people in each age group for your party!");
            return false;
        }
*/        
        var days_ahead = current_date();
        days_ahead.setDate(days_ahead.getDate() + 1);
        
        if(arrival_date < days_ahead) {
            alert("You can not book a reservation on line for arrival "
                  + "tonight or for a date in the past. Please call "
                  + "Killington Central Reservations at 1-800-621-MTNS "
                  + "for short notice arrivals.");
            return false;
        }

/* Modified BRG
        go_web_coris_with_dates(
            coris_format(arrival_date),
            $('#planform-nights').fieldValue()[0],
            $('#planform-adults').fieldValue()[0],
            $('#planform-seniors').fieldValue()[0],
            $('#planform-teens').fieldValue()[0],
            $('#planform-children').fieldValue()[0]
        );
*/

        go_web_coris_with_dates(
            coris_format(arrival_date),
            $('#planform-nights').fieldValue()[0],
            $('#planform-party').fieldValue()[0],
            0,
            0,
            0
        );
        
        return false;
    };
    
    // go_web_coris_with_dates(...) -> Goes to the CORIS reservation system by
    // opening a new window and generating a CORIS reservation session kickoff
    // URL.
    var go_web_coris_with_dates = function(arrival_date, nights, adults, seniors, teens, children) {
        var width = 800, height = 570;
        var leftposition = (screen.width) ? (screen.width-width)/2 : 100;
        var topposition = (screen.height) ? (screen.height-height)/2 : 100;
        var destination = (
            RES_URL
            +"&adt="+arrival_date
            +"&ddt=&days="+nights
            +"&ad="+adults
            +"&ch="+children
            +"&tn="+teens
            +"&sr="+seniors
        );
        
        window.open(destination, 'CORIS', "height="+height+",width="+width+",toolbar=1,resizable=1,scrollbars=1,location=1,status=1,menubar=1,top="+topposition+",left="+leftposition);
        return false;
    };
    


    // This sets up object behaviors when the DOM objects are ready.
    $(document).ready(function() {
        // The 'get quote' image/button onclick -> calls go_quote();
        $('#plan_your_vacation_check_link').click(function() { return go_quote(); });

        // The 'ages-closer' button ('X') closes the 'group ages' popup.
        $('#ages-closer').click(function() { $('#ages-content').hide(); });
        // Every time the main form's party size popup changes, show the 'select
        // ages' popup.
        $('#ages-content').hide();
        $('#planform-party').change(function () { $('#ages-content').show(); });

        // When any of the 'select ages' widgets change value, update the main
        // form's party size widget.
        $('#ages-content select').change(function() { 
            var party_size = calculate_party_size();
            // Finds the option tag whose value attribute matches party size.
            var selector = '#planform-party option[value='+party_size+']';
            $(selector).get(0).selected = true;
        });

    });

    // These are the only exported functions for this pseudo-module.
    return {
        'calculate_party_size': calculate_party_size,
        'go_quote': go_quote
    };
})(jQuery);
