$(function(){

	// Change heading fonts with cufon
	// ==================================================
	Cufon.replace('h1');
	Cufon.replace('h2');
	Cufon.replace('#footerNav h5');
	Cufon.replace('#sponsorHeading h5');


	
	// toggle for show/hide footer links
	// ==================================================
	if ($("#footerShowHide").length > 0) {
		
		function footerShowHide(){
			if($("#footerShowHide a").attr("rel") == "invisible"){
				$("#footerNavWrap").slideDown(200, function(){
					$.scrollTo( '#footerShowHide', 800);
					$("#footerShowHide").remove();
				});
			};
		};
		
		// if it's the home page, do this
		if($("#bookShowcase").length > 0) {
			$("#footerShowHide").remove();
		} 
		// otherwise, do this
		else 
		{
			$("#footerShowHide a").text("Where to next?").attr("rel", "invisible").click(function(){
				footerShowHide();
				return false;
			});
			$("#footerNavWrap").hide();
		};
		
	};
	


	// Auto cycle through the books showcase on home page
	// ==================================================
	if ($("#bookShowcase").length > 0) {
		$("#bookShowcase").cycle({
			fx: 'fade',
			timeout: 6000,
			pager: '#slideNumber',
			pause: 1
		});
	};

	
	
	// Display authors in a carosel format and use tooltips
	// ==================================================
	if ($("#authorScroll").length > 0) {

		// if looking at an author, find current author in carossel and show that slide
		var startingAuthorSlide = 0;
		if ($("#authorContent").length > 0) {
			var thisAuthor = $("#authorContent").attr("rel");
			var startingAuthorSlide = $("#" + thisAuthor).parent().attr("rel");
		};

		$("#authorScroll").cycle({
			fx: 'scrollHorz',
			timeout: 0,
			next: ".authorsNext",
			prev: ".authorsPrev",
			startingSlide: startingAuthorSlide
		});
		
		$("#authorScroll .authorPic").each(function(){
			var thisAuthorID = $(this).attr("rel");
			
			$(this).tooltip({
				tip: '#ttAuthor' + thisAuthorID, 
				offset: [10, 0],
				position: 'bottom center', 
				effect: 'slide',
				predelay: 300
			});
		});
	};
	


	// Display tooltips for videos
	// ==================================================
	if ($(".videoList").length > 0) {

		$(".videoList .videoPic").each(function(){
			var thisVideoID = $(this).attr("id");
			//console.log(thisVideoID);
			
			$(this).tooltip({
				tip: '#ttVideo' + thisVideoID, 
				offset: [10, -110],
				position: 'bottom right', 
				effect: 'slide',
				predelay: 300
			});
		});
	};
	
	
	
	// Display tooltips for download (look inside)
	// ==================================================
	if ($("#bookShowcase").length > 0) {

		$("#bookShowcase .lookInside a").each(function(){
			var thisDownloadID = $(this).attr("rel");
			//console.log(thisVideoID);
			
			$(this).tooltip({
				tip: '#ttDownload' + thisDownloadID, 
				offset: [10, -110],
				position: 'bottom right', 
				effect: 'slide',
				predelay: 300
			});
		});
	};



	// Display books in a carosel format and use tooltips
	// ==================================================
	if ($(".bookScroll").length > 0) {
		
		// if looking at a book, find current book in carossel and show that slide
		var startingBookSlide = 0;
		if ($("#bookContent").length > 0) {
			var thisBook = $("#bookContent").attr("rel");
			var startingBookSlide = $("#" + thisBook).parent().attr("rel");
		};

		$(".bookScroll").cycle({
			fx: 'scrollHorz',
			timeout: 0,
			next: ".booksNext",
			prev: ".booksPrev",
			startingSlide: startingBookSlide
		});
		
		$(".bookScroll .bookPic").each(function(){
			var thisBookID = $(this).attr("rel");
			//console.log(thisbookID);
			
			$(this).tooltip({
				tip: '#ttBook' + thisBookID, 
				offset: [13, 0],
				position: 'bottom center', 
				effect: 'slide',
				predelay: 300
			});
		});
	};
	
	
	
	// Scroll the page when user clicks specific # tags
	// ==================================================
	if ($("#reviewShortcuts").length > 0) {

		$("#bookReviewsShortcut").click(function(){
			$.scrollTo('#bookReviews', 800);
			return false;
		});
		
		$("#writeReviewShortcut").click(function(){
			$.scrollTo('#writeReview', 800);
			return false;
		});
		
	};
	if ($("#articleShortcuts").length > 0) {

		$("#commentsReadShortcut").click(function(){
			$.scrollTo('#commentsRead', 800);
			return false;
		});
		
		$("#commentsWriteShortcut").click(function(){
			$.scrollTo('#commentsWrite', 800);
			return false;
		});
		
	};
	


	// attach fancybox to popup links
	// ==================================================
	$("a.contactPopUp").fancybox({
		'scrolling'			: 'no',
		'titleShow'     	: false,
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'elastic',
		'width'				: 620,
		'height'			: 235,
		'autoDimensions'	: false,
		'overlayOpacity'	: 0.7,
		'overlayColor'		: "#000",
		'hideOnOverlayClick': true,
		'hideOnContentClick': false,
		'enableEscapeButton': true,
		//'modal'				: true,
		'centerOnScroll'	: false,
		'padding'			: 10,
		'onComplete'		: function(){
			
			// submit contact form via ajax
			$("#contactSubmit").click(function(){
				var thisName = $("#form_name").val();
				var thisEmail = $("#form_email").val();
				var thisPhone = $("#form_phone").val();
				var thisContent = $("#form_content").val();

				$.ajax({
					type: "POST",
					url: "" + $("#contactForm form").attr("action"),
					data: "form_name=" + thisName + "&form_email=" + thisEmail + "&form_phone=" + thisPhone + "&form_content=" + thisContent + "",
					dataType: "xml",
					error: function() {
						// an internal error has occurred
						console.log("internal error - please try again later");
					},
					success: function(xml) {

						// get status response
						var statusMsg = $(xml).find("status").text();

						// set response status message
						if (statusMsg == "success") { 
							// all completed successfully, display the success messages
							if ($("#contactErrors").length > 0) {
								$("#contactErrors").slideUp(500, function(){
									$("#contactErrors").remove();
									var successBox = '<div id="contactErrors" class="successWrap popupSuccess hide"><ul>Thank you, your message has been sent successfully!</ul></div>'
									$("#contactFormErrorWrap").prepend(successBox).animate({opacity: 1}, 300, function(){
										$("#contactErrors").slideDown(function(){
											$("#contactErrors").animate({opacity: 1}, 2000, function(){
												parent.$.fancybox.close();
											});
										});
									});
								});
							} else {
								var successBox = '<div id="contactErrors" class="successWrap popupSuccess hide"><ul>Thank you, your message has been sent successfully!</ul></div>'
								$("#contactFormErrorWrap").prepend(successBox).animate({opacity: 1}, 300, function(){
									$("#contactErrors").slideDown(function(){
										$("#contactErrors").animate({opacity: 1}, 2000, function(){
											parent.$.fancybox.close();
										});
									});
								});
							};
						} else if (statusMsg == "error") { 
							// an error has occurred, display the error messages
							if ($("#contactErrors").length > 0) {
								$("#contactErrors").slideUp(500, function(){
									$("#contactErrors").remove();
									var errorBox = '<div id="contactErrors" class="errorWrap popupErrors hide"><ul>' + $(xml).find("error_message").text() + '</ul></div>'
									$("#contactFormErrorWrap").prepend(errorBox).animate({opacity: 1}, 300, function(){
										$("#contactErrors").slideDown(function(){
											$("#contactErrors").wait(3000).slideUp();
										});
									});
								});
							} else {
								var errorBox = '<div id="contactErrors" class="errorWrap popupErrors hide"><ul>' + $(xml).find("error_message").text() + '</ul></div>'
								$("#contactFormErrorWrap").prepend(errorBox).animate({opacity: 1}, 100, function(){
									$("#contactErrors").slideDown(function(){
										$("#contactErrors").wait(3000).slideUp();
									});
								});
							};
						};
					}
				});

				return false;

			});
			
		}
	});

	$("a.videoPopUp").fancybox({
		'scrolling'			: 'no',
		'titleShow'     	: false,
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'elastic',
		'width'				: 400,
		'height'			: 300,
		'autoDimensions'	: false,
		'overlayOpacity'	: 0.7,
		'overlayColor'		: "#000",
		'hideOnOverlayClick': true,
		'hideOnContentClick': false,
		'enableEscapeButton': true,
		//'modal'				: true,
		'centerOnScroll'	: false,
		'padding'			: 0		 
	});
	
	$("a.newsletterPopUp").fancybox({
		'scrolling'			: 'no',
		'titleShow'     	: false,
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'elastic',
		'width'				: 410,
		'height'			: 110,
		'autoDimensions'	: false,
		'overlayOpacity'	: 0.7,
		'overlayColor'		: "#000",
		'hideOnOverlayClick': true,
		'hideOnContentClick': false,
		'enableEscapeButton': true,
		'centerOnScroll'	: false,
		'padding'			: 10,
		'onComplete'		: function(){
			
			// submit contact form via ajax
			$("#newsletterSubmit").click(function(){
				var thisName = $("#form_name").val();
				var thisEmail = $("#form_email").val();
				
				$.ajax({
					type: "POST",
					url: "/ajax/send/newsletter",
					data: "form_name=" + thisName + "&form_email=" + thisEmail + "",
					dataType: "xml",
					error: function() {
						// an internal error has occurred
						console.log("internal error - please try again later");
					},
					success: function(xml) {

						// get status response
						var statusMsg = $(xml).find("status").text();

						// set response status message
						if (statusMsg == "success") { 
							// all completed successfully, display the success messages
							if ($("#newsletterErrors").length > 0) {
								$("#newsletterErrors").slideUp(500, function(){
									$("#newsletterErrors").remove();
									var successBox = '<div id="newsletterErrors" class="successWrap popupSuccessSmall hide"><ul>Thank you, you have been subscribed!</ul></div>'
									$("#newsletterFormErrorWrap").prepend(successBox).animate({opacity: 1}, 300, function(){
										$("#newsletterErrors").slideDown(function(){
											$("#newsletterErrors").animate({opacity: 1}, 2000, function(){
												parent.$.fancybox.close();
											});
										});
									});
								});
							} else {
								var successBox = '<div id="newsletterErrors" class="successWrap popupSuccessSmall hide"><ul>Thank you, you have been subscribed!</ul></div>'
								$("#newsletterFormErrorWrap").prepend(successBox).animate({opacity: 1}, 300, function(){
									$("#newsletterErrors").slideDown(function(){
										$("#newsletterErrors").animate({opacity: 1}, 2000, function(){
											parent.$.fancybox.close();
										});
									});
								});
							};
						} else if (statusMsg == "error") { 
							// an error has occurred, display the error messages
							if ($("#newsletterErrors").length > 0) {
								$("#newsletterErrors").slideUp(500, function(){
									$("#newsletterErrors").remove();
									var errorBox = '<div id="newsletterErrors" class="errorWrap popupErrorsSmall hide"><ul>' + $(xml).find("error_message").text() + '</ul></div>'
									$("#newsletterFormErrorWrap").prepend(errorBox).animate({opacity: 1}, 300, function(){
										$("#newsletterErrors").slideDown(function(){
											$("#newsletterErrors").wait(3000).slideUp();
										});
									});
								});
							} else {
								var errorBox = '<div id="newsletterErrors" class="errorWrap popupErrorsSmall hide"><ul>' + $(xml).find("error_message").text() + '</ul></div>'
								$("#newsletterFormErrorWrap").prepend(errorBox).animate({opacity: 1}, 100, function(){
									$("#newsletterErrors").slideDown(function(){
										$("#newsletterErrors").wait(3000).slideUp();
									});
								});
							};
						};
					}
				});

				return false;

			});
			
		}
	});
	
	
	
	
	// send comments forms via ajax
	// ==================================================
	if ($("#commentsForm").length > 0) {
		
		// function to add a comment to blog pages
		function addComment(commentName,commentMessage){
			
			// build comment block to be inserted onto page
			var commentBlock = '<div id="comment-latest" class="commentSingle hide"><div class="commentDetails"><div class="commentGravatar"><img src="http://www.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s=46" alt="'+ commentName +'" width="46" height="46" /></div><div class="commentAuthor">'+ commentName +'</div><div class="commentDate">Posted just now!</div><div class="clear"></div></div><div class="commentContent">'+ commentMessage +'</div></div>';

			// check if no comments paragraph is there and get rid of it
			if ($("#comments #noComments").length > 0) {
				$("#comments #noComments").slideUp(function(){
					$("#comments #noComments").remove();
					$("#comments").append(commentBlock).animate({opacity: 1}, 300, function(){
						$("#comments #comment-latest").slideDown();
					});
				});
			} else {
				$("#comments").append(commentBlock).animate({opacity: 1}, 300, function(){
					$("#comments #comment-latest").slideDown().removeAttr("id");
				});
			};
			
			// blank the form fields and lock the submit button
			$("#comment_name").val("");
			$("#comment_email").val("");
			$("#comment_www").val("");
			$("#comment_content").val("");
			$("#commentsSubmit").attr("disabled","disabled").animate({ opacity: 1 }, 10000, function(){
				$("#commentsSubmit").removeAttr("disabled");
			});
			
		};
		
		
		// if the page has just loaded and there are errors on it, scroll to them
		if($("#form_errors").length > 0) {
			$("#form_errors").animate({ opacity: 1 }, 500, function(){
				$.scrollTo('#commentsForm', 800);
			})
		};
		
		// submit comments form via ajax
		$("#commentsSubmit").click(function(){
			var thisName = $("#comment_name").val();
			var thisEmail = $("#comment_email").val();
			var thisWebsite = $("#comment_www").val();
			var thisComment = $("#comment_content").val();
			var thisRealname = $("#realname").val();

			$.ajax({
				type: "POST",
				url: "/ajax" + $("#commentsForm form").attr("action"),
				data: "realname=" + thisRealname + "&comment_name=" + thisName + "&comment_email=" + thisEmail + "&comment_www=" + thisWebsite + "&comment_content=" + thisComment + "",
				dataType: "xml",
				error: function() {
					// an internal error has occurred
					alert("internal error - please try again later");
				},
				success: function(xml) {
		
					// get status response
					var statusMsg = $(xml).find("status").text();
		
					// set response status message
					if (statusMsg == "success") { 
						// all completed successfully, display the success messages
						if ($("#form_errors").length > 0) {
							$("#form_errors").slideUp(500, function(){
								$("#form_errors").remove();
								addComment($(xml).find("comment_name").text(),$(xml).find("comment_content").text());
							});
						} else {
							addComment($(xml).find("comment_name").text(),$(xml).find("comment_content").text());
						};
					} else if (statusMsg == "error") { 
						// an error has occurred, display the error messages
						if ($("#form_errors").length > 0) {
							$("#form_errors").slideUp(500, function(){
								$("#form_errors").remove();
								var errorBox = '<div id="form_errors" class="errorWrap hide"><ul>' + $(xml).find("error_message").text() + '</ul></div>'
								$("#commentsFormErrorWrap").prepend(errorBox).animate({opacity: 1}, 300, function(){
									$("#form_errors").slideDown();
								});
							});
						} else {
							var errorBox = '<div id="form_errors" class="errorWrap hide"><ul>' + $(xml).find("error_message").text() + '</ul></div>'
							$("#commentsFormErrorWrap").prepend(errorBox).animate({opacity: 1}, 100, function(){
								$("#form_errors").slideDown(500);
							});
						};
					};
				}
			});
			
			return false;
			
		});
	};



	// send contact form via ajax
	// ==================================================
	if ($("#contactForm").length > 0) {
		
		// submit contact form via ajax
		$("#contactSubmit").click(function(){
			var thisName = $("#form_name").val();
			var thisEmail = $("#form_email").val();
			var thisPhone = $("#form_phone").val();
			var thisContent = $("#form_content").val();
			var thisRealname = $("#realname").val();
			
			$.ajax({
				type: "POST",
				url: "/ajax" + $("#contactForm form").attr("action"),
				data: "realname=" + thisRealname + "&form_name=" + thisName + "&form_email=" + thisEmail + "&form_phone=" + thisPhone + "&form_content=" + thisContent + "",
				dataType: "xml",
				error: function() {
					// an internal error has occurred
					console.log("internal error - please try again later");
				},
				success: function(xml) {
		
					// get status response
					var statusMsg = $(xml).find("status").text();
		
					// set response status message
					if (statusMsg == "success") { 
						// all completed successfully, display the success messages
						if ($("#contactErrors").length > 0) {
							$("#contactErrors").slideUp(500, function(){
								$("#contactErrors").remove();
								var successBox = '<div id="contactErrors" class="successWrap hide"><ul>Thank you, your message has been sent successfully!</ul></div>'
								$("#contactFormErrorWrap").prepend(successBox).animate({opacity: 1}, 300, function(){
									$("#contactErrors").slideDown();
									$("#form_name").val("");
									$("#form_email").val("");
									$("#form_phone").val("");
									$("#form_content").val("");
								});
							});
						} else {
							var successBox = '<div id="contactErrors" class="successWrap hide"><ul>Thank you, your message has been sent successfully!</ul></div>'
							$("#contactFormErrorWrap").prepend(successBox).animate({opacity: 1}, 300, function(){
								$("#contactErrors").slideDown();
								$("#form_name").val("");
								$("#form_email").val("");
								$("#form_phone").val("");
								$("#form_content").val("");
							});
						};
					} else if (statusMsg == "error") { 
						// an error has occurred, display the error messages
						if ($("#contactErrors").length > 0) {
							$("#contactErrors").slideUp(500, function(){
								$("#contactErrors").remove();
								var errorBox = '<div id="contactErrors" class="errorWrap hide"><ul>' + $(xml).find("error_message").text() + '</ul></div>'
								$("#contactFormErrorWrap").prepend(errorBox).animate({opacity: 1}, 300, function(){
									$("#contactErrors").slideDown();
								});
							});
						} else {
							var errorBox = '<div id="contactErrors" class="errorWrap hide"><ul>' + $(xml).find("error_message").text() + '</ul></div>'
							$("#contactFormErrorWrap").prepend(errorBox).animate({opacity: 1}, 100, function(){
								$("#contactErrors").slideDown(500);
							});
						};
					};
				}
			});
			
			return false;
			
		});
	};

	

});
