jQuery(document).ready(function($) {
  
  // superfish menus
  $('ul#main-nav, ul#aux-nav').superfish(
    { 
      delay:       1000,                           
      animation:   {opacity:'show'}, 
      speed:       'fast',                         
      autoArrows:  false,                          
      hoverClass	: 'sfHover',
      dropShadows: true,
      onBeforeShow: function(){Cufon.refresh();},
      onHide: function(){Cufon.refresh();}
    }
  );
  
  var promo_state = 'fwd';

  $('div#hero_promo_slides').cycle({
    fx: 'fade',
    pagerAnchorBuilder: function(idx, slide) {
      // return selector string for existing anchor
      idx = idx + 1;
      return '#promo_nav div:eq(' + idx + ') a';
    },
    speed: 'fast',
    next: '#next_promo',
    prev: '#prev_promo',
    timeout: 20000
  });
  
  var pause = false;
  
  $('div#pause_promo').click(function(){
    if(pause == false) {
      $('div#hero_promo_slides').cycle('pause');
      $(this).addClass('active');
      pause = true;
    }
    else {
      $('div#hero_promo_slides').cycle('resume');
      $(this).removeClass('active');
      pause = false;
    }
  });  
  
  $('div#header_pause_promo').click(function(){
    if(pause == false) {
      $('div#content_media-block').cycle('pause');
      $(this).addClass('active');
      pause = true;
    }
    else {
      $('div#content_media-block').cycle('resume');
      $(this).removeClass('active');
      pause = false;
    }
  });  
  
  $('div#content_media-block').cycle({
    fx: 'fade',
    speed: 'fast',
    timeout: 20000,
    next: '#header_next_promo',
    prev: '#header_prev_promo'
  });
  
  $('div#next_promo, div#prev_promo, div#header_next_promo, div#header_prev_promo').mousedown(function(){
    $('.active').removeClass('active');
    $('div#content_media-block').cycle('resume');
    $(this).addClass('active');
    pause = false;
  });
  
  $('div#next_promo, div#prev_promo, div#header_next_promo, div#header_prev_promo').mouseup(function(){
    $('.active').removeClass('active');
    $('div#content_media-block').cycle('resume');
    $(this).removeClass('active');
    pause = false;
  });
  
  $.fn.cycle.transitions.scrollInDirection = function($cont, $slides, opts) {
    if (opts.nextSlide == opts.currSlide+1 || (opts.currSlide == $slides.length-1 && opts.currSlide - opts.nextSlide>1)) { // forward -->
      $cont.css('overflow','hidden');
      opts.before.push($.fn.cycle.commonReset);
      var h = $cont.height();
      opts.cssFirst = { left: 0 };
      opts.cssBefore= { left: 0, top: h };
      opts.animIn	  = { top: 0 };
      opts.animOut  = { top: 0-h };
    } else if (opts.nextSlide == opts.currSlide-1 || opts.currSlide == 0) {
      $cont.css('overflow','hidden');
      opts.before.push($.fn.cycle.commonReset);
      var h = $cont.height();
      opts.cssFirst = { left: 0 };
      opts.cssBefore= { left: 0, top: -h };
      opts.animIn	  = { top: 0 };
      opts.animOut  = { top: h };
    }
  };
  
  $('div#news_content').cycle({
    fx: 'scrollInDirection',
    next: '#next_news',
    prev: '#prev_news',
    timeout: 20000
  });
  
  $('div#Photo').cycle({
    fx: 'fade',
    timeout: 20000
  });
  
  // sidekick tabs
  $('.tabbed_child_promos .tab-menu a').bind('click', function(e){
    e.preventDefault();
    var panel_id = $(this).attr('href');
    $('.tab-panel').removeClass('active-panel');
    $(panel_id).addClass('active-panel');
    $('.tabbed_child_promos .tab-menu a').removeClass('active-tab');
    $(this).addClass('active-tab');
  });
  
  // set the value from the title
    $(".embedded_input_title").each(function () {
      $(this).attr("value", $(this).attr("title"));
    });

  // empty the field on click if it has default value
    $(".embedded_input_title").click(function () {
      if ($(this).attr("value") == $(this).attr("title")) {
        $(this).attr("value", '');
      }
    });

  // reset the field to default value on blur if it is empty
    $(".embedded_input_title").blur(function () {
      if (!$(this).attr("value")) {
        $(this).attr("value", $(this).attr("title"));
      }
    });

  // validate the fields
    $(".embedded_titles").submit(function() {

      // check email
      var email = $(this).find("input[name='email']").attr("value");
      var filter=/^.+@.+\..{2,3}$/;
      if (email) {
        if (!filter.test(email)) {
          alert("Please input a valid email address!");
          return false;
        }
      }

      // empty the field if the same value as title before submitting
      $(this).find(".embedded_input_title").each(function() {
        if ($(this).attr("value") == $(this).attr("title")) {
          $(this).attr("value", '');
        }
      });
      return true;
    });
    
    

  
    var DAYINMILISECS = ((1000 * 60) * 60) * 24;


    $("input.calendar_date").datepicker({minDate:'+0', defaultDate:'+0', onSelect: function(dateText, inst){
        var booking_block = $(this).parents("div.booking-block");
        my_date = new Date(dateText);
        var daterange_element = booking_block.find("input.daterange");
        if ($(this).is("input.departuredate")) {
          // $(this).parents("div.booking-block").find("input.arrivaldate").datepicker('option', 'maxDate', my_date);
          if (daterange_element.get() && (daterange_element.val() > 0)) {
            var my_date = new Date($(this).val());
            var past_date = new Date(my_date.getTime() - (daterange_element.val() * DAYINMILISECS));
            $(this).parents("div.booking-block").find("input.arrivaldate").datepicker('setDate', past_date);
          }
        } else {
          if (daterange_element.get()) {
            // maybe this isn't so useful...
            //update_departure_from_daterange(daterange_element);
          } else {
            $(this).parents("div.booking-block").find("input.departuredate").datepicker('option', 'minDate', my_date);
          }
        }
      }
    });
    function update_departure_from_daterange(daterange_element){
      var date_range = parseInt(daterange_element.val());
      if (date_range >= 1) {
        var booking_block = daterange_element.parents("div.booking-block");
        my_date = new Date(booking_block.find("input.arrivaldate").val());
        future_date = new Date(my_date.getTime()+(date_range * DAYINMILISECS));
        booking_block.find("input.departuredate").datepicker('setDate', future_date);
      } else {
        daterange_element.val("0");
      }
    }
    $("input.daterange").keyup(function(e){
      update_departure_from_daterange($(this));
    });


    $("div#booking_widget a.booking-link").bind('click', function(e){
      var booking_block = $(this).parents("div.booking-block");
      var booking_url = $(this).attr("href"); // includes constants like language, salesid, etc.
      booking_block.find("input, select").each(function(){
        var my_name = $(this).attr("name");
        var my_value = '';
        if ($(this).is("input")) {
          my_value = $(this).val();
        } else {
          my_value = $(this).find("option:selected").val();
        }
        booking_url += "&"+my_name+"="+encodeURIComponent(my_value);
      });
      window.open(booking_url, '_blank');
      e.preventDefault();
    });


    // handle find airport code links
    var find_airport = function(e) {
      var airport_input = $(this).siblings("input.airport_name");
      var airport_link = $(this);
      if (airport_input.val()) {
        airportlookup_xml = $(this).attr('href');
        $.ajax({
          url: airportlookup_xml,
          data: {searchairport:airport_input.val()},
          dataType: 'xml',
          success: airport_link.attr("id") == "airport_departure-link" ? handle_departure_response : handle_arrival_response,
          error: function(XMLHttpRequest, textStatus, errorThrown){
            alert(XMLHttpRequest+"\n"+textStatus+":"+errorThrown);
          },
          complete: function(XMLHttpRequest, textStatus){
            //alert('complete : '+textStatus);
          }
        });
      } else {

        alert('Nothing was entered in the lookup field.');
      }
      e.preventDefault();
    };
    function handle_airport_response(data, textStatus, airport_link) {
      // show a list of found airport codes that the user can select
      var airport_input = airport_link.siblings("input.airport_name");
      x = data.getElementsByTagName("Airport");

      if (x.length == 0) {
        alert('No match found. Please try again.');
      }
      else {
        airport_input.after("<select name='"+airport_input.attr("name")+"' class='airport_name'></select>");
        var airport_select = airport_input.siblings("select.airport_name");
        airport_input.remove();
        for (i=0; i<x.length; i++) {
          code = x[i].getAttribute("Code");
          city = x[i].getAttribute("City");
          region = x[i].getAttribute("Region");
          country = x[i].getAttribute("Country");
          name = x[i].getAttribute("Name");

          region_or_country = region ? region : country;
          airport_select.append("<option value='"+code+"' displayValue='"+city+", "+region_or_country+"'>"+city+", "+region_or_country+"</option>");
          airport_select.append("<option value='"+code+"' displayValue='"+name+"'> &gt;&gt;"+code+" "+name+"</option>");
        }
        airport_link.html("Change Airport");
        airport_link.unbind('click', find_airport);
        airport_link.bind('click', change_airport);
      }
    }
    var handle_departure_response = function(data, textStatus){
      var airport_link = $("body").find("a#airport_departure-link");
      handle_airport_response(data, textStatus, airport_link);
    };
    var handle_arrival_response = function(data, textStatus){
      var airport_link = $("body").find("a#airport_arrival-link");
      handle_airport_response(data, textStatus, airport_link);
    };
    var change_airport = function(e) {
      var airport_link = $(this);
      var airport_select = airport_link.siblings("select.airport_name");
      airport_select.after("<input type='text' class='airport_name' name='"+airport_select.attr("name")+"' value='"+airport_select.find("option:selected").attr("displayValue")+"'>");
      airport_link.html("Find Airport");
      airport_select.remove();
      e.preventDefault();
      airport_link.unbind('click', change_airport);
      airport_link.bind('click', find_airport);
    };
    $("div#booking_widget a.find_airport-link").bind('click', find_airport );

    // people fields and daterange
    $("div#booking_widget input.people, div#booking_widget input.daterange").keydown(function(e){
      var number_of_people = parseInt($(this).val());
      if (!number_of_people) { number_of_people = 0 }
      if (e.keyCode == 38) { // up
        $(this).val(number_of_people+1);
      }
      if (e.keyCode == 40 && number_of_people>0) { // down
        $(this).val(number_of_people-1);
      }
    });
    // handle child ages form for lodging
    $("div#booking_widget div#lodging-booking input[name='childcount']").keyup(function(e){
      $("div#lodging-booking-childages").show();
      var number_of_children = parseInt($(this).val());
      /*
      if (e.keyCode == 38) {
        $(this).val(number_of_children+1);
        number_of_children = number_of_children+1;
      }
      if (e.keyCode == 40) {
        $(this).val(number_of_children-1);
        number_of_children = number_of_children-1;
      }
      */

      var existing_selects = $("select.childage-select").length+1;
      for (i=existing_selects; i<=number_of_children; i++) { // add any fields
        $("div#booking_widget div#lodging-booking select[name='child1age']").clone().appendTo($("div#booking_widget div#lodging-booking div#lodging-booking-childages"));
        $("div#booking_widget div#lodging-booking select.childage-select:last").attr("name", 'child'+i+'age');
      }
      // or
      for (i=existing_selects; i>number_of_children; i--) { // remove extra fields
        if (i==1) {
          // do nothing
        } else {
          $("div#booking_widget div#lodging-booking select[name='child"+i+"age']").remove();
        }
      }
      if (number_of_children==0) {
        $("div#lodging-booking-childages").hide();
      }

    });

    $('.details').toggle(function(){
      $(this).parent().next('.full_description').show();
      $(this).text('Hide Details');
    },function(){
      $(this).parent().next('.full_description').hide();
      $(this).text('Room Details');
    });

    $('.options').toggle(function(){
      $(this).next('.room_options').hide();
      $(this).text('View Rooms and Pricing...');
    },function(){
      $(this).next('.room_options').show();
      $(this).text('Hide Rooms and Pricing...');
    });

    $('input.plan_arrival_date').datepicker({
      minDate:'+0', 
      defaultDate:'+0',
      onSelect: function(dateText, inst){
        /* on select, calculate departure date */
        var arrival_date = new Date($('input.plan_arrival_date').val());
        var departure_date = new Date(arrival_date.getTime() + ($('select#num_nights option:selected').val() * DAYINMILISECS));
        $('input.departuredate').val(parseInt(departure_date.getMonth()+1).toString() + '/' + departure_date.getDate() + '/' + departure_date.getFullYear());
        $('input.arrivaldate').val(parseInt(arrival_date.getMonth()+1).toString() + '/' + arrival_date.getDate() + '/' + arrival_date.getFullYear());
        $('input.nights').val(parseInt($('select#num_nights').val()));
      }
    });

    $('select#num_nights').change(function(){
      var arrival_date = new Date($('input.plan_arrival_date').val());
      var departure_date = new Date(arrival_date.getTime() + ($(this).val() * DAYINMILISECS));
      $('input.departuredate').val(parseInt(departure_date.getMonth()+1).toString() + '/' + departure_date.getDate() + '/' + departure_date.getFullYear());
      $('input.arrivaldate').val(parseInt(arrival_date.getMonth()+1).toString() + '/' + arrival_date.getDate() + '/' + arrival_date.getFullYear());
      $('input.nights').val(parseInt($(this).val()));
    });
    
    // equalize blocks.
    $.fn.v_justify = function(block_sel) {
      var min_height = 100;
      $(this).find(block_sel).each(function() {
        var element = $(this);
        if (element.height() > min_height) {
          min_height = element.height();
        }
      });
      $(this).find(block_sel).css({height: min_height+"px"});
    }
    
    
    // collapse.js
       // hide all collapse_hide_area and add toggle button for each
       $('.collapsible .collapse_hide_area').hide();
       $('.collapsible .collapse_show_area').prepend("<div class='wrapper-toggle'><a class='collapse_toggle' href=''><span>toggle</span></a></div>");
       $('.collapsible .collapse_show_button div').prepend("<a class='collapse_toggle' href=''><span>toggle</span></a>");

      // show collapse_hide_area that have show class and sync button
       $('.collapsible .collapse_hide_area.show').show();
       $('.collapsible .collapse_hide_area.show').parents(".collapsible").find("a.collapse_toggle").toggleClass('collapse_open');

      // handle click events
       $(".collapsible .collapse_toggle").click(function(event){
         $(this).parents(".collapsible").find("a.collapse_toggle").toggleClass('collapse_open');
         $(this).parents(".collapsible").children(".collapse_hide_area").toggle();
         // only track open events 
         if ($(this).parents(".collapsible").find("a.collapse_toggle").hasClass('collapse_open')) {
           report_header = $(this).parents(".collapsible").find("h2.report_header").text();
         }

         return false;
       });

      // collapse global
       $(".global_collapse_hide").click(function(event){
         $("a.collapse_toggle").removeClass('collapse_open');
         $(".collapsible .collapse_hide_area").hide();

         // Stop the link click from doing its normal thing
         return false;
       });
       $(".global_collapse_show").click(function(event){
         $(".collapsible .collapse_toggle").each(function(e){
          $(this).addClass('collapse_open');
          $(this).parents(".collapsible").children(".collapse_hide_area").show();
         });

         // Stop the link click from doing its normal thing
         return false;
       });
       $(".global_collapse_show").trigger('click'); // default to show all
    

    // lodging-page star rating
    var lightbox_auto_open = true;
    $(".lightcycle").delegate(".view-stars a", 'click', function(e){
      $(this).parents('.lightcycle').find('.view-stars a').removeClass("highlight");
      e.preventDefault();
      var star_rating = parseInt($(this).data('star_rating'));
      $(this).parents(".lightcycle").find('.view-stars a.lodging-star-'+star_rating).addClass("highlight");

      function destroy_and_clone(target) {
        // destroys the target parent's cycle galleria and clone's itself for future generations.
          var content_galleria = target.parents(".content");
          var content_galleria_id = content_galleria.attr('id');
          var cloned = $('#cloned-'+content_galleria_id);
          content_galleria.find(".galleria-slides").cycle('destroy');
          content_galleria.remove();
          cloned.show();
          cloned.attr('id', content_galleria_id);
          cloned.clone().attr('id', 'cloned-'+content_galleria_id).insertAfter(cloned).hide(); // cloning a clone.  What could possibly go wrong?
          return cloned;
      }
      var cloned = destroy_and_clone($(this));
      var thumbnail_filter = null;
      if ($(this).data('star_rating') != 'all') {
        thumbnail_filter = '.image-block-star_rating-'+star_rating;
      }

      cloned.cyclepager({
        dimensions:js_args,
        always_show_carousel: true,
        slideExpr: thumbnail_filter  // only select slides with this class ( set to null to select all children )
      });
      // activate the galleria_colorbox
      var width = js_args['width'];
      if (width) {
        width = js_args['width']+'px';
      }
      var height = js_args['height'];
      if (width) {
        height = js_args['height']+'px';
      }
      var thumbnail_height = js_args['thumbnail_height']+parseInt($(".galleria-title").css('height'));
      $(cloned).find("a.fullsize").galleria_colorbox({
        rel: 'nofollow', // don't group lightcycles
        open: lightbox_auto_open,
        href: cloned,
        inline: true,
        scrolling: false,
        photo: false,
        scalePhotos: false, // redundant
        innerWidth: width,
        //innerHeight: parseInt(height)+parseInt(thumbnail_height)+100,
        current: "",
        onComplete: function(e){
          $("#galleria_cboxTitle").hide();
          var loaded_height = $("#galleria_cboxLoadedContent .content").height();
          $("#galleria_cboxLoadedContent").height(loaded_height);
        },
        onClosed: function(e){
          $("#galleria_cboxTitle").show();
          // recreate cyclepager and show all slides
          // need to actually reclone the cloned clone... but don't auto open the lightbox.
          lightbox_auto_open = false; 
          $(this).parents('.lightcycle').find('.view-stars a.lodging-star-all').click();
          lightbox_auto_open = true;
        }
      });


    });
    
    
    $(window).load(function() {
      // resize elements here
      $("div#forecasts-group").v_justify("div.forecast-box");
    });
    
});

