$(function() {
  $('#to_city').focus();

  var to, searchResults, rowCount;

  $('#search_form').submit(function()
  {
  	if ($('#to_city').value == '') {
  		alert('To continue, please enter your destination city.');
  		$('#to_city').focus();
  		return false;
  	}
  	if ($('#travelers').value < $('#rooms').value) {
      alert('The Number of rooms cannot be greater than the number of guests. Please correct this to continue.');
      $('#rooms').focus();
      return false;
    }
  	if (($('#travelers').value / $('#rooms').value) > 4) {
  		alert('Sorry, but no more than 4 guests can stay in a room. Please correct this to continue.');
  		$('#rooms').focus();
  		return false;
  	}
    if (!validateDates()) return false;

    if ($('#to_city').val() == to) {
      return false;
    } else {
      to = $('#to_city').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 ($('#to_city').val().length == 3) $('#to_city').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;
        }
      }
      
      // 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 min = parseFloat(results.display[i].hotel_min_rooms);
      if (!_(min).isNaN() && min > 0) {
	      if (parseFloat($('#rooms').val()) < min) continue;
      }

      var max = parseFloat(results.display[i].hotel_max_rooms);
      if (!_(max).isNaN() && max > 0) {
	      if (parseFloat($('#rooms').val()) > max) 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();

    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: 'hotels', 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() {
    if (!_(searchResults).isEmpty() && !_(searchResults.display).isEmpty()) {
      if (!validateDates()) return false;
      
      var field = $(this).attr('id');
      if (field != 'to_city') searchResults.params[field] = $(this).val();
      if ($('#to_city').val() != '') updateResults();
    } else {
      checkAndSubmit();
    }
  }

  $('#to_city').focusout(checkAndSubmit);
  $('#hotel_name, #rooms, #travelers, #depart_date, #return_date').change(checkAndUpdate);
  $('#depart_date, #return_date').bind('checkAndUpdate', checkAndUpdate);

});

function validateDates () {
	if (!departureDateValid('depart_date')) {
	  alert('Your chosen check-in date is invalid. To continue, please correct this.');
		$('#depart_date').focus();
		return false;
	}
	if (!returnDateValid('depart_date', 'return_date')) {
		alert('Your chosen check-out date is invalid. To continue, please correct this.');
		$('#return_date').focus();
		return false;
	}
	return true;
}

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

