$(function() {
  $('#from_code').focus();
  
  var from, to, searchResults, rowCount;

  $('#search_form').submit(function()
  {
  	if ($('#from_code').val() == '') {
  		alert('To continue, please enter departure city or airport code.');
  		$('#from_code').focus();
  		return false;
  	}
  	if ($('#to_code').val() == '') {
  		alert('To continue, please enter destination city or airport code.');
  		$('#to_code').focus();
  		return false;
  	}
  	if ($('#from_code').val() == $('#to_code').val() || extractIATACode($('#from_code').val()) == extractIATACode($('#to_code').val())) {
  		alert('To continue, your destination city or airport code must be different than the departure city or airport code.');
  		$('#to_code').val('').select();
  		return false;
    }
    if (!validateDates()) return false;

    if ($('#from_code').val() == from && $('#to_code').val() == to) {
      return false;
    } else {
      from = $('#from_code').val();
      to = $('#to_code').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 {
            searchResults = data;
            updateResults();
            updateTitle(travel_guide_safe(data.destinationForContent));
            getDeals(searchResults.product, data.places.destination, data.destinationForContent);
            getTravelGuide(data.destinationForContent);
            getTopHotels(data.destinationForContent);
          }
        } 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();

    if ($('#from_code').val().length == 3) $('#from_code').val(results.places.origin.display_name);
    if ($('#to_code').val().length == 3) $('#to_code').val(results.places.destination.display_name);

    var departDate = Date.parse($('#depart_date').val()),
        returnDate = Date.parse($('#return_date').val()),
        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;
        }
      }

      if (departDate.equals(returnDate) && !parseFloat(results.display[i].accepts_same_day_return)) {
        continue;
      }

      // depart_date at least min_days_in_advance
      var min = parseFloat(results.display[i].min_days_in_advance);
      if (!_(min).isNaN() && min > 0) {
        if (departDate.compareTo(Date.today().add(min).days()) < 0) continue;
      }

      // depart_date at no more than max_days_in_advance
      var max = parseFloat(results.display[i].max_days_in_advance);
      if (!_(max).isNaN() && max > 0) {
        if (departDate.compareTo(Date.today().add(max).days()) > 0) continue;
      }

      // difference between depart_date and return_date no more than max_duration
      var max = parseFloat(results.display[i].max_duration);
      if (!_(max).isNaN() && max > 0) {
	      if (returnDate.compareTo(Date.parse($('#depart_date').val()).add(max).days()) > -1) continue;
      }

      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: 'packages', 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,
      route_id: searchResults[type][i].route
    }, searchResults.params));
  }

  function checkAndUpdate(event) {
    if (!_(searchResults).isEmpty() && !_(searchResults.display).isEmpty()) {
      if (!validateDates()) return false;
      
      var field = $(this).attr('id');
      if (field != 'to_code' || field != 'from_code') {
        searchResults.params[field] = $(this).val();
      }

      if ($('#from_code').val() != '' && $('#to_code').val() != '') {
        updateResults();
      }
    } else {
      $('#search_form').submit();
    }
  }

  $('#from_code, #to_code').focusout(checkAndSubmit);
  $('#travelers').change(checkAndUpdate);
  $('#depart_date, #return_date').bind('checkAndUpdate', checkAndUpdate);

});

function validateDates () {
  if (!departureDateValid('depart_date')) {
    alert("We cannot accept a departure date in the past or\nmore than 330 days in the future. Dates must be in the form of mm/dd/yy. To continue, please correct the departure date.");
    $('#depart_date').focus();
    return false;
  }
  if (!returnDateValid('depart_date', 'return_date')) {
    alert('Your chosen return date is invalid. To continue, please correct this.');
    $('#return_date').focus();
    return false;
  }
	if (!dateDayDifference('depart_date', 'return_date')) {
		alert("Packages cannot be booked for longer than 26 days. Please select an earlier return date.");
		$('#return_date').focus();
		return false;
	}
	return true;
}

function checkAndSubmit() {
  if (!validateDates()) return false;
  setTimeout(function(){
    if ($('#from_code').val() != '' && $('#to_code').val() != '') $('#search_form').submit();
  }, 200);	
}

