var data = [];
var updown = [];
var udthis = 0; // where on the nav are we initially (up/down)
var dtot = 0;
var title = ""; // placeholder, comes from xml
var keyCode = ""; // placeholder, key presses

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function showLoad()
{
	$("#loader").show();
}

function hideLoad()
{
	$("#loader").hide();
}

function slideMkp(i,t)
{
	var sp = i.split(".");
	var sl = sp[0].split("/");
	var iid = sl[sl.length-1];
	return "<table id='"+iid+"' title=\"" + t + "\" width='100%' style='height: 550px;' cellspacing='0' cellpadding='0'><tr><td valign='bottom'><img id='largeimage' src='"+i+"' alt=''/></td></tr></table>";
}

shuffle = function(o){ //v1.0
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
}

function ucfirst(str) {
    var firstLetter = str.substr(0, 1);
    return firstLetter.toUpperCase() + str.substr(1);
}

function Navigate(dir)
{
	var incthumbs = "";
	if (window.location.hash)
	{
		var h = window.location.hash.replace("#","");
		var s = h.split("-");
		if (s[1] == 'thumbs') var incthumbs = "-thumbs";
	}
	
	$("#titlebox").html("&nbsp;");
	$("#nofn").html("&nbsp;");	
		
	if (dir == 'up' && window.location.hash)
	{
		if (udthis == 0)
			udthis = updown.length-1;
		else
			udthis--;
		gallery(updown[udthis]+incthumbs);
	}
	else if (dir == 'down' && window.location.hash)
	{
		if (udthis == updown.length-1)
			udthis=0;
		else
			udthis++;
		gallery(updown[udthis]+incthumbs);			
	}
	else
	{
		if (window.location.hash && window.location.hash != "#info" && incthumbs != "-thumbs") $("#cycle").cycle(dir);
	}
}

function set_udthis(x)
{
	for(i=0;i<=updown.length;i++)
	{
		if (updown[i] == x) udthis = i;
	}
}

function showThumbs()
{
	if (window.location.hash && window.location.hash != "#info")
	{	
		var h = window.location.hash.replace("#","");
		var s = h.split("-");
		if (s[1] == "thumbs")
			var go = s[0];
		else
			var go = s[0] + "-" + "thumbs";
		gallery(go);
	}
}

function gallery(g)
{
	// alert($("#cycle").offset().top);
	
	$(".navitem>a").removeClass('here');
	$("#prevnext").hide();
	$("#indextext").hide();
	$("#thumbs-icon").hide();
	$("#titlebox").html("&nbsp;");
	$("#nofn").html("&nbsp;");
	$("#cycle table").removeClass('nextimg');

	document.title = title;

	showLoad();

	var s1 = g.split("-");
	var x = s1[0];
	var thisimg = s1[1];

	// mark our position in nav
	set_udthis(x);
			
	if (thisimg == "thumbs")
	{
		window.location.hash=g;
		document.title = "Thumbnails - " + ucfirst(x) + " - " + title;
		$("#nav-"+x).addClass("here");

                var thuArr = [];
                for (i=0;i<=dtot;i++)
                {
                        if (data[i].section == x)
                                thuArr.push(data[i].img);
                }

		var ttot = thuArr.length-1;
		var thumbs = "";
		for (i=0;i<=ttot;i++)
		{
			var tim = thuArr[i].replace("large","thumb");
			var ts1 = tim.split(".");
			var ts2 = ts1[0].split("/");
			var tid = ts2[ts2.length-1];
			thumbs = thumbs	+ "<a href='javascript:;' onclick=gallery('" 
					+ x + "-" + tid + "')><img class='thumb' src='"+tim+"' alt='' /></a>";
		}

		$("#cycle").html("<div>"+thumbs+"</div>");
		hideLoad();
	}
	//  images on main page
	else if (x == "index")
	{

		window.location.hash = "";
		$("#indextext").show();

		udthis = 0;
		var indArr = [];
				
		for (i=0;i<=dtot;i++) 
		{
			if (data[i].index == 1) 
				indArr.push({ img: data[i].img, title: data[i].title }); 
		}
		
		indArr = shuffle(indArr);
		
		showLoad();
		var p = new Image();
		p.src = indArr[0].img;
		$(p).bind('load',function() {
			hideLoad();
			var imgtot = indArr.length-1;
			var imgList = "";
			for (j=0;j<=imgtot;j++)
			{
				imgList = imgList+slideMkp(indArr[j].img,"");
			}
			
			$("#cycle").html(imgList);
			
			$("#cycle table:first").fadeIn(650, function() {
				$("#cycle").cycle({ speed: 3000, speedIn: 650, speedOut: 650 });
			});
							
		});
	}
	// info section
	else if (x == "info")
	{
		udthis = 0;
		window.location.hash = x;
		document.title = "info/contact - " + title;
		$("#nav-info").addClass('here');
		$("#nofn").html("<img src='images/abouttext.gif' usemap='#map2' border='0' /><map name='map2' id='map2'><area shape='rect' coords='240,-14,375,20' href='http://wonderfulmachine.com/jessyel-ty-gonzalez' target='_blank' alt='Supported by Wonderful Machine' /></map>");
		hideLoad();
		$("#titlebox").html("&nbsp;");
		$.get('info.html', function(data) {
				$("#cycle").html(data);
		});
	}
	// selected galleries
	else
	{
		if (!thisimg) window.location.hash = x;
		$("#nav-"+x).addClass('here');

		// $("#cycle").html("&nbsp;");
		$("#nofn").html("&nbsp;");
		$("#titlebox").html("&nbsp;");
		
		var galArr = [];
		for (i=0;i<=dtot;i++) 
		{
			if (data[i].section == x) 
				galArr.push({ img: data[i].img, title: data[i].title, info: data[i].info, iwidth: data[i].infowidth, iheight: data[i].infoheight, download: data[i].download }); 
		}

		var imgtot = galArr.length-1;
		var imgList = "";
		var current_image = 0;
		
		if (thisimg)
		{
			for (i=0;i<=imgtot;i++)
			{
				var s1 = galArr[i].img.split(".");
				var s2 = s1[0].split("/");
				var iid = s2[s2.length-1];
				if (thisimg == iid) current_image = i;
			}
		}
	
		
		showLoad();
		var p = new Image();
		p.src = galArr[0].img;
		$(p).bind('load',function() {
			hideLoad();
			$("#prevnext").fadeIn("slow");
			$("#thumbs-icon").fadeIn("slow");

			for (j=0;j<=imgtot;j++)
			{
				imgList = imgList+slideMkp(galArr[j].img,galArr[j].title);
			}
			
			$("#cycle").html(imgList);

			$("#cycle table").addClass("nextimg");
			
			$("#cycle table:eq("+current_image+")").fadeIn(650, function() {
				$("#cycle").cycle({ startingSlide: current_image, timeout: 0, speed: 650, prev: '#prev-arrow', next: '.nextimg', before: onBefore, after: hideLoad });
			});
			
			function onBefore()
			{
				var thispic = 0;
				var tot = imgtot+1;
				showLoad();

				$("#moreinfo_link").hide();
			 	$("#moreinfo").remove();				
			
				for (i=0;i<=imgtot;i++)
				{
					var s1 = galArr[i].img.split(".");
					var s2 = s1[0].split("/");
					var iid = s2[s2.length-1];
					if (this.id == iid)
					{
						if (galArr[i].info == "yes")
						{
							$.get('images/' + x + '/popup/'+this.id+'.html', function(data) {
								  $("<div id='moreinfo'>"+data+"</div>").appendTo("body");
							});	
							$("#moreinfo_link").show().fancyZoom({ directory: "images/fancyzoom", width: parseFloat(galArr[i].iwidth), height: parseFloat(galArr[i].iheight) });
					
						}
						thispic = i+1;
						// download link - mb 110401
						if (galArr[i].download == "yes") 
							$(".dllnk").attr("href","download.php?id=" + x + "-" + this.id).show();
						else
							$(".dllnk").attr("href","#").hide();
						
					}
				}
				
				window.location.hash = x + "-" + this.id;
				document.title = this.title + " - " + ucfirst(x) + " - " + title;
				$("#nofn").html("<img height='12' src='img.php?text="+thispic+"/"+tot+"' alt='' />");
				var timg = new Image();
				timg.src = 'images/' + x + '/title/' + this.id + '.gif';
				$("#titlebox").html(timg);							
			}
		});		
	}
	
}

function main()
{
	$.ajax({
		type: "GET",
		url: "data.xml",
		dataType: "xml",
		success: function(xml) {

			// site title
			title = $(xml).find("portfolio").attr("title");
			
			$(xml).find("image").each(function() 
			{	
				var infow = 0;
				var infoh = 0;
				var indexp = 0;
				if ($(this).attr("info") == "yes")
				{
					infow = $(this).attr("infowidth");
					infoh = $(this).attr("infoheight");
				}
				if ($(this).attr("index") == "yes") indexp = 1;
					
				data.push({ 
					img: 'images/' + $(this).parent().attr("name") + '/large/'+$(this).attr("id")+'.jpg', 
					section: $(this).parent().attr("name"),
					info: $(this).attr("info"),
					infoheight: infoh,
					infowidth: infow,
					index: indexp,
					download: $(this).attr("download"),
					title: $(this).attr("title")
				});
			});
			
			// build nav and keyboard up/down
			// first item is home
			// updown.push("index");
			
			// then the rest from xml
			$(xml).find("section").each(function()
			{
				var nimg = $(this).attr('navimg');
				var nsec = $(this).attr('name');
				$("<div class='navitem'><a href='javascript:;' id='nav-"+nsec+"' onclick=gallery('"+nsec+"')><img src='"+nimg+"' alt='' /></a></div>").insertBefore("#infoitem");
				updown.push(nsec);
			});
			
			// finally the info link
			//updown.push('info');
			
			// info section
			// $.get('info.html', function(data) {
			// 	$("<div id='info-contact'>"+data+"</div>").appendTo("body");
			// });	
			// $("#nav-info").fancyZoom({ directory: "images/fancyzoom", width: 550, height: 400 });
							
			dtot = data.length-1;
			var where = window.location.hash ? window.location.hash.replace("#","") : "index";
			gallery(where);
		},
		before: function(b) { showLoad() },
		error: function(e) {
			alert("Error loading xml content. " + e);
		}
	});
		
	// key handlers
	$(document).keydown(function (e) {
		keyCode = e.keyCode || e.which,
		key = {left: 37, up: 38, right: 39, down: 40, c: 67, e: 69, i: 73, p: 80, s: 83, t: 84, h: 72};
		// more key codes at http://jui.cc/R3

		switch (keyCode) {
			case key.left:
				Navigate('prev');
			break;
			case key.right:
				Navigate('next');
			break;
			case key.up:
				Navigate('up');
			break;
			case key.down:
				Navigate('down');
			break;			
			case key.c:
				gallery('commercial');
			break;
			case key.e:
				gallery('portraits');
			break;
			case key.i:
				gallery('info');
			break;
			case key.p:
				gallery('travel');
			break;		
			case key.h:
				gallery('index');
			break;
			case key.s:
				showThumbs();
			break;	
		}
	});	
}

$(document).ready(function() 
{
	main();
});

