// Settings
var use_fancy_animation = true;
var results_per_page = 16;

$.facebox.defaults = {
	opacity      : 0,
	overlay      : true,
	loadingImage : '/skins/default/images/loading.gif',
	closeImage   : '/skins/default/images/closelabel.gif',
	imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
	faceboxHtml  : '\
		<div id="facebox" style="display:none;"> \
			<div class="popup"> \
				<table> \
					<tbody> \
						<tr> \
							<td class="tl"/><td class="b"/><td class="tr"/> \
						</tr> \
						<tr> \
							<td class="b"/> \
							<td class="body"> \
								<div class="content"> \
								</div> \
							</td> \
							<td class="b"/> \
						</tr> \
						<tr> \
							<td class="bl"/><td class="b"/><td class="br"/> \
						</tr> \
					</tbody> \
				</table> \
			</div> \
		</div>'
};

// Globals

$(document).ready(function() {		
	/**************************************************************************
	* BINDINGS AND "LIVE" BINDINGS
	**************************************************************************/

	// Search submit
	$("#search .search-form").submit(function() {
		if($("#search-results .loading").css("display") == "none") {
			if($("input[name='search_terms']").attr("value") != "") {
			
				$("#search-results .init").hide();
				$("#search-results .loading").show();
				$("#search-results .no-results").remove();
				$("#results-list").remove();
				$("#search-results .more button").hide();

				// *** Post search ***
				$.post("/trade/search/", $(this).serialize(), function(data) {
					onSearchResults(data);
				});
			
				// analytics ajax event
				$.trackEvent('trade', 'click', 'search', $("input[name='search_terms']").attr("value"));
			} else {
				alert("Type the name of your phone, then click search.")
			}
		}

		return false;
	});

	$("#results-list .item").livequery('click', function(event) {
		url = $(this).attr('href') + "/true";
		
		$.facebox(function() {
			$.post(url, function(data) {
				if(data.length == 0) {
					$(document).trigger('close.facebox');

					if(use_fancy_animation) {
						var pos = $("#checkout").offset().top - 100;
						$("html,body").animate({scrollTop: pos + "px"}, 300);
					}
					
					updateCart();
					return false;
				}
							
				$.facebox(data);
			});
		});
		
		// analytics ajax event
		$.trackEvent('trade', 'click', 'add-device');
		
		return false;
	});
	
	$(".question-form").livequery('submit', function(event) {
		$(document).trigger('close.facebox');
		
		post_data = $(this).serialize();

		// Encapsulating facebox opens alert with loading graphic
		$.facebox(function() {
			$.post("/trade/questions/", post_data, function(data) {		
				if(data.length == 0) {
					$(document).trigger('close.facebox');
					updateCart();
					return null;
				}
				
				$.facebox(data);
			});
		});
		
		// analytics ajax event
		$.trackEvent('trade', 'click', 'questions-submit');
		
		return false;
	});

	$(".cart-delete").livequery('submit', function(event) {
		$.post("/trade/remove_item/", $(this).serialize(), function(data) {				
			updateCart();
		});
		
		// analytics ajax event
		$.trackEvent('trade', 'click', 'delete-device');
		
		return false;
	});	

	// Show and hide account fields
	$("input[name='account_type']").click(function() {
		// If the account type is changing, seem unint
		// $("li").removeClass("error");
		
		if($(this).attr("value") == "new") {
			$(".new-account-field").show();
			$(".existing-account-field").hide();
			// alert('new');
		} else {
			$(".new-account-field").hide();
			$(".existing-account-field").show();
			// alert('existing');
		}
	});
		
	// Show tooltips on questions
	$(".trade-questions li[tip]").livequery('mouseover', function(event) {
		tip = $(this).attr("tip");
					
		$(this).qtip({
			content: tip,
			position: {
				corner: {
					target: 'topMiddle',
					tooltip: 'bottomMiddle'
				}
			},
			style: { 
				name: 'cream',
				border: {
					width: 2,
					radius: 4
				},
				tip: {
					corner: 'bottomMiddle',
					size: {
						x: 18,
						y: 10
					}
				}
			},
			show: { ready: true }
		});
	});
	
	// Move focus to search box and shake
	$("#checkout .init button").livequery('click', function(event) {
		$("#search-results .init").show();
		$("#search-results .loading").hide();
		$("#results-list").empty();
		$("#search-form input").val('');
				
		if(use_fancy_animation) {
			var pos = $("#main").offset().top - 20;
			$("html,body").animate({scrollTop: pos + "px"}, 300);
			$("#search-form").effect("shake", { times: 5, distance: 5 }, 75, function() { 
				$("#search-form input").focus();
			});
		} else {
			$("#search-form input").focus();
		}
	});
	
	// Show more results
	$("#search-results .more button").click(function() {
		showMoreResults();		
		return false;
	});
	
	// Show tooltips on items
	// $("#search-results a[tip]").livequery('mouseover', function(event) {
	// 	tip = $(this).attr("tip");
	// 				
	// 	$(this).qtip({
	// 		content: tip,
	// 		position: {
	// 			corner: {
	// 				target: 'topMiddle',
	// 				tooltip: 'bottomMiddle'
	// 			}
	// 		},
	// 		style: { 
	// 			name: 'cream',
	// 			border: {
	// 				width: 2,
	// 				radius: 4
	// 			},
	// 			tip: {
	// 				corner: 'bottomMiddle',
	// 				size: {
	// 					x: 18,
	// 					y: 10
	// 				}
	// 			}
	// 		},
	// 		show: { ready: true }
	// 	});
	// });
	
	init();
});


/**************************************************************************
* CALLBACK FUNCTIONS
**************************************************************************/

// Callback function when search results are ready
function onSearchResults(data) {
	$("#search-results .loading").hide();
	$("#search-results").prepend(data);
	showAbbreviatedResults();
	if(use_fancy_animation) $("#search-results").effect("highlight", {}, 1000);
		
	return false;
}

function onCartUpdate(data) {	
	$("#checkout .loading").hide();
	$("#errorLi").remove();
	$("#cart").html(data);
	if(use_fancy_animation) $("#cart").effect("highlight", {}, 1000);

	if($("#cart-list").children().size() == 0)
		$("#checkout .init").show();
	else
		$("#checkout .init").hide();
	
	return false;
}


/**************************************************************************
* EVENT FUNCTIONS
**************************************************************************/

// Do initial variable setting here
function init() {
	$("input[name='account_type']:checked").trigger("click");
	
	showAbbreviatedResults();
}

// Reloads cart section via AJAX call
function updateCart() {	
	$.post("/trade/cart/true", null, function(data) {
		$("#checkout .loading").show();
		onCartUpdate(data);
	});
}

function showMoreResults() {
	if(use_fancy_animation)
		// $("#results-list li:hidden:lt("+results_per_page+")").effect("highlight", {}, 1000);
		$("#results-list li:hidden:lt("+results_per_page+")").fadeIn("normal");
	else
		$("#results-list li:hidden:lt("+results_per_page+")").show();

	if($("#results-list").children().length < results_per_page || $("#results-list li:hidden").length == 0)
		$("#search-results .more button").hide();
}

function showAbbreviatedResults() {	
	// make sure 'more' button only appears when necessary	
	results_to_hide = $("#results-list li:gt("+(results_per_page - 1)+")");
	if(results_to_hide.length > 0) {
		results_to_hide.hide();
		$("#search-results .more button").show();
	} else
		$("#search-results .more button").hide();
}