﻿/**
 * This file contains all custom JS for the site.
 *
 * @file script.js
 * @author Dan DeFelippi
 */

// SyntaxHighlighter settings
SyntaxHighlighter.config.clipboardSwf	= "js/syntaxhighlighter/scripts/clipboard.swf";
// Why does it use <pre>? <code> exists for a reason!
SyntaxHighlighter.config.tagName		= "code";

// Initialize everything when document is ready
$(function() {
	/**
	 * This provides switching of content when each vertical dt is clicked.
	 */
	$("#menu dt a").click(function(e) {
		$("#menu dd").hide();
		$(this.href.match(/(#.*)/)[0]).show();
	});
	
	// Check if user loaded site with location hash, eg #code
	if (window.location.hash) {
		$("#menu dd").hide();
		$(window.location.hash).show();
	}
	
	/**
	 * Display highlighted source code for links with the "source" class.
	 *
	 * This is accomplished by fetching the file via XHR and loading it into a modal popup.
	 * Highlighting done with SyntaxHighlighter (http://alexgorbatchev.com/wiki/SyntaxHighlighter).
	 */
	$("a.source").click(function(e) {
		var href = this.href,
			$dialog = $("#code-dialog"),
			$d;
		
		// Check for the dialog box
		if (!$dialog.length) {
			$d = $(document);
			
			// It doesn't exist, create it.
			$dialog = $('<div id="code-dialog"><h2 class="loading">Loading...</h2></div>')
			.appendTo('body')
			.dialog({
				modal: true,
				draggable: false,
				resizable: false,
				// Set the width and height to 90% of the document
				width: parseInt($d.width() * .9),
				height: parseInt($d.height() * .9),
				show: 'slide',
				title: 'HTML Source'
			});
		} else {
			// Replace content with loading and reopen it.
			$dialog.html('<h2 class="loading">Loading...</h2>')
			.dialog('open');
		}
		
		// Fetch the code
		$.get(href, null, function(data, textStatus) {
			// Find the brush type to use. Defaults to xml.
			var type = href.match(/https?:\/\/(.*)\/(.*)\.(.*)/);
			
			if (type && type.length) {
				type = type[type.length - 1];
			} else {
				type = "xml";
			}
			
			// Inject it. Replaces loading header.
			// All "<" characters must be changed to an HTML entity so it doesn't render.
			$dialog.html('<code class="brush:' + type + '">' + data.replace(/</g, "&lt;") + "</code>");
			// Highlight it
			SyntaxHighlighter.highlight();
		});
		
		e.preventDefault();
	});
});