//     =============================================
//
//     WWW.QUIS.CC
//     ---------------------------------------------
//
//     By Chris Hill-Scott, except where noted.
//
//     Code is public domain, reuse as desired.
//
//     Requires jQuery
//
//     ---------------------------------------------
//
//     TODO:
//     • Commentee URLs into links
//     • Refactor AJAX comments function
//
//     =============================================


var QUIS = {
	focus: false, // Track element focus
	imageSelector: "img:not(.static)", // Selector for the resizable images
	isMobile: (function() {

		//Initialize our user agent string to lower case.
		return !!navigator.userAgent.toLowerCase().match(/(iphone|ipod|ipad|symbian|android|palm|blackberry)/gi);

	}())
};

$(function(){ // jQuery document ready

	QUIS.$page = $("html, body");
	QUIS.$window = $(window);
	QUIS.$document = $(document);

//  INIT  --------------------------------------
	$(QUIS.imageSelector)
		.imageScale();

//  BIND EVENTS  -------------------------------

	// Inline labels for forms
	// Uses scripts/jquery.labelify.js
	// http://www.kryogenix.org/code/browser/labelify/
    $(":text, input.email, input.url")
		.labelify(
			{
				labelledClass: "entering"
			}
		);

	// Allow comments textarea to grow automatically like on Facebook
	// Uses scripts/jquery.vertigro.js
	// http://aquaron.com/~jquery/vertigro
    $("textarea")
		.vertigro();

    // Hook up AJAX comments
	$("#photos input[type='submit']")
		.live(
			"click",
			function() {

				commentSubmit($(this));
				return false;

			}
		);

	// Bring up info/comments overlay on each photo
	$("#photos img")
		.live(
			"click",
			function() {

				$(this)
					.annotate();

			}
		);

	// Expand navigation bars on click
	$("#header div p.intro")
		.slidingPanel();

	// Reactivate submit on enter function for search form with hidden button
	$("#searchform input")
		.keydown(
			function(e) {

				if (13 == e.keyCode) {

					$(this)
						.parents("form")
						.submit();

					return false;

				}

			}
		);


	// Scroll photo-by-photo
	$("#scroll a")
		.click(
			function() {

				return scrollPhotos.go(($(this).attr("id") == "down") ? 1 : -1);

			}
		);

	// Show comments for articles
	$(".blogPost a[href='#comments']")
		.live(
			"click",
			function() {

				$(this)
					.blur()
					.slideToggle()
				.parent()
					.next()
					.slideToggle();

				return false;

			}
		);


	if (!QUIS.isMobile) {

		$("#footer")
			.hide();

	}

	// Automatically load new photos when scrolling near bottom of page
	$("#photos")
		.infinitescroll(
			{
				navSelector: "#footer #navigationLinks",
				nextSelector: "#footer #navigationLinks a:last",
				itemSelector: ".unit",
				loadingText: "Loading more photos",
				donetext: "No more photos",
				callback: function(path, pageID) {

					// size newly-loaded images
					$("#" + pageID + " " + QUIS.imageSelector)
						.imageScale();

					// Notify Google Analytics of page view
					_gaq.push(["_trackPageview", path]);

				}
			}
		);

	// Keyboard navigation controller
	$(document)
		.keydown(
			function(event) {

				// check for form focus
				if (QUIS.focus) return true;

				switch (event.keyCode || event.which) {
				// this doesn't work completely
// 					case 16: // shift
// 					case 17: // ctrl
// 					case 18: // alt
// 					case 91: // left command
// 					case 93: // right command
// 						return true;
					case 74: // j
//					case 40: // down arrow
						return scrollPhotos.go(1);
					case 75: // k
//					case 38: // up arrow
						return scrollPhotos.go(-1);
					case 32: // [space]
					case 73: // i
						scrollPhotos.nearest(0)
							.click();
						return false;
				}

			}
		);

	$("input, textarea")
		.live(
			"blur focus",
			function(event) {

				QUIS.focus = (event.type == "focusin");

			}
		);

});

// AJAX comment submission
// Too messy
// Plugin?
function commentSubmit($button) {

	$button
		.addClass("commentSubmitting");

	// TODO: rewrite using $.serialize()
	var $mostRecent = $button.parents(".commentsContainer").children(".yourComment"),
		$noComment  = $button.parents(".commentsContainer").children(".noComment"),
		author  = $button.siblings(".author").val(),
		email   = $button.siblings(".email").val(),
		url     = $button.siblings(".url").val(),
		comment = $button.siblings(".comment").val(),
		ID      = $button.siblings(".comment_post_ID").val();

	// TODO: commentee's urls into links!
	$.post(
		"http://quis.cc/wp-comments-post-ajax.php",
		{
			author:  author,
			email:   email,
			url:     url,
			comment: comment,
			comment_post_ID: ID
		},
		function(response) {

			$(".error")
				.hide(200);

			if ("success" == response) {

				$noComment
					.hide("slow");
				$mostRecent
					.before("<p class=\"incoming\"><span class=\"commentAuthor\">" + author + " says:</span> " + comment);

			} else {

				$mostRecent
					.after("<p class=\"error\">" + response + "</p>");
				$button
					.removeClass("commentSubmitting");

			}

			$(".incoming")
				.show(
					"slow",
					function() {

						$button
							.removeClass("commentSubmitting");

					}
				);
		}
	);

	return false;
}


