$(document).ready(function() {
	// Bootstrap is used to load post specific functionality.
	var url = window.location.pathname;
	bootstrap(url.replace(/-/g,'_'));

	commentUrls();
	commentPreview();
	syntaxhighlighter();
});

function bootstrap(url) {

	var parts = url.substring(1).split("/");

	// @TODO: need to work out why there is a JS error being thrown in console regarding bootstrap.

	var controller = "home";
	var action = "index";

	if (parts.length >= 1) {
		controller = parts[0];
	}
	if (parts.length >= 2) {
		action = parts[1];
	}

	// Try to run the controller's init function first.
	try {
		routes[controller]["init"]();
	}
	catch (e) {
		$(document).log("Bootstrap could not run ["+controller+"][init] function.");
	}

	// Then try to run the controller's action function.
	try {
		routes[controller][action]();
	}
	catch (e) {
		$(document).log("Bootstrap could not run ["+controller+"]["+action+"] function.");
		$(document).log("error: " + e);
	}

}

/**
 * Declare bootstrap functions for controllers and actions.
 * Init functions are run before action functions.
 * Init functions are run for all actions on a controller.
 * Action functions are obviously only run for a particular action.
 */
var routes = {
	posts: {
		index: function() {
			// listing...
		},
		a_gateway_class_for_amfphp_remoting: function() {
			$("#chucknorris-demo").flash({
				src: '/flash/chucknorris.swf',
			    width: 540,
			    height: 250,
			    // wmode: "opaque"
			}, {
				update: false
			});
		},
		multi_file_drag_and_drop_ajax_upload: function() {
			fileUpload();
		},
		init: function() {
			signInWithTwitter();
			logOutLink();
			relatedPosts();
		} // Run on /posts/* pages.
	}
};

/**
 * File upload example based on the file uploader from:
 * http://valums.com/ajax-upload
 */
function fileUpload() {
	var $fileUpload = $('#example-file-upload');

	if ($fileUpload.length > 0) {
		// Set up the FileUploader...
		var uploader = new qq.FileUploader({
			element: $fileUpload[0],
			action: '/uploads/upload',
			params: {},
			allowedExtensions: ['png', 'jpg', 'jpeg', 'gif', 'bmp'],
			sizeLimit: 1 * 1024 * 1024,
			onSubmit : function(id, filename) {},
			onComplete : function(id, filename, response) {},
			template:
				'<div class="qq-uploader">' +
					'<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
					'<div class="qq-upload-button">Upload a file</div>' +
					'<ul class="qq-upload-list"></ul>' +
					'<a class="qq-clear-list" href="#">clear list</a>' +
				'</div>'
		});

		// Wire up the click handler for the clear list hyperlink.
		var $link = $fileUpload.find('a.qq-clear-list');
		$link.click(function() {
			$fileUpload.find('ul.qq-upload-list').empty();
			return false;
		});
	}
}

function relatedPosts() {
	$(window).scroll(function(){
		var distanceTop = $('#comments').offset().top - $(window).height();

		if ($(window).scrollTop() > distanceTop)
			$('#slidebox').animate({'right':'0px'},300);
		else
		$('#slidebox').stop(true).animate({'right':'-430px'},100);
	});

	$('#slidebox .close').bind('click',function(){
		$(this).parent().remove();
	});
}

/**
 * We want to persist any comment before the user is redirected to the logout action.
 */
function logOutLink() {
	$('#comment-logout').click(function(e) {
		e.preventDefault();

		var url = $(this).attr('href');
		persistComment(url);
	});
}

/**
 * We're keeping a global variable to track whether
 * we there is an existing Twitter window open.
 */
var twitterWindow = null;
function signInWithTwitter() {
	var $signInWithTwitter = $('#sign-in-with-twitter');
	if ($signInWithTwitter.exists()) {
		// Hi-jack the button to use a lightbox/modal window.
		$signInWithTwitter.click(function(e) {
			e.preventDefault();

			// Persist the comment to cookie before proceeding.
			persistComment();

			var url = $(this).attr('href') + '/1';
			var title = 'Sign in with Twitter';
			var w = 840, h = 400;
			var options = 'width='+w+',height='+h;

			// Update the current page to include a hash to the comments.
			document.location.hash = 'add-comment';

			// Check if the twitterWindow already exists...
			if (twitterWindow == null || twitterWindow.closed) {
				twitterWindow = window.open(url, title, options);

				// Work out where the parent window is.
				// Different browsers have different properties for doing this.
				var left = window.screenLeft != undefined ? window.screenLeft : window.screenX;
				var top = window.screenTop != undefined ? window.screenTop : window.screenY;

				// Center the window inside the parent window (approximately, since it uses view port).
				var windowWidth = $(window).width();
				var windowHeight = $(window).height();
				var x = left + (windowWidth/2 - w/2);
				var y = top + (windowHeight/2 - h/2);

				// Sometimes this can throw an error if Twitter is considered the owner of the page.
				// This can happen if the user is refreshing the page etc in an odd fashion.
				try {
					twitterWindow.moveTo(x, y);
				}
				catch (exception) {} // Whatevs!
			}
			twitterWindow.focus();
		});
	}
}

/**
 * A user may perform an action that will change the page during the process of commenting on a post,
 * this could be due to clicking the the 'Sign in with Twitter' link or the 'log out' link, etc.
 * As such - we want to try and persist anything they have written into the comment field(s) to cookie.
 */
function persistComment(callbackUrl) {
	var commentValue = $('#comment').val();

	var url = '/comments/persist';
	var data = { comment: commentValue };

	$.post(url, data, function(response) {
		if (typeof callbackUrl != 'undefined' && callbackUrl != null) {
			window.location = callbackUrl;
		}
	});
}

function commentUrls() {
	$("#comments div.comment div.meta p.url").hide();

	$("#comments div.comment").live('mouseover', function() {
		$(this).find("div.meta p.url").show();
	}).live('mouseout', function() {
		$(this).find("div.meta p.url").hide();
	});
}

function syntaxhighlighter() {
	$.beautyOfCode.init({
		baseUrl: '/syntaxhighlighter/',
		brushes: ['AS3', 'Xml', 'JScript', 'CSharp', 'Plain', 'Php'], // 'Mxml'],
		config: {
		},
		defaults: {
			gutter: false,
		},
		theme: 'TonyMilne',
		ready: function() {
			jQuery.beautyOfCode.beautifyAll();

			$("div.syntaxhighlighter")
				.before("<div class='syntaxhighlighter-top' />")
				.after("<div class='syntaxhighlighter-bottom' />");
		}
	});
}

function commentPreview() {
	$('#add-comment input, #add-comment textarea').bind('blur keyup',function() {
		// If $commentPreview doesn't exist, we'll add it to the DOM
		// once we know the user has entered something into the form.
		var hasInput = false;
		$commentPreview = $('#comment-preview');

		// Set up handles to the variables.
		var nameValue, urlValue, commentValue, emailValue, imageUrl;

		// Grab the values all at once and validate that *something* has been entered.
		nameValue = $('#name').val();
		urlValue = $('#url').val();
		commentValue = $('#comment').val();

		// Populate the variables depending on the authentication type being used.
		var authType = $('#authentication-type').val();
		switch(authType) {
			case 'twitter':
				imageUrl = $('#image-url').val();
				hasInput = commentValue;
				break;
			case 'facebook': break;

			case 'none':
				emailValue = $('#email').val();

				// Generate the image url using Gravatar.
				if (emailValue && /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(emailValue)) {
					var md5Email = $.md5(emailValue);
					imageUrl = 'http://gravatar.com/avatar.php?gravatar_id=' + md5Email + '&size=60' + '&default=http://tonymilne.com.au/img/transparent.gif';
				}

				hasInput = (nameValue || urlValue || emailValue || commentValue);
				break;

			default: break;
		}

		if (hasInput && !$commentPreview.exists()) {
			var html = getEmptyCommentPreview();
			$('#comments h2').before(html);

			// Grab a handle to $commentPreview.
			$commentPreview = $('#comment-preview')

			// Hide the comment url (to be consistent with the other comments).
			$commentPreview.find('p.url').hide();
		}

		// Populate the commentPreview elements.
		if (nameValue) {
			$commentPreview.find('p.name').html(nameValue);
		}
		if (urlValue && /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{2}/.test(urlValue)) {
			$commentPreview.find('p.url a').attr('href', urlValue).text(urlValue);
		}
		if (imageUrl) {
			$commentPreview.find('div.avatar img').attr('src', imageUrl);
		}
		if (commentValue) {
			var commentHtml = commentValue.replace(/\n/g,'<br />');
			$commentPreview.find('div.content').html(commentHtml);

			// @TODO: Need to Code Highlighting:
			// It needs to work for incomplete html/code, and work with line breaks.

			// Basic working version:
			// var regex = /<pre class="code"><code.*>.*<\/code><\/pre>/;

			// Regex that allows for single/double quotes and spaces/tabs between tags.
			// var regex = /<pre class=['"]code['"]>[\r\n\s]*<code( class=['"][a-zA-Z0-9]+['"]|)>\s*.*\s*<\/code>\s*<\/pre>/m;

			// Latest attempt to handle split over multiple lines.
			var regex = /<pre class=['"]code['"]>\s*<code( class=['"][a-zA-Z0-9]+['"]|)>\s*(.|\r|\n)*\s*<\/code>\s*<\/pre>/;
			if (commentHtml.match(regex)) {
				// We've got at least one valid code block.
				// Try to bust a move with the SyntaxHighlighting.
				try {
					$commentPreview.find('div.content pre.code').beautifyCode(null, {
						bloggerMode: true
					});

					$commentPreview.find("div.content div.syntaxhighlighter")
						.before("<div class='syntaxhighlighter-top' />")
						.after("<div class='syntaxhighlighter-bottom' />");
				}
				catch (e) {}
			}
			/*
			<pre class="code"><code class="php">$this->var = "hello world!";</code></pre>
			*/
			/*
			This is an example comment with code:
			<pre class="code">
			<code class="php">
			$this->example = "hello world";
			</code>
			</pre>
			Testing...
			*/
			// Need to find out if we have a full <pre class="code"><code></code></pre>.
		}
	});

	// Force the live preview to run on page load in case of persisted comments.
	$('#comment').blur();
}

function getEmptyCommentPreview() {
	var html = '';
	html += '<div id="comment-preview" class="comment">';
	html += 	'<div class="meta">';
	html += 		'<p class="name"></p>';
	html += 		'<p class="url">&nbsp; - &nbsp;<a href=""></a></p>';
	html += 		'<p class="published-date">(Live Preview)</p>';
	html += 		'<div class="clearer"></div>';
	html += 	'</div><!-- end meta -->';

	html += 	'<div class="avatar">';
	html += 		'<img src="/img/transparent.gif" width="60px" height="60px" alt="">';
	html += 	'</div><!-- end avatar -->';

	html += 	'<div class="content">';
	html += 	'</div><!-- end content -->';

	html += 	'<div class="clearer"></div>';
	html += '</div>';

	return html;
}
