/**
 * dxprog.com AJAX library
 */

var ch = 0, s = 0;
 
$(document).ready (function () {
	
	// Fix up inline gallery items with a lightbox
	$(".gallery a").lightBox ();
	
	// Fix up the slider thing in the gallery page
	switch (dxPage) {
		case "gallery":
			ch = $("#content > ul").height ();
			var c = 560; $("#content").height (c);
			$("#content > ul").height (c);
			$("#content > ul > li > ul").height (c - ch);
			$("#content > ul > li > ul > li:odd").addClass ("odd");
			$("#content > ul > li:first > ul").show ();
			
			// Set up the event listeners for the gallery pane
			$("#content > ul > li").click (function () {
				$("#content > ul > li > ul").hide ();
				$("ul", this).show ();
			});
			$("#content > ul > li > ul > li a").bind ("click", getItem);
			
			// Check to see if an item is being looked at
			var id = window.location.href.toString().match(/\/([0-9]+)\//);
			if (id.length > 0) {
				getItem(parseInt(id[1]));
			}
			
			break;
		case "home":
			setInterval (function () {
				s++;
				if (s >= 4)
					s = 0;
				var l = parseInt ($("#featured ul li").width ()) * s;
				$("#featured ul").animate ({left:"-" + l + "px"});
			}, 4500);
	}
	
	
});

function resizePane ()
{
	h = ($("#content > div").height () > 560) ? $("#content > div").height () : 560;
	$("#content").height (h);
	$("#content > ul").height (h);
	$("#content > ul > li > ul").height (h - ch);
}

function getItem (e)
{
	var id;
	if (typeof(e) === "number") {
		id = e;
	} else {
		id = this.href.match (/\/([0-9]+)\//)[1];
	}
	
	$.getJSON (baseURI + "/api/index.php", {"id":id, "type":"json", "method":"gallery.getItem"}, function (data) {
		
		// Clear out the old div
		$("#content > div").empty ();
		
		// Calculate the size of the object
		var cw = $("#content > div").width ();
		var h = Math.round (cw * parseFloat (data.body.aspect));
		
		// Check on the file type
		var ext = data.body.file.split (".");
		var file = baseURI + "/" + data.body.file;
		ext = ext[ext.length - 1];
		switch (ext) {
			case "jpg":
			case "jpeg":
			case "png":
			case "gif":
				var i = new Image ();
				i.src = file;
				i.onload = function () {
					var a = this.height / this.width;
					var w = (this.width > cw) ? cw : this.width, h = w * a;
					$("#content > div").prepend ("<img src=\"" + file + "\" / width=\"" + w + "\" height=\"" + h + "\" alt=\"Image\">");
					$("#content > div").append ("<article><header><h1>" + data.body.name + "</h1></header><p>" + data.body.description + "</p></article>");
					resizePane ();
				}
				break;
			case "flv":	
				file = baseURI + "/flvplayer.swf?file=" + file;
			case "swf":
				$("#content > div").flash ({swf: file, width: cw, height: h});			
				$("#content > div").append ("<article><header><h1>" + data.body.name + "</h1></header><p>" + data.body.description + "</p></article>");
				resizePane ();
				break;
		}
		
	});
	return false;
}