// JavaScript Document

// create array for division names
var divisions = new Array();
// create array for artist names
var artists = new Array();
// create array for artist names
var collections = new Array();
// create array for new work
var imageArray = new Array();
// set up master array to hold new work image details
var divLoadCounter = 0;
var artistLoadCounter = 0;
var divs = new Array();
var artistsToLoad = new Array();
//
var timeStamp = new Date().getTime();
//
var base_url = "";
var library_prefix = "../";

function loadXML(file, onComplete, params, onFail) {
	//alert('loadXML:'+file);
	//
	if (!params) {
		params = new Array();
	}
	//
	$.ajax({
		type: "GET",
		url: file+"?var="+timeStamp,
		dataType: "xml",
		success: function(xml) {
			params.unshift(xml);
			onComplete.apply(this, params);
		},
		error: function(err) {
			//alert(err);
			onFail.call(this);
		}
	});
}

// loads an artist's xml file
function getArtist(xml, divid, artistid, onComplete, params) {
	//alert('getArtist:'+divid+" : "+artistid);
	//
	var aid = $(xml).children(':first').children(':eq('+divid+')').children(':eq('+artistid+')').attr("id");
	loadXML(library_prefix+"artist"+aid+".xml", onComplete, params); 
}

// returns the contents of a particular book from specified artist and division
function getBook(collections, bookid) {
	//
	//alert('get book');
	var counter = 0;
	var arr = new Array();
	$(collections[bookid]["xml"]).find("image").each(function(){
		//
		if ($(this).parent().attr("status") == "live" && $(this).attr("path").length>0) {
			var imageObj = new Object();
			imageObj.name = $(this).parent().attr("name");
			imageObj.caption = $(this).parent().attr("caption") ? $(this).parent().attr("caption") : "";
			//imageObj.caption2 = $(this).attr("caption2") ? $(this).attr("caption2")+"<br />" : "<br />";
			imageObj.path = $(this).attr("path");
			imageObj.wid = $(this).attr("width");
			imageObj.thumbwid = $(this).attr("thumbwidth");
			//
			// work out height
			var thw = $(this).attr("thumbwidth");
			var rat = thumbHeight/thw;
			var ih = $(this).attr("width")*rat;
			imageObj.hei = 800; //Math.max(Math.round(ih/100)*100, 800);
			//
			if ($(this).children(':first').attr("path")) {
				imageObj.partnerpath = $(this).children(':first').attr("path");
				imageObj.partnerwid = $(this).children(':first').attr("width");
				imageObj.partnerthumbwid = $(this).children(':first').attr("thumbwidth");
				//
				var thw = $(this).children(':first').attr("thumbwidth");
				var rat = thumbHeight/thw;
				var ih = $(this).children(':first').attr("width")*rat;
				imageObj.partnerhei = 800; //Math.max(Math.round(ih/100)*100, 800);
			}
			arr.push(imageObj);
		}
		counter++;
	});
	//
	return arr;
}


function createThumbGrid() {
	//	
	if ($('#thumbnails').css("display") != "block") {
		// hide images
		//$('#left-image').fadeOut(600);
		//$('#right-image').fadeOut(600);
		$('#left-image').css("display", "none");
		$('#right-image').css("display", "none");
		//
		$('body').css("overflow", "auto");
		//
		createCaption(currentImage);
		//
		for (var i=0; i<imageArray.length; i++) {
			$('#thumbnails').append("<div class='foliothumb'><a href='#"+i+"' onclick='enlarge("+i+", true);' ><img id='thumbnail_"+i+"' style='display:none;' src='"+library_prefix+imageArray[i].path.replace("low res", "thumbs")+"' alt='"+imageArray[i].caption+"' border='0' onmousedown='event.preventDefault();'  onmouseover='createCaption("+i+");' /></a></div>");
			//
			$('#thumbnail_'+i).load(function()
				{
					// this = jQuery image object selection
					// callback executes when all images are loaded
					//alert('images loaded');
					//fillArea($(this), 116, 90);
					$(this).height(100);
					//position($(this), $(this).parent().parent(), "center");
					$(this).fadeIn(600);
				}).each(function(){ 	// IE workaround as load doesn't fire on cached images
					if(this.complete && (jQuery.browser.msie)) {
						$(this).trigger("load");
					}
				});
			//
			$('#thumbnail_'+i).error(function(){
				//
				$(this).parent().parent().css("width", 0);
				$(this).parent().parent().css("margin-right", 0);
			
			});
			//
			// partner
			if (imageArray[i].partnerpath) {
				$('#thumbnails').append("<div class='foliothumb'><a href='#"+i+"' onclick='enlarge("+i+", true);' ><img id='thumbnail_p_"+i+"' style='display:none;' src='"+library_prefix+imageArray[i].partnerpath.replace("low res", "thumbs")+"' alt='"+imageArray[i].caption1+"' border='0' onmousedown='event.preventDefault();' onmouseover='createCaption("+i+");' /></a></div>");
				//
				$('#thumbnail_p_'+i).load(function()
					{
						// this = jQuery image object selection
						// callback executes when all images are loaded
						//alert('images loaded');
						//fillArea($(this), 116, 90);
						//position($(this), $(this).parent().parent(), "center");
						$(this).height(100);
						$(this).fadeIn(600);
					}).each(function(){ 	// IE workaround as load doesn't fire on cached images
						if(this.complete && (jQuery.browser.msie)) {
							$(this).trigger("load");
						}
					});
				//
				$('#thumbnail_p_'+i).error(function(){
					//
					$(this).parent().parent().css("width", 0);
					$(this).parent().parent().css("margin-right", 0);
				});
			}
		};
		//
		$('.book-btn').each(function(){
			$(this).attr("href", $(this).attr("href")+"#thumbs"); 
		});
		//
		//$('#thumbnails').fadeIn(600);
		$('#thumbnails').css("display", "block");
		resizeWorkArea();
		$('#prev-next').html("<a href='#"+i+"' onclick='enlarge("+currentImage+");' >Back</a>");
		$('#thumbs-btn').attr("class", "selected");
		$('#preload').css("display", "none");
		//
		updateText();
	}
}


function hideThumbGrid() {
	//
	$('#thumbs-btn').attr("class", "clickable");
	$('#thumbnails').fadeOut(600);
	$('body').css("overflow", "hidden");
	$('#thumbnails').empty();
	$('.book-btn').each(function(){
		$(this).attr("href", $(this).attr("href").replace("#thumbs", "")); 
	});
	displayThumbs = 'off';
}

function listBooks(xml) {
	//
	var counter = 0;
	//
	$(collections).each(function(){
		//
		var cls = counter == currentBook && pageName == "folio.php" ? "selected" : "";
		if (counter>0) {
			$('#books').append('<a href="folio.php?bookid='+counter+'" class="book-btn '+cls+'" title="'+$(this["xml"]).attr("name")+'">'+$(this["xml"]).attr("name")+'</a> &ndash; ');
		}
		counter++;
	});
};


function getInfo(xml) {
	//	
	//alert('get info');
	$(xml).find("artist").each(function() {
		var biog = $(this).attr("client");
		biog = biog.replace('\r', '<br />');
		$('#biog').append('<p>'+biog+'</p>');
		//
		var clients = $(this).attr("notes");
		clients = clients.replace(/{H}/gi, "<span class='grey'>");
		clients = clients.replace(/{EH}/gi, "</span>");
		clients = clients.replace(/\r/g, '<br />');
		$('#clients').append('<p>'+clients+'</p>');
	});
};

function loadImages(xml) {
	//
	//alert('load images');
	getAllCollections(xml);
	// get the contents of a book
	imageArray = new Array();
	imageArray = getBook(collections, currentBook);
	//
};

function preloadImages(firstimage, lastimage) {
	//
	//alert('preload '+lastimage);
	for (i=firstimage; i<=lastimage; i++) {
		//alert('preloading '+library_prefix+imageArray[i].path);
		$.imgpreload(library_prefix+imageArray[i].path,function()
		{
			// this = new image object
			// callback
		});
		if (imageArray[i].partnerpath) {
			$.imgpreload(library_prefix+imageArray[i].partnerpath,function()
			{
				// this = new image object
				// callback
			});
		}
	}
	// if we didn't start with the first image, load the rest now
	if (firstimage > 1) {
		preloadImages(0, firstimage);
	}
}

function getAllCollections(xml, ignoreStatus) {
	//
	collections = new Array();
	$(xml).find("collection").each(function(){
		if (ignoreStatus == true || ($(this).attr("status") == "live" || ($(this).attr("status") == "private" && allowAccess==true))) {
			var arr = new Array();
			arr["xml"] = $(this);
			var parent_info = new Object({name:$(this).parent().attr("name"),status:$(this).parent().attr("status")});
			arr["parent_info"] = parent_info;
			//arr["parent_status"] = $(this).parent().attr("status");
			collections.push(arr);
		};
	});
};

function loadOpeners(xml) {
	//
	getAllCollections($(xml).children(":first").children(":first"), true);
	imageArray = new Array();
	imageArray = getBook(collections, 0);
}

function getIdByNodeAttr(xml, node_name, attr, attrValue, ignoreStatus) {
	//
	var counter=0;
	var bookid;
	//
	$(xml).find(node_name).each(function(){
		//
		if (ignoreStatus != true) {
			if ($(this).attr("status") == "live" || $(this).attr("status") == "private" && allowAccess==true) {
				//
				if ($(this).attr(attr) == attrValue) {
					bookid = counter;
					//return;
					//break;
				}
				else {
					counter++;		
				}
			}
		} else {
			if ($(this).attr(attr) == attrValue) {
				bookid = counter;
				//return;
				//break;
			}
			else {
				counter++;		
			}
		}
	});
	//
	return bookid;
}

function createCaption(imageid) {
	//
	var caption = imageArray[imageid].caption;
	$('#caption').html(caption);
	updateText();
};

function enlarge(imageid, startPreload) {
	//
	//alert('enlarge '+imageid);
	//
	//$('#leftimg').imgpreload(null);
	//$('#rightimg').imgpreload(null);
	//
	if ($('#thumbnails').css("display") != "none") {
		hideThumbGrid();
		//createImageNav(imageid);
		//$('#downloadbtn').css("display", "inline");
	}
	//
	var nextimg = imageid < imageArray.length-1 ? parseInt(imageid)+1 : 0;
	var previmg = imageid > 0 ? imageid-1 : imageArray.length-1;
	//
	//$('#left-image').empty();
	//$('#right-image').empty();
	$('#left-image').css("visibility", "hidden");
	$('#right-image').css("visibility", "hidden");
	$('#preload').css("display", "block");
	//
	var caption = imageArray[imageid].caption; //.replace(/&gt;/g, '>');
	//caption = pageName == "folio.php" ? caption.toUpperCase() : caption;
	caption = caption.replace(/&gt;/gi, '>');
	caption = caption.replace(/&lt;/gi, '<');
	//
	$('#left-image').replaceWith('<a href="#'+nextimg+'" id="left-image" style="visibility:hidden;"><img src="'+library_prefix+imageArray[imageid].path+'" alt="'+caption+'" onclick="enlarge(\''+nextimg+'\');" id="leftimg" /></a>');
	//
	if(imageArray[imageid].partnerpath) {
		$('#right-image').replaceWith('<a href="#'+nextimg+'" id="right-image" style="visibility:hidden;"><img src="'+library_prefix+imageArray[imageid].partnerpath+'" alt="'+caption+'"onclick="enlarge(\''+nextimg+'\');" id="rightimg" /></a>');
	} else {
		$('#right-image').replaceWith('<a href="#'+nextimg+'" id="right-image" style="visibility:hidden"><img src="" alt="" onclick="" width="0" id="rightimg" /></a>');
	}
	//
	//$('#image-nav').empty();
	$('#caption').text(caption);
	//	
	if (pageName == "folio.php") {
		$('#prev-next').html('<a href="#'+previmg+'" onclick="enlarge(\''+previmg+'\');" >Previous</a> &ndash; <a href="#'+nextimg+'" onclick="enlarge(\''+nextimg+'\');" >Next</a>');
	}
	//
	var leftimg = new Object;
	leftimg.arrived = false;
	if(imageArray[imageid].partnerpath) {
		var rightimg = new Object;
		rightimg.arrived = false;
	}
	//
	$('#leftimg').load(function()
	{
		leftimg.arrived = true;
		if (rightimg && rightimg.arrived == true) {
			$('#preload').css("display", "none");
			resizeWorkArea();
			$('#left-image').css("visibility", "visible");
			$('#right-image').css("visibility", "visible");
		} else if (!rightimg) {
			$('#preload').css("display", "none");
			resizeWorkArea();
			$('#left-image').css("visibility", "visible");
			//
		}
	}).each(function(){ 	// IE workaround as load doesn't fire on cached images
		if(this.complete && (jQuery.browser.msie)) {
			$(this).trigger("load");
		}
	});	
	if(imageArray[imageid].partnerpath) {
		//
		//$('#rightimg').imgpreload(function()
		$('#rightimg').load(function()
		{
			//alert('right image');
			rightimg.arrived = true;
			if (leftimg.arrived == true) {
				$('#preload').css("display", "none");
				resizeWorkArea();
				$('#left-image').css("visibility", "visible");
				$('#right-image').css("visibility", "visible");
			}
		}).each(function(){ // IE workaround as load doesn't fire on cached images
			if(this.complete && (jQuery.browser.msie)) {
				$(this).trigger("load");
			}
		});
	}
	//
	currentImage = imageid;
	//
	if (startPreload) {
		var numImages = imageArray.length;
		var firstimage = imageid<numImages-1 ? parseInt(imageid)+1 : 0;
		preloadImages(firstimage, numImages-1);	
	}
	//
	//
	updateText();
	//
	return true;
}


function loadArtistPage(xml) {
	//
	//alert('load artist page');
	//writeName(xml);
	//getInfo(xml);
	//
	
	if (pageName == "folio.php") {
		//
		var anch = jQuery.url.attr("anchor") ? jQuery.url.attr("anchor") : '0';
		var firstimage = anch;
		//
		loadImages(xml);
		listBooks();
		//
		if (firstimage == "thumbs") {
			createThumbGrid();
		} else if (parseInt(firstimage>=0)) {
			enlarge(parseInt(firstimage), true);
		} else {
			enlarge(parseInt(firstimage), true);
		}
		//
	} else if (pageName == "biog.php" || pageName == "contact.php") {
		//
		getAllCollections(xml);
		listBooks();
		$('body').css("overflow", "auto");
		//
	} else {
		// opening page
		getAllCollections(xml);
		listBooks();
		loadOpeners(xml);
		var randomNum=Math.floor(Math.random()*imageArray.length);
		enlarge(randomNum);
	}
	//
	showPage();
}


// for private links
if (allowAccess == 'true' || allowAccess == true) {
	//
	var allowAccess = true;
} else {
	//
	var allowAccess = false;
}
//
var privateArtist = privateArtist;
var privateBook = privateBook;
