$(function() {

  var to, searchResults, rowCount;

  $('#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()
      $('div#searchResults').block({
        message: '<img src="http://i.qs.stcdn.net/ajax-loader.gif" align="absmiddle" />&nbsp;&nbsp;Updating. Please wait...',
        css: {
          border: '1px solid #DDDDDD',
          padding: '12px',
          backgroundColor: '#EEEEEE'
        },
        overlayCSS: {
          backgroundColor: '#FFFFFF',
          opacity: 0.6
        }
      });
    }


    $('.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, #searchResultsHeader, #related_package, #badge-header').hide();
            $('#searchResults').unblock();
            $('#exampleBadges, #save70').show();
            $('#Continue').attr('src', $('#Continue').attr('src').replace('btn_compare.gif', 'btn_compare_gray.gif'));
          } else {
            var val = $('#destination').val();
            var destination = $("#destination option[value='"+val+"']").text();
            searchResults = data;
            updateResults();
            
            if (val != 17 && val != 21 && val != 24) {
              var destination = data.places.destination;
            } else {
              var destination = null;
            }
            
            getDeals(searchResults.product, destination, destination);
            if (destination != null) {
              updateTitle(travel_guide_safe(destination));
              getTravelGuide(destination);
              getTopHotels(destination);
            }
          }
        } else {
          $('#oops').show().html(data);
          $('#badges, #Continue, #searchResultsHeader, #related_package').hide();
          $('#searchResults').unblock();
        }
      }
    });

    return false;
  });

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

    var position = 1,
        partnerIds = [],
        bumped = [],
        bumpedCount = 0,
        justBumped = false;

    rowCount = ((searchResults.display.length/3)+'').split('.');
    if (rowCount[1] == undefined) {
      rowCount = rowCount[0];
    } else {
      rowCount = (rowCount[1] > 0) ? (rowCount[0]++)+1 : rowCount[1];
    }

    ib=0;
    for (var i=0; true; i++) {
      justBumped = false;
      
      log("looping " + i + " with position "+position+"...");
      
      if (position > 12) break;

      if (bumped[position] != undefined) {
        log("   Found fixed badge "+ bumped[position] +" at position " + position);
        partnerIds.push(buildHtml(bumped[position], position));
        log("   pushed!");
        bumpedCount--;
        justBumped = true;
        position++;
      }
      
      if (!results.display[i]) {
        if (bumpedCount > 0) {
          if (!justBumped) position++;
          log("   empty. continuing...");
          continue;
        } else {
          log("   empty. breaking!");
          break;
        }
      }

      var fixed = parseFloat(results.display[i].fixed);
      // If fixed but is not fixed to current position, we bump it
      if (fixed > 0 && position != fixed) {
        log("   fixed at " + results.display[i].fixed);
        bumped[fixed] = i;
        bumpedCount++;
        continue;
      }
      
      partnerIds.push(buildHtml(i, position));
      log("   pushed!");
      position++;
    };
    
    // Added to fix the initial display of badges issue
    $('#sponsorBadges #exampleBadges').hide();
    $('#sponsorBadges #badges').show();
    $('#targetPage').remove();

    // Added to fix the initial display of badges issue
    $('#sponsorBadges #exampleBadges').hide();
    $('#sponsorBadges #badges').show();
    $('#targetPage').remove();

    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, #searchResultsHeader, #searchResults').hide();
      $('#searchResults').unblock();
    } else {
      Omniture.trackQuickSearch(results, partnerIds);
      GoogleAnalytics.trackSearch(results);
      
      $('#flashMessage').hide();
      if ($('#searchResults').is(':visible')) $('div#searchResults').unblock();
      $('#Continue, #badges, #searchResultsHeader, #searchResults').show().attr('disabled', false);
      
      var src = $('#Continue').attr('src');
      $('#Continue').attr('src', src.replace('btn_compare_gray', 'btn_compare'));
      
      if ($('#save70').size() > 0) {
        $('#save70').hide();
        $('#badge-header').show();
      }
    }
  }
  
  // Builds the badge HTML
  //    +i+ - The index number of the searchResults.display hash element
  //    +position+ - The badge position
  var ib = 0;
  function buildHtml(i, position) {
    var div = $('<div>', { 'class': 'badge border-btm' });
    div.append(
      $('<div>', { 'class': 'checkbox' }).append($('<input>', {
        type: 'checkbox',
        'data-cid': searchResults.display[i].cid,
        value: product_path + "/rd/?" + buildUrl('display', i)
      }))
    );
    div.append($('<img>', {
      src: 'http://i.qs.stcdn.net/logos/' + searchResults.display[i].image.replace(/(\.jpg|\.gif|\.jpeg)$/, '_sm$1'),
      width: 90,
      height: 22
    }));
      
    var row = ib/rowCount;
    if (row >= rowCount && row <= rowCount+1) div.removeClass("border-btm");
    div.appendTo('#sponsorBadges #badges');
    if ((ib+1)%3 != 0) div.after($('<div>', { 'class': 'divider' }));

    ib++;
    return { category: 'cruises', partner_id: searchResults.display[i].id };
  }

  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,
      utm_source: 'TS_'+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);	
}

