(function($){
	$.gallery = function(options){
		var galleryXML = null;
		var highestZ = 1;
		var categories = new Array;
		var currentCategory = 0;
		var defaults = { };
		var options = $.extend(defaults, options);

		setupLightbox();
		$('#galleryCategories li').each(function(i) { 
			var c = $(this).text().toLowerCase().replace(/ /g, '-');
			if(c.charAt(c.length-1) == '-') c = c.slice(0,-1);
			categories.push(c); 
			$(this).click(function() { changeCategory(i); return false; }); 
		});
		$.ajax({ type: "GET", url: "gallery.xml?r="+Math.random()*1000, dataType: "xml", success:setupImages});
		
		function setupImages(xml) {
			galleryXML = xml;
			changeCategory(0);
		}
		
		function changeCategory(index) {
			$('#content').fadeOut(150);
			$('.projectContainer').fadeOut(150, function() { $(this).remove(); });
			currentCategory = index;
			$(galleryXML).find(categories[index]+' image').each(function(i) {
				var src = $(this).attr('src');
				$('<div class="projectContainer"><a href="images/gallery/'+src+'"><img src="images/gallery/thumbs/'+src+'" /></a></div>').appendTo('body').css({ paddingTop:16 }).each(function(j, div) { 
					if($.cookie('GP'+src)) {
						var tl = $.cookie('GP'+src);
						tl = tl.split(',');
						var t = Number(tl[0]);
						var l = Number(tl[1]);
					} else {
						var t = Math.random()*($(window).height()-220);
						var l = (Math.random()*($(window).width()-480))+280;
						$.cookie('GP'+src, t+','+l);
					}
					$(this).css({ position:'absolute', top:t, left:l }); 
				}).find('a').click(startLightBox).find('img').load(function() { setupHandle($(this).parent().parent()); });						   
			});
		}

		function setupHandle(div) {
			$(div).css({ width:$(div).width() }).prepend('<img class="handle" src="images/drag-handle.gif" alt="Drag this Shit!" />').css({ paddingTop:0, overflow:'hidden' }).find('.handle').css({ marginLeft:-(300-$(div).width())/2, cursor:'move' });
			$(div).draggable({ handle:'img:first', start:function() { $(this).css({ zIndex:highestZ++ }); }, stop:resetCookie });
		}
		
		function resetCookie() {
			var src = $(this).find('img:last').attr('src');
			src = src.substr(src.lastIndexOf('/')+1);
			$.cookie('GP'+src, this.offsetTop+','+this.offsetLeft);
		}
		
		function setupLightbox() {
			string = '<div id="overlay"></div><div id="lightbox"></div>';
			$("body").append(string);
			$("#overlay, #lightbox").click(function(){ closeLightBox(); }).filter('#overlay').hide();
			document.onkeydown = keyboardAction;
		}
		
		function startLightBox(e) {
			e.preventDefault();
			var a = this;
			$("#overlay").hide().css({ width:'100%', height: '100%', opacity : .8, zIndex:highestZ++ }).fadeIn('normal', function() { 
				var filename = $(a).attr('href').substr($(a).attr('href').lastIndexOf('/')+1);
				$(galleryXML).find(categories[currentCategory]+' image[@src='+filename+']').each(function() { 
					$('#lightbox').css('zIndex', highestZ++);
					$('<div id="lightbox-main"></div><div id="lightbox-info"></div><div id="close-button">Close</div>').appendTo('#lightbox');
					$('#close-button').hide();
					setupImage(this);
				});
			});
			return false;	
		}
		
		function setupImage(current) {
			$('<img class="" src="images/gallery/'+$(current).attr('src')+'" />').hide().load(function() { 
				$(this).fadeIn(); 
				$('<h2>'+$(current).find('title').text()+'</h2>'+$(current).find('description').text()+'<div id="imageNavContainer"><p><a id="prev" href="">Previous Project</a></p> <p><a id="next" href="">Next Project</a></p></div>').appendTo('#lightbox-info').fadeIn();
				$('#close-button').css({ cursor:'pointer', left:$(this).width()-$('#close-button').width() }).click(closeLightBox).fadeIn();
				handleArrows(current);
			}).appendTo('#lightbox-main');
		}
		
		function changeImage(obj) {
			$('#close-button').hide();
			$('#lightbox-main').children().remove();
			$('#lightbox-info').children().remove();
			setupImage(obj);
			handleArrows(obj);
		}
		
		function handleArrows(obj) {
			var next = $(obj).next();
			var prev = $(obj).prev();
			if (prev.find('title').text()) $('#prev').fadeIn().click(function() { changeImage(prev); return false; }); else $('#prev').hide();
			if (next.find('title').text()) $('#next').fadeIn().click(function() { changeImage(next); return false; }); else $('#next').hide();
		}
		
		function closeLightBox() {
			$('#lightbox').children().remove();
			$('#overlay').fadeOut();	
		}
		
		function keyboardAction(e) {
			if((e && e.keyCode == 27) || (!e && event.keyCode == 27)){
				closeLightBox();
			}
		}
	}
})(jQuery);

$(document).ready(function(){
	$.gallery();
	$(window).resize(function() { 
		var mydate = new Date();
		mydate.setTime(mydate.getTime() - 1); 
		var cookies = document.cookie.split(";");
		for (var i=0; i<cookies.length; i++) {
			var current = cookies[i].split("=");
			if (current[0]) document.cookie = current[0]+"=; expires=" + mydate.toGMTString();
		}
	});
	$('#navAbout').click(function() {
		$('.projectContainer').fadeOut(150, function() { $(this).remove(); });
		$('#content').fadeOut(150, function() {
			$('#content').load('about.html', { limit:25 }, function() { 
				$(this).fadeIn(150); 
			}); 
		});
		return false;	
	}); 
	$('#navContact').click(function() {
		$('.projectContainer').fadeOut(150, function() { $(this).remove(); });	
		$('#content').fadeOut(150, function() {
			$('#content').load('contact.html', { limit:25 }, function() { 
				$(this).fadeIn(150); 
			}); 
		});
		return false;	
	});
});
