// method to tell jQuery send the auth token as needed, see:
// http://henrik.nyh.se/2008/05/rails-authenticity-token-with-jquery
// http://www.viget.com/extend/ie-jquery-rails-and-http-oh-my
$(document).ajaxSend(function(event, request, settings) {
  if (settings.type == 'GET' || settings.type == 'get' || typeof(AUTH_TOKEN) == "undefined") { return; }
  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

function formatAutocompleteItem(row) {
	return row[0] + "<br><i>" + row[1] + "</i>";
}

function production_environment() {
	return (window.location.hostname === 'www.dealbase.com');
}

function create_cookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000)); //time in milliseconds
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}


$(document).ready(function() {
	// Set the date format we want for use in JavaScript and jQuery dates
	Date.format = 'mmm d, yyyy';
	
	// Setup jQuery AJAX requests
	jQuery.ajaxSetup({ beforeSend: function(xhr) {
		xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
	} });

	$.ajaxSetup({
		headers: {"X-Requested-With":"XMLHttpRequest"}
	});
	
	function do_search(e) {
	  var search_text = $.trim($('input#omniscient_search').val());
	  if (search_text.length > 0)
	    $.get("/destinations/find_deals_url?name=" + search_text, null, search_results, 'json');
	}
	
	function search_results(data, textStatus) {
	  if (data.url === '')
	    google_cse_search();
	  else
	    document.location.href = data.url;
	}
	
	function google_cse_search(e) {
		$('input#cse_search').attr("value", $('input#omniscient_search').val());
		$('form#cse-search-box').submit();
	  return false;
  	}

	function round_corners() {
		if (!($.browser.msie && $.browser.version < 7)) { //If not ie6, round the search corner
			$('#main_search').corner();
		}
		if ($.browser.mozilla || $.browser.safari) { //if mozilla or safari, round everything
  		$('#alerts_signup').corner();
			$('#stats1').corner();
			$('#stats2').corner();			
		}
	}
	
	// Round DIVS on front page
	if ($('#main_search').length > 0) {
	  round_corners();
	}
	
	// Enable and check for lightbox
	if ($('[id*=show_lightbox]').length > 0)
	{
		jQuery('[id*=show_lightbox]').click(function(){
			$('#lightbox_source_name').text($(this).attr('id').substr(14)); //append out the name of the hotel or source
		  jQuery.facybox({ div: '#lightbox_email_pop'});
			if (production_environment()) {
				pageTracker._trackPageview('/alerts-lightbox' + window.location.pathname);
			}
		});
		$('.close').livequery('click', function(){
			create_cookie("alert_lightbox", "true", 7);
			$('[id*=show_lightbox]').unbind('click'); //we don't want to show the pop-up again if they re-click 'get this deal' on same page load
		});
	}
	
	//Check Rates Lightbox
	if ($('#show_check_rates').length > 0)
	{
		jQuery('#show_check_rates').click(function(){
		  jQuery.facybox({ div: '#check_rates_pop'});
			if (production_environment()) {
				pageTracker._trackPageview('/OT-hotel' + window.location.pathname);
			}
		});
	}
	
	$('input#omniscient_search').keypress(function(e) { if (e.which==13) { do_search(e); } });
	$('#search_submit').click(do_search);
  	
	$('input#omniscient_search').autocomplete("/search_all", 
																						{ matchContains:1, 
                                            	delay:40,
																							minChars:3, 
																							matchSubset:false, 
																							cacheLength:1,
																							max:10,
																							mustMatch:false,
																							selectFirst:false,
																							scrollHeight:280 });
	$('input#omniscient_search').result(function(event, data, formatted) {
		if (data[1] != 0) {
  	  $('input#omniscient_search').unbind('keypress');
  	  document.location.href = data[1];
	  }
  });
  
  $('#home #user_email').example('Enter your email address');
	
	function remove_favorite_success_handler(msg, deal_id) {
		// Remove the heart
		$('div#favorite-' + deal_id).after(msg).remove();
		// If we're on the My Favorites page, then also remove the deal card
		if (document.location.href.match(/\/favorites$/)) {
			$('div.mini-card.' + deal_id).parent().hide();
		}
	}
	
	$('.create_favorite_button').livequery('click', function() {
		var deal_id = $(this).attr("id").split('-')[1];
		$.ajax({ type: "POST",
						 url: "/favorites",
						 data: "favorite[deal_id]=" + deal_id,
						 success: function(msg){ $('div#favorite-' + deal_id).after(msg).remove(); } });
		$('div.mini-card.' + deal_id).addClass("favorite_deal");
		return false;
	});
	
	$('.remove_favorite_button').livequery('click', function() {
		var deal_id = $(this).attr("id").split('-')[1];
		var delete_url = this.href;
		$.ajax({ type: "DELETE",
						 url: delete_url,
						 data: "method=delete",
						 success: function(msg){ remove_favorite_success_handler(msg, deal_id); } });
		$('div.mini-card.' + deal_id).removeClass("favorite_deal");
		return false;
	});

	$('span.link').click(function() {
		parts = $(this).attr('id').split('_');
		switch(parts[0]) {
			case "edit":
				document.location.href = '/' + parts[1] + 's/' + parts[2] + '/edit';
				break;
			case "history":
				document.location.href = '/' + parts[1] + 's/history/' + parts[2];
				break;
			case "revert":
				if (confirm('Are you sure you want to revert this hotel?')) {
					document.location.href = '/' + parts[1] + 's/revert/' + parts[2];
				}
				break;
			case "copy":
				document.location.href = '/' + parts[1] + 's/copy/' + parts[2];
				break;
		}
	});
		
});

