$(function() {

  var to, searchResults;

  $('#search_form').submit(function()
  {
  	var today = new Date();
  	var month = today.getMonth()+1;
  	var year = today.getYear();
  	var day = today.getDate();

  	if (day < 10) day = "0" + day;
  	if (month < 10) month= "0" + month;
  	if (year < 1000) year += 1900;

  	if ($('#month').val() < month && $('#year').val() == year) {
  		alert('Your departure date cannot be before the current month. To continue, please correct this.');
  		$('#month').focus();
  		return false;
  	}

  	if ($('#destination').val() == '') {
  		alert('To continue, please select a cruise destination.');
  		$('#destination').focus();
  		return false;
  	}

    if ($('#destination').val() == to) {
      return false;
    } else {
      to = $('#destination').val();
    }

    if ($('#searchResults').is(':visible')) {
      $('div#sponsorBadges').show();
      if ($('div#sponsorBadges').height() == 0) $('div#sponsorBadges').height(100);
      $('div#sponsorBadges').block({
        message: '<img src="http://i.qs.stcdn.net/ajax-loader.gif" align="absmiddle" /> Updating. Please wait...',
        css: {
          border: '1px solid #aaa',
          padding: '8px'
        },
        overlayCSS: {
          backgroundColor: '#E3F0F6',
          opacity: 0.6
        }
      });
      $('#Continue').attr('disabled', true);
    }

    $('.fieldError').empty().hide();

    $.ajax({
      url: $(this).attr('action'),
      type: 'POST',
      data: $(this).serialize(),
      success: function(data, state, xhr){
        $('#oops').empty().hide();
        if (xhr.getResponseHeader('content-type') == 'application/json') {
          if (data.error) {
            if (_(data.error.field).isUndefined()) {
              $('#flashMessage').text(data.error.message).show();
            } else {
              $('#'+data.error.field).next().text(data.error.message).show();
            }
            $('#badges, #Continue').hide();
            $('#sponsorBadges').hide().unblock();
          } else {
            searchResults = data;
            updateResults();
            if (data.params.destination != 17 && data.params.destination != 21 && data.params.destination != 24) {
              var destination = data.places.destination;
            } else {
              var destination = null;
            }
            
            $('#searchResultsCallToAction span').text(destination == null ? "" : travel_guide_safe(destination));
            getDeals(searchResults.product, destination, destination);
            if (destination == null) {
              $('#advice').hide();
              $('#whereToGo').show();
            } else {
              getTravelGuide(searchResults.product, destination);
            }
            getTopHotels(destination);
          }
        } else {
          $('#oops').show().html(data);
          $('#badges, #Continue').hide();
          $('#sponsorBadges').unblock();
        }
      }
    });

    return false;
  });

  function updateResults() {
    var results = searchResults;
    $('#sponsorBadges #badges').empty();
    $('#oops').empty().hide();

    var partnerIds = [],
        ii = 1;

    for (var i=0; i < results.display.length; i++) {
      if (ii > 12) break;

      var div = $('<div>', { 'class': 'badge' })
      div.append($('<input>', {
        type: 'checkbox',
        value: product_path + "/rd/?" + buildUrl('display', i)
      }));
      div.append($('<img>', {
        src: 'http://i.qs.stcdn.net/logos/' + results.display[i].image.replace(/(\.jpg|\.gif|\.jpeg)$/, '_sm$1'),
        width: 90,
        height: 22
      }));
      if(ii%3 == 0 ) { div.addClass("last"); }
      div.appendTo('#sponsorBadges #badges');

      partnerIds.push({ category: 'cruises', partner_id: results.display[i].id });

      ii++;
    };

    if ($('#badges .badge').size() < 1) {
      $('#flashMessage').text("Sorry, but there are no partners who match your search criteria. Please amend your search and try again.").show();
      $('#badges, #Continue, #searchResultsCallToAction, #searchResults').hide();
      $('#sponsorBadges').unblock();
    } else {
      Omniture.trackQuickSearch(results, partnerIds);

      $('#flashMessage').hide();
      if ($('#searchResults').is(':visible')) $('div#sponsorBadges').unblock();        
      $('#Continue, #badges, #searchResultsCallToAction, #searchResults').show().attr('disabled', false);
    }
  }

  function buildUrl(type, i){
    return $.param($.extend({
      button_rank: i+1,
      button_max: searchResults[type].length,
      button_type: (type == 'display') ? 'badge' : type,
      name: searchResults[type][i].name,
      id: searchResults[type][i].id
    }, searchResults.params));
  }

  function checkAndUpdate(event) {
    if (!_(searchResults).isEmpty() && !_(searchResults.display).isEmpty()) {
      var field = $(this).attr('id');
      if (field != 'destination') searchResults.params[field] = $(this).val();
      if ($('#destination').val() != '') updateResults();
    } else {
      checkAndSubmit();
    }
  }

  $('#destination').change(checkAndSubmit);
  $('#length, #month, #year').change(checkAndUpdate);

});

function checkAndSubmit() {
  setTimeout(function(){
    if ($('#destination').val() != '') $('#search_form').submit();
  }, 200);	
}
