$(document).ready(function() {
  $('ul.vacation_specials .edit').hide();
  $('ul.specials li.small').small_special();
  
  // booking engine ===========================================================
  // menu ---------------------------------------------------------------------
  $('#engine .book').hide();
  $('#engine .menu input').click(function() {
    $('#engine .book').hide();
    $('#engine .menu label').removeClass('selected');
    $(this).next().addClass('selected');
    $("#" + $(this).val()).show();
  });
  $('#engine .menu li:first-child input').click();
  
  // date fields --------------------------------------------------------------
  $('input.date').datepicker({
		numberOfMonths  : 2,
		showButtonPanel : true,
		dateFormat      : 'mm/dd/yy'
  });
  
  $('input.start').change(function() {
    var end = $('input.end', $(this).parents('form'));
    if(end.val() != 'mm/dd/yyyy') { return false; }
    end.val($(this).val());
  });
  
  // hotels -------------------------------------------------------------------
  // map date fields to wct date selectors
  $('#check_in').change(function() { $(this).convert_date('#doa_mm', '#doa_dd', '#doa_yy'); });
  $('#check_out').change(function() { $(this).convert_date('#dod_mm', '#dod_dd', '#dod_yy'); });
  
  // vacations ----------------------------------------------------------------
  $('#depart').change(function() { $(this).convert_date('#dateLeavingMonth', '#dateLeavingDay'); });
  $('#return').change(function() { $(this).convert_date('#dateReturningMonth', '#dateReturningDay'); });
  
  // cars ---------------------------------------------------------------------
  $('#pick_up_location').watermark('Airport code');
  $('#pick_up').change(function() { $(this).convert_date('#pudate_mo', '#pudate_dy'); });
  $('#drop_off').change(function() { $(this).convert_date('#dodate_mo', '#dodate_dy'); });  
  
  // deals --------------------------------------------------------------------
  // populate deals selectors from wctravel javascript
  var from = $('#from_state_or_region');
  for(var origin in originations) { from.append('<option value="' + origin + '">' + originations[origin] + '</option>'); }
  
  var to = $('#to_state_or_region');
  for(var state in states) { to.append('<option value="' + state + '">' + states[state].name + '</option>'); }
  
  var city = $('#to_city');
  city.reset = function() {
  	this.get(0).options.length = 0;
  	this.get(0).options[0] = new Option('Choose a city', 'all');
  	this.get(0).options[1] = new Option('Show all cities', 'all');
  }
  
  from.change(function() {
    var state_codes = states_by_orig[from.val()];
    city.reset();
  	to.get(0).options.length = 0;
  	to.get(0).options[0] = new Option('Choose a state or region', 'all');
  	for(var i in state_codes) { to.append('<option value="' + state_codes[i] + '">' + states[state_codes[i]].name + '</option>'); }
  });
  
  to.change(function() {
  	var cities = intersect_arrays(cities_by_orig[from.val()], states[to.val()].cities);
    city.reset();
    for(var i in cities) { city.append('<option value="' + cities[i] + '">' + destinations[cities[i]] + '</option>'); }
  });
  
  // attractions --------------------------------------------------------------
  $('#start').change(function() { $(this).convert_date('#from_mm', '#from_dd'); });
  $('#thru').change(function() { $(this).convert_date('#to_mm', '#to_dd'); });
  
  var all_categories = $('#ACTTYPE_all');
  var categories = $('input[id!="ACTTYPE_all"]', all_categories.parents('fieldset'));
  all_categories.click(function() { categories.attr('checked', ''); });
  categories.each(function() {
    $(this).click(function() { all_categories.attr('checked', ''); });
  })
  
  $('#engine ul.menu input[checked=checked]').click();
  
  // deal page ================================================================
  initialize_deal_images();
  
  // locations menu -----------------------------------------------------------
  var contents = [];
  $('ul.menu.locations li a').each(function(i) {
    var content = $($(this).attr('href'));
    content.hide().data('link', $(this));
    contents.push(content);
    
    $(this).click(function(i) {
      if(content.is(":visible")) return false;
      
      for(var i = 0; i < contents.length; i++) { contents[i].hide().data('link').removeClass('selected'); }
      content.show();
      $(this).addClass('selected');
      
      return false;
    });
  });
  
  var selected = $('ul.menu.locations a.selected');
  selected.get(0) ? selected.click() : $('a', $('ul.menu.locations li:first-child').next()).click();
  
  // sort specials ------------------------------------------------------------
  $('body.public ul.specials').specials_sorter();
});

