function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

jQuery(document).ready(function($) {

  // superfish menus
  $('ul#nav').superfish(
    { 
      delay:       1000,                           
      animation:   {opacity:'show'}, 
      speed:       'fast',                         
      autoArrows:  false,                          
      hoverClass	: 'sfHover',
      dropShadows: true                           
    }
  );

  // local_nav accordion
  $("div#local_nav ul li ul").hide();
  $("div#local_nav ul li.current_section ul").slideDown(0);
  $("div#local_nav ul li a.local-top-link").click(function(e) {
    $("div#local_nav ul li:not(.current_section) ul").slideUp("slow");
    if ( $(this).next('ul').html() && $(this).next('ul').css('display') == 'none') {
      $(this).next('ul').slideDown("slow");
      e.preventDefault();
    } else if ( $(this).next('ul').html() ) {
      e.preventDefault();
    }
  });

  // silly link img border fix
  $("div#content a img").parents("a").css({"border-bottom":"0px"}); /* need this for ie? and any img that sets border=0 */
    
  // cycle (http://malsup.com/jquery/cycle/options.html)
  $("#landing_gallery-slides").cycle({
    fx: 'fade',
    speed: 'fast',
    timeout: 0, // prevents auto cycling
    next: '#landing_gallery',
    pager: '#landing_gallery-nav',
    pagerAnchorBuilder: function(idx, slide) {
      // return selector string for existing anchor
      return '#landing_gallery-nav a:eq(' + idx + ')';
    }
  });
  $("#header_gallery-slides").cycle({
    fx: 'fade',
    speed: 'fast',
    timeout: 0, // prevents auto cycling
    next: '#header_gallery',
    pager: '#header_gallery-nav',
    pagerAnchorBuilder: function(idx, slide) {
      // return selector string for existing anchor
      return '#header_gallery-nav a:eq(' + idx + ')';
    }
  });
  // override cycle plugin hiding
  $.fn.cycle.flashpromocommonReset = function(curr,next,opts,w,h,rev) {
    $(opts.elements).not(curr).css('overflow', 'hidden');
    $(opts.elements).not(curr).css('height', '0px');
    opts.cssBefore.opacity = 1;
    opts.cssBefore.height = '380px';
    opts.cssBefore.width = '897px';
    opts.cssBefore.display = 'block';

    opts.cssAfter = opts.cssAfter || {};
    opts.cssAfter.overflow = 'hidden';
    opts.cssAfter.height = '0';
    $(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0));
    $(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1));
  };

  $.fn.cycle.transitions.flashfade = function($cont, $slides, opts) {
    $slides.not(':eq('+opts.currSlide+')').css('opacity',0);
    opts.before.push(function(curr,next,opts) {
      $.fn.cycle.flashpromocommonReset(curr,next,opts);
      opts.cssBefore.opacity = 0;
    });
    opts.animIn	   = { opacity: 1 };
    opts.animOut   = { opacity: 0 };
    opts.cssBefore = { top: 0, left: 0 };
  }

  // colorbox (http://colorpowered.com/colorbox/)
  $("a.colorbox").colorbox();
  $("a.gallery_photo-link").colorbox({rel:'photo_gallery', photo:true});
    // group inline photo gallery
  $("a.inline_photo_gallery-link").each(function(i) {
    $(this).siblings("a.photo-link").attr("rel", 'group'+i);
    $(this).siblings("a.photo-link").html("");
    $(this).siblings("a.photo-link:first").html($(this).html());
    $(this).hide();
    $("a.photo-link[rel='group"+i+"']").colorbox({photo:true, speed:200});
  });
    // single colorbox views
  $("a.colorbox-mov").each(function(i) {
    $(this).colorbox({iframe:true, speed:200, preloading:false, width:800, height:800});
  });
    

  // convert weather_widget f/c ( and save preference as cookie )
  function temp_convert(temp_unit) {
    $("span.temp_unit").removeClass("alt");
    $("strong#temp_digits").removeClass("farenheit");
    $("strong#temp_digits").removeClass("celsius");
    var temp = $("strong#temp_digits").text();
    if (temp_unit == "c") {
      // convert to celsius
      // [°C] = ([°F] - 32) × 5/9
      temp = Math.round((temp - 32) * 5/9);
      $("span#temp_unit-f").addClass("alt");
      $("strong#temp_digits").addClass("celsius");
    } else {
      // convert to farenheit
      // [°F] = [°C] × 9/5 + 32 
      temp = $("strong#temp_digits").attr("hold_f"); // temp * 9/5 + 32;
      $("span#temp_unit-c").addClass("alt");
      $("strong#temp_digits").addClass("farenheit");
    }
    $("strong#temp_digits").html(temp);
  }
  $("div#temp_unit-control").click(function(e) {
    var state = "c";
    if ( $(this).children("span.alt").attr('id') == 'temp_unit-c' ) {
      // convert to celsius
    } else {
      // convert to farenheit
      state = "f";
    }
    temp_convert(state)
    createCookie('temp_unit', state, 365);
  });
  $("strong#temp_digits").attr("hold_f", $("strong#temp_digits").text());
  $("div#temp_unit-control").append("|<span id='temp_unit-c' class='alt temp_unit'>c</span>");
  temp_unit = readCookie('temp_unit');
  if (temp_unit == null) {
  } else {
    if (temp_unit == 'c') {
      temp_convert(temp_unit)
    }
  }

  // lodging-page toggle descriptions
  $("div#lodging-page div.lodging_room-block").each(function() {
    var my_block = $(this);
    my_block.find("div.long_description").hide();
    my_block.find("a.toggle_description").click(function(e) {
      if ($(this).html() == "More Details") {
        my_block.find("div.long_description").show();
        my_block.find("p.short_description").hide();
        $(this).html("Less Details");
      } else {
        my_block.find("p.short_description").show();
        my_block.find("div.long_description").hide();
        $(this).html("More Details");
      }
      e.preventDefault();
    });
  });

        
      


  // equalize columns.
  $.fn.v_justify = function() {
    var min_height = 100;
    $(this).find("div.column").each(function() {
      var element = $(this);
      if (element.height() > min_height) {
        min_height = element.height();
      }
    });
    $(this).find("div.column").css({height: min_height+"px"});
  }
  $("div#bottom_promos").v_justify();

  // make a grid
  $.fn.grid_list = function() {
    var min_height = 10;
    var min_width = 10;
    $(this).find("li").each(function() {
      var element = $(this);
      if (element.height() > min_height) {
        min_height = element.height();
      }
      if (element.width() > min_width) {
        min_width = element.width();
      }
    });
    $(this).find("li").css({height: min_height+"px", width: min_width+"px"});
  }
  $("ul.float-grid").grid_list();
  $("div#local_top_menu ul").grid_list();

});

/* 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;
        }
        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;
        }

        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]
        );
        
        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);
$(window).load(function() {
  if (!($.browser.msie && ($.browser.version == '6.0'))) {
    $("#large_promo-slides").cycle({
      fx: 'flashfade',
      speed: 'fast',
      containerResize: false,
      timeout: 0, // prevents auto cycling
      pager: '#large_promo-nav',
      pagerAnchorBuilder: function(idx, slide) {
        // return selector string for existing anchor
        idx = idx + 1;
        return '#large_promo-nav li:eq(' + idx + ') a';
      }
    });
  } else {
    $("#large_promo-slides div.large_promo-slide").slice(1, $("#large_promo-slides div.large_promo-slide").length).remove();
    $("#large_promo-nav").remove();
  }
});
