// Spin.js jQuery plugin
$.fn.spin = function(opts) {
	this.each(function() {
		var $this = $(this),
		data = $this.data();	
		if (data.spinner) {
			data.spinner.stop();
			delete data.spinner;
		}
		if (opts !== false) {
			data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
		}
	});
	return this;
};

// Functions
function modal(id) {
	// Add modal to page
	$("body").prepend('<div id="modal"><\/div>');
	var html = "";			
	html += '<div class="loading"></div>'+"\n";
	html += '<div class="overlay"></div>'+"\n";
	$("#modal").html(html);
	
	$("#modal .loading").spin({
		lines: 12, // The number of lines to draw
		length: 5, // The length of each line
		width: 2, // The line thickness
		radius: 5, // The radius of the inner circle
		color: '#000', // #rgb or #rrggbb
		speed: 1, // Rounds per second
		trail: 60, // Afterglow percentage
		shadow: false // Whether to render a shadow
	});
	
	// Load modal content
	$("#modal .loading").load('/listing/modal/' + id, function() {
		$("#modal .loading").data().spinner.stop();
	});
	
	// Bind close events to modal, document
	$(document).keyup(function(e) {
		if (e.which == "27") {
			if ($("#modal").length > 0 && $("#modal").css('display') != "none") {
				$("#modal").remove();
			}
		}
	});
	$("#modal .overlay").live('click', function() {
		$("#modal").remove();
	});
	$("#modal .close a").live('click', function() {
		$("#modal").remove();
	});	
}

function modal_request(id) {
	$("#modal .loading").data().spinner.spin();
	var comment = $("#modal form textarea[name=comment]").val();
	var q = "&listing=" + id + "&comment=" + comment;
	
	$.ajax({type: "POST", url: "/listing/modal_request", data: q, dataType: "text",
		success: function (data, textStatus) {
			if (data == "1") {
				$("#modal .loading").load('/listing/modal_confirm/' + id, function() {
					$("#modal .loading").data().spinner.stop();
				});						
			} else {
				alert(data);							
				$("#modal .loading").html('<div class="content"><h2>Request Error</h2><div class="error"><p>There was an issue sending your request. Please try again.</p><button onclick="$(\'#modal\').hide();">Close</button></div></div>');
				return false;
			}
		}
	});
}

function modal_image(id) {
	// Add modal to page
	$("body").prepend('<div id="modal_image"><\/div>');
	var html = "";			
	html += '<div class="loading"></div>'+"\n";
	html += '<div class="overlay"></div>'+"\n";
	$("#modal_image").html(html);
	
	$("#modal_image .loading").spin({
		lines: 12, // The number of lines to draw
		length: 5, // The length of each line
		width: 2, // The line thickness
		radius: 5, // The radius of the inner circle
		color: '#000', // #rgb or #rrggbb
		speed: 1, // Rounds per second
		trail: 60, // Afterglow percentage
		shadow: false // Whether to render a shadow
	});
	
	// Load modal content
	$("#modal_image .loading").load('/listing/modal_image/' + id, function() {
		$("#modal_image .loading").data().spinner.stop();
	});
	
	// Bind close events to modal, document
	$(document).keyup(function(e) {
		if (e.which == "27") {
			if ($("#modal_image").length > 0 && $("#modal_image").css('display') != "none") {
				$("#modal_image").remove();
			}
		}
	});
	$("#modal_image .overlay").live('click', function() {
		$("#modal_image").remove();
	});
	$("#modal_image .close a").live('click', function() {
		$("#modal_image").remove();
	});
	$("#modal_image .additional a").live('mouseover', function() {
		var src = $(this).find("img").attr("longdesc");
		$("#modal_image .view img").attr("src", "/public/cache/image.php?width=600&image=" + src);
	});	
}

function modal_recommendations(id) {
	// Add modal to page
	$("body").prepend('<div id="modal"><\/div>');
	var html = "";			
	html += '<div class="loading"></div>'+"\n";
	html += '<div class="overlay"></div>'+"\n";
	$("#modal").html(html);
	
	$("#modal .loading").spin({
		lines: 12, // The number of lines to draw
		length: 5, // The length of each line
		width: 2, // The line thickness
		radius: 5, // The radius of the inner circle
		color: '#000', // #rgb or #rrggbb
		speed: 1, // Rounds per second
		trail: 60, // Afterglow percentage
		shadow: false // Whether to render a shadow
	});
	
	// Load modal content
	$("#modal .loading").load('/recommendations/modal/' + id, function() {
		$("#modal .loading").data().spinner.stop();
	});
	
	// Bind close events to modal, document
	$(document).keyup(function(e) {
		if (e.which == "27") {
			if ($("#modal").length > 0 && $("#modal").css('display') != "none") {
				$("#modal").remove();
			}
		}
	});
	$("#modal .overlay").live('click', function() {
		$("#modal").remove();
	});
	$("#modal .close a").live('click', function() {
		$("#modal").remove();
	});	
}

function modal_recommendation_request(id) {
	$("#modal .loading").data().spinner.spin();
	var comment = $("#modal form textarea[name=comment]").val();
	var q = "&account=" + id + "&comment=" + comment;
	
	if (comment.length < 1) {
		alert('Please provide a comment for your recommendation');
		return false;
	}
	
	$.ajax({type: "POST", url: "/recommendations/modal_request", data: q, dataType: "text",
		success: function (data, textStatus) {
			if (data == "1") {
				$("#modal .loading").load('/recommendations/modal_confirm/' + id, function() {
					$("#modal .loading").data().spinner.stop();
				});						
			} else {
				alert(data);							
				$("#modal .loading").html('<div class="content"><h2>Recommendation Error</h2><div class="error"><p>There was an issue sending your recommendation. Please try again.</p><button onclick="$(\'#modal\').hide();">Close</button></div></div>');
				return false;
			}
		}
	});
}

function favorites_add(id, company) {
	var q = "&account=" + id;
	$.ajax({type: "POST", url: "/favorites/add", data: q, dataType: "text",
		success: function (data, textStatus) {
			if (data == "1") {
				alert(company + ' has been added to your Favorites');				
			} else if (data == "2") {
				alert(company + ' is already one of your Favorites');
			} else {
				alert('Your favorite could not be added');
			}
		}
	});	
}

function favorites_remove(id, company) {
	if (confirm('Are you sure you want to delete ' + company + ' from your favorites?')) {
		window.location.href = '/favorites/remove/' + id;
	}
}

// Sidebar, Blog
var sidebar_blog_total = 0;
var sidebar_blog_interval = 0;
var sidebar_blog_length = 5000;
var sidebar_blog_page = 0;

function loadNextBlog() {
	var blog_next = sidebar_blog_page + 1;
	if (blog_next >= sidebar_blog_total) {
		blog_next = 0;
	}
	loadBlog(blog_next);
}
function loadPrevBlog() {
	var blog_prev = sidebar_blog_page - 1;
	if (blog_prev < 0) {
		blog_prev = sidebar_blog_total - 1;
	}
	loadBlog(blog_prev);
}
function loadBlog(index) {	
	if (index != sidebar_blog_page) {
		clearInterval(sidebar_blog_interval);
		sidebar_blog_page = index;
		$('#sidebar .blog .content_wrapper').stop(false, true).animate({marginLeft: (index * -288)});		
		updateBlogNav(index);
	}
}
function updateBlogNav(index) {
	sidebar_blog_interval = setInterval(loadNextBlog, sidebar_blog_length);
	$("#sidebar .blog li").each(function() {
		if ($(this).index() == index) {
			$(this).find("a").addClass("active");
		} else {
			$(this).find("a").removeClass("active");
		}
	});
}

// Document ready functions
$(document).ready(function() {
	$("#header .actions .blur input[type=text]").focus(function() {
		var form = $(this).parent().parent();
		form.find(".blur").hide();
		form.find(".category").show();
		form.find(".focus").show();
		$("#header .actions .focus input[type=text]").focus();
	});
	/* $("#header .actions form").mouseleave(function() {
		var form = $(this).parent().parent();
		form.find(".blur").show();
		form.find(".category").hide();
		form.find(".focus").hide();
	}); */
	$("#header .actions .focus input[type=submit]").click(function() {
		var keyword = $("#header .actions .focus input[type=text]").val();
		if (keyword.length < 2) {
			alert("Please enter at least two characters");
			$("#header .actions .focus input[type=text]").focus();
			return false;
		}
	});
	
	if ($("#sidebar .blog").length) {
		sidebar_blog_total = $("#sidebar .blog li").length;
		$("#sidebar .blog .content_wrapper").css("width", Number(sidebar_blog_total) * 288)
		$("#sidebar .blog li a").click(function() {
			var index = $(this).parent().index();		
			loadBlog(index);	
		});
		sidebar_blog_interval = setInterval(loadNextBlog, sidebar_blog_length);
	}
	
	$("#buy_guide .hide a").click(function() {
		$.ajax({type: "POST", url: "/buy/hide", data: "", dataType: "text",
			success: function (data, textStatus) {
				//alert(data);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//alert(XMLHttpRequest.responseText);
				//alert(errorThrown);
			}
		});
		$('#buy_guide').slideUp();
	});
	
	$("#buy .filters .all_size a").click(function() {
		var link = $(this);
		$('.size-expand').slideToggle('slow', function() {
			if ($(this).css("display") == "none") {
				link.text("All Sizes");
			} else {
				link.text("Hide All Sizes");
			}
		});
	});
	
	$("#buy .filters .all_type a").click(function() {
		var link = $(this);
		$('.type-expand').slideToggle('slow', function() {
			if ($(this).css("display") == "none") {
				link.text("All Types");
			} else {
				link.text("Hide All Types");
			}
		});
	});	
	
	$("#register select[name=country_id]").change(function() {
		if ($(this).val() == "232") {
			$('.state-dropdown').show();
			$('.state-input').hide();
		} else {
			$('.state-dropdown').hide();
			$('.state-input').show();
		}
	});
	if ($("#register select[name=country_id]").length > 0) {
		// Trigger onload
		if ($("#register select[name=country_id]").val() != "") {
			$("#register select[name=country_id]").change();
		}
	}
	$("#account select[name=country_id]").change(function() {
		if ($(this).val() == "232") {
			$('.state-dropdown').show();
			$('.state-input').hide();
		} else {
			$('.state-dropdown').hide();
			$('.state-input').show();
		}
	});
	if ($("#account select[name=country_id]").length > 0) {
		// Trigger onload
		if ($("#account select[name=country_id]").val() != "") {
			$("#account select[name=country_id]").change();
		}
	}
});