// http://spudly.shuoink.com/2008/05/31/arrayintersection/
// tried to put on Array.prototype but messed up array defs for some reason?
function intersect_arrays( setA, setB ) {  
  var setA_seen = {};  
  var setB_seen = {};  
  for ( var i = 0; i < setB.length; i++ ) {  
    setB_seen[ setB[i] ] = true;  
  }  
  
  var intersection = [];  
  for ( var i = 0; i < setA.length; i++ ) {  
    if ( !setA_seen[ setA[i] ] ) {  
      setA_seen[ setA[i] ] = true;  
      if ( setB_seen[ setA[i] ] ) {  
        intersection.push( setA[i] );  
      }  
    }  
  }  
  return intersection;  
};

function initialize_deal_images() {
  $('.deal_images').each(function(i) {
    if($('ul.menu', $(this)).get(0)) { return true; }
    
    var deal_images_container = $(this).children('ul');
    var deal_images = $('li', deal_images_container);
    deal_images_container.after('<ul class="menu"></ul>');
    
    var deal_images_menu = deal_images_container.next();
    
    deal_images.each(function(i) {
      var image = $(this);
      
      image.hide();
      deal_images_menu.append('<li><a href="#" class="show_image" id="show_image_' + i + '" title="Show Image">' + (i+1) + '</a></li>');
      $('a#show_image_' + i).click(function() {
        if($(this).hasClass('selected')) return false;
        
        deal_images.hide();
        $('a.show_image').removeClass('selected');
        image.fadeIn();
        $(this).addClass('selected');
        return false;
      });
    });
    
    $('a#show_image_0').click();
  });
}

$.fn.extend({
  convert_date : function(month, day, year) {
    var segments = $(this).val().split('/');

    $(month).val(segments[0]);
    $(day).val(segments[1]);
    if(typeof year != 'undefined') { $(year).val(segments[2].replace(/20/, '')); }
  }
});

$.widget('ui.small_special', {
  _init: function() {
    var content = this.element;
    
    $('.description', content).hide();
    
    if(!$('a.expand', content).get(0))
      $('a.title', content).before('<a href="#" title="More Info" class="expand">+</a><a href="#" title="Less Info" class="contract">-</a>');
    
    $('a.expand', content).click(function() {
      $(this).hide();
      $(this).next().show();
      content.addClass('expanded');
      $('.description', content).show();
      return false;
    });
    
    $('a.contract', content).click(function() {
      $(this).hide();
      $(this).prev().show();
      content.removeClass('expanded');
      $('.description', content).hide();
      return false;
    }).hide();
  }
});

$.widget('ui.specials_sorter', {
  _init: function() {
    this.types = ['large', 'medium', 'small'];
    
    var specials = this;
    
    this.element.before('<ul class="sort menu"><li class="title">Sort by:</li><li><a href="#" class="sort asc" id="sort_by_price">Price (low-high)</a></li><li><a href="#" class="sort asc" id="sort_by_name">Name (a-z)</a></li></ul>')
    var sort_menu = this.element.prev();
    
    var click_sort = function(source, sort_method) {
      var ascending = source.hasClass('asc');
      var ordered   = [];

      for(var i = 0;i < specials.types.length;i++) {
        var group = [];
        
        $('li.' + specials.types[i], specials.element).each(function() { group.push($(this)) });
        group.sort(function(a, b) { return (ascending ? sort_method(a, b) : sort_method(b, a)); });
        for(var j = 0;j < group.length;j++) { ordered.push(group[j].clone()); }
      }
      
      $('li', specials.element).remove();
      for(var i = 0;i < ordered.length;i++) { specials.element.append(ordered[i].fadeIn('fast')); }
      $('li.small', specials.element).small_special();
      
      ascending ? source.addClass('desc').removeClass('asc') : source.addClass('asc').removeClass('desc');
    }
    
    $('a#sort_by_price', sort_menu).click(function() {
      click_sort($(this), function(a, b) {
        return parseInt($('.price:last-child', a).text().replace(/[^\-\d]/, '')) - parseInt($('.price:last-child', b).text().replace(/[^\-\d]/, ''));
      })
      $(this).hasClass('asc') ? $(this).text('Price (low-high)') : $(this).text('Price (high-low)');
      return false;
    });

    $('a#sort_by_name', sort_menu).click(function() {
      click_sort($(this), function(a, b) {
        return $('a.title', a).text() > $('a.title', b).text();
      })
      $(this).hasClass('asc') ? $(this).text('Name (a-z)') : $(this).text('Name (z-a)');
      return false;
    });
  }
});