$(document).ready(function() {
			
			(function() {
				$('#inner').css({
					width: '508px'
				});
				$('#leftColumn').ajaxStart(function(){
					$(this).addClass('preloader');
				});
				retrieveXML("/includes/xml/writing.xml");
				
				if(id != null) {
					var backlink = $("<a>Back</a>").attr({
						href: "index.php",
						id: "backLink"
					});

					$("#subnavwrap").append(backlink)
				}
				
			})();
			
			function retrieveXML(xmlpath) {
				$.ajax({
					type: "GET",
					url: xmlpath,
					dataType: "xml",
					success: function(xml) {
						if(id != null && id != undefined) {
							getWriting(xml, id);
						} else {
							getWritings(xml);
							$('#writingContent').jScrollPane({
								showArrows: true,
								dragMinHeight: 10,
								dragMaxHeight: 10, 
								scrollbarWidth: 13,
								animateTo: true,
								animateStep: 10
							});
						}
					}
				});
			}
			function getWritings(xmlObj) {
				var x = $(xmlObj);
				var temp = {};
				var l = 0;
				x.find("writing").each(function() {
					l++;
					var t = $(this);
					temp[t.attr("id")] = {
						title: t.find("title").text(),
						magazine: t.find("magazine").text(),
						issue: t.find("issue").text(),
						writingpath: t.find("writingpath").text(),
						thumb: t.find("thumb").text(),
						full: t.find("full").text(),
					}
				});
				buildHTML(temp);
			}
			
			function getWriting(xmlObj, id) {
				$('#rightColumn').ajaxStart(function(){
					$(this).html("Loading...");
				});
				
				var writing = $(xmlObj).find("writing").filter(function(){
					return $(this).attr("id") == id;
				});
				var imgPath = writing.find("full").text();
				var title = writing.find("title").text();
				var htmlPath = writing.find("writingpath").text();
				
				var imgEl = $("<img />").attr({
					src: imgPath,
					alt: title,
					width: "566",
					height: "415"
				});
				
				$("#leftColumn").append(imgEl);
				$("#leftColumn").removeClass("preloader");
				$.ajax({
					type: "GET",
					url: htmlPath,
					dataType: "html",
					success: function(html) {
						$("#rightColumn").html('<div id="writingContent">' + html + '</div>');
						$('#writingContent').jScrollPane({
							showArrows: true,
							dragMinHeight: 10,
							dragMaxHeight: 10, 
							scrollbarWidth: 13,
							animateTo: true,
							animateStep: 10
						});
					}
				});
			}
			
			function buildHTML(obj) {
				var inner = $('<div id="inner" class="clearfix"></div>');
				for(var prop in obj) {
					$(inner).append('<div class="writingBlock"><a href="/writing/writing.php?id=' + prop + '"><img src="' + obj[prop].thumb + '" width="144" height="187" alt="Image" /></a></div>');
				}
				$("#leftColumn").html('<div id="center"></div>');
				$("#leftColumn").removeClass("preloader");
				$("#center").append(inner);
			}
});
