var timeout = new Array();
var cancel = new Array();
var currentRecordView;
var currentCollection;
var currentRecords = new Object();
var cols;
var rows;
var maxPagesForNavigation = 5;
var searchWindow;
var lastSearchWord = "";
var leftColumnText = "";
var rightColumnText = "";
var numRecordsFound = -1;
var assetBoxWidth = 213;
var assetBoxHeight = 251;
var assetBoxHeightBasket = 49;
var thumbnailSize = 128;
var userCollectionList = new Array();
var sharedCollectionList = new Array();
var maxRecordsToProcess = 50;
var useJSPageDesignForRecords = false;
var useXSL = true;
var xslRecords;
var xslCategoryTree;
var messages = new Object();
var rootFilterCategory;
var currentLightBoxName = "";
var artistView = false;
var isGuest;
var userEmail;
var currentIndex;
var needToConfirmExit = true;
var currentPage;
var currentSize = 0.33;
var currentLanguage;
var displayBasketPermissionWarning = false;
var basketPermissionsWarningDisplayed = false;
var downdloadTermsCallback = null;
var termsApproved = false;

function init() {
	var ua = navigator.userAgent;

	window.onscroll = scrollColumns;

	if (getWindowWidth() < 1069) {
		document.body.style.width = "1070px";
	}

	centerImages();

	dwr.util.setValue("leftColumn", getFilledDisplayLeftColumnTemplate());
	dwr.util.setValue("rightColumn", getFilledDisplayRightColumnTemplate());

	if (useXSL) {
		loadXML("xsl/Records.xsl.jsp", function(xml) {
			xslRecords = xml;
		});
		loadXML("xsl/CategoryTree.xsl.jsp", function(xml) {
			xslCategoryTree = xml;
		});
	}

	preLoadCollectionList();
	
	if (currentLightBoxName) {
		var collectionInfo = new Object();
		collectionInfo["id"] = currentLightBoxName;
		collectionInfo["shared"] = false;

		CollectionHandler.loadCollection("LightBox", collectionInfo, function (success) {
			if (success) {
				dwr.util.setValue("LightBoxLink", messages["lightbox"] + " (" + currentLightBoxName + ")");
			}
			
			loadRecordsInit();
		});
	} else {
		loadRecordsInit();
	}

	//var slider = new Control.Slider("handle", "track", {axis: "horizontal", increment: 1, sliderValue: 0.5});

	//slider.options.onSlide = function(size) {
	//	scale(size);
	//}

	//slider.options.onChange = function(size) {
	//	scale(size);
	//}
}

function loadRecordsInit() {
	if (currentCollection != "Artist") {
		loadCategoryTree(rootFilterCategory, "CategoryTree");
		new Resizeable('leftColumn', {top: 0, left: 0, bottom: 0, resize: function(el) { resize();  }, minWidth: 155, maxWidth: 500});
	} else {
		document.getElementById("leftColumn").style.display = "none";

		if (currentSize != 0.33) {
			scale(currentSize);
		}
	}

	CollectionHandler.setSize(getCols(), getRows(), function() {
		if (currentIndex && currentIndex != "null" && currentIndex > -1) {
			var page = Math.ceil(currentIndex / (getCols() * getRows())) + 1;
				
			dwr.util.setValue("secondaryNav", getFilledDisplaySecondaryNavTemplate());
				
			showRecords(page);
			CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
				
			currentIndex = null;
		} else {
			showCurrentRecords();
		}
	});
}

function showArtistUrl(artist) {
	var ele = document.getElementById("artistUrlBox");
	var adjust = 0;
	
	if (IE && document.documentElement.scrollTop > -1) {
		adjust = document.documentElement.scrollTop;
	}

	ele.style.display = "block";
	ele.style.top = mouseY + adjust + "px";
	ele.style.left = mouseX + "px";

	ele = document.getElementById("artistUrl");
	
	dwr.util.setValue(ele, artist);
	
	ele.focus();
	ele.select();
}

function hideArtistUrl() {
	document.getElementById("artistUrlBox").style.display = "none";
}

function createPageUrl() {
	CollectionHandler.createPageUrl(currentCollection, displayPageUrl);
}

function displayPageUrl(url) {
	if (url) {
		showArtistUrl(url);
	}
}

function resize() {
	var newCols = getCols();
	var newRows = getRows();
	
	if (getWindowWidth() <= 1069) {
		document.body.style.width = "1070px";
	} else {
		document.body.style.width = "";
	}

	if (newRows < 1) {
		newRows = 1;
	}
	
	if (newCols * newRows != cols * rows) {
		var count = 0;
		var assetsDiv = document.getElementById("assets");
		var assetBoxes = assetsDiv.childNodes;
		var lastIndex = -1;
			
		for(var i = 0; i < assetBoxes.length; i++) {
			if(assetBoxes[i].className == "assetInfo" || assetBoxes[i].className == "assetRowContainer") {
			count++;
				lastIndex = assetBoxes[i].getAttribute("index");
			}
		}
	
		var recordsNeeded = newCols*newRows - count;
		
		cols = newCols;
		rows = newRows;

		if (recordsNeeded > 0) {
			if (currentRecords && currentRecords[currentCollection]) {
				var catalogIDs = new Array();
				var recordIDs = new Array();
				var index = 0;
			
				for(var id in currentRecords[currentCollection]) {
					var catalogIDTmp = currentRecords[currentCollection][id]["catalogID"];
					var recordIDTmp = currentRecords[currentCollection][id]["recordID"];
				
					catalogIDs[index] = catalogIDTmp;
					recordIDs[index] = recordIDTmp;
					index++;
				}
			
				dwr.engine.beginBatch();
				CollectionHandler.getNewRecord(currentRecordView, catalogIDs, recordIDs, recordDisplayFields, recordDisplayNotInCollectionNames, recordsNeeded, displayRecord);
				CollectionHandler.getNewPageNumbers(currentRecordView, maxPagesForNavigation, cols, rows, displayPageNavigation);
				CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
				dwr.engine.endBatch();
			} else if (useXSL){
				displayRecordsXML("xml/Records.xml.jsp?collection=" + currentCollection + "&lastIndex=" + lastIndex + "&num=" + recordsNeeded, false, function() {
					if (currentCollection == "CollBasket") {
						colorCollBasket();
					}

					dwr.engine.beginBatch();
					CollectionHandler.getNewPageNumbers(currentRecordView, maxPagesForNavigation, cols, rows, displayPageNavigation);
					CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
					dwr.engine.endBatch();
				});
			} else {
				dwr.engine.beginBatch();
				CollectionHandler.getNewRecordText(currentCollection, lastIndex, recordsNeeded, displayRecord);
				CollectionHandler.getNewPageNumbers(currentRecordView, maxPagesForNavigation, cols, rows, displayPageNavigation);
				CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
				dwr.engine.endBatch();
			}
		} else {
			if (currentRecords && currentRecords[currentCollection]) {
				var records = new Array();
				var index = 0;
			
				for(var id in currentRecords[currentCollection]) {
					records[index] = currentRecords[currentCollection][id];
					index++;
				}

				for (var i=index - 1; i > index + recordsNeeded - 1; i--) {
					var catalogID = records[i]["catalogID"];
					var recordID = records[i]["recordID"];
				
					var assetBox = document.getElementById("assetBox" + catalogID + "x" + recordID);
		
					try {
						document.getElementById("assets").removeChild(assetBox);
					} catch (e) {
						var container = document.getElementById("container" + catalogID + "x" + recordID);
			
						document.getElementById("assets").removeChild(container);
					}

					delete currentRecords[currentCollection][catalogID + "x" + recordID];
					numRecordsFound--;
				}
			} else {
				for(var i = count + recordsNeeded; i < count; i++) {
					for(var j = assetBoxes.length - 1; j >= 0; j--) {
						if(assetBoxes[j].className == "assetInfo" || assetBoxes[j].className == "assetRowContainer") {
							if(assetBoxes[j].getAttribute("index") == lastIndex) {
								assetsDiv.removeChild(assetBoxes[j]);
								numRecordsFound--;
								lastIndex--;
								break;
							}
						}
					}
				}
			}
						
			dwr.engine.beginBatch();
			CollectionHandler.getNewPageNumbers(currentRecordView, maxPagesForNavigation, cols, rows, displayPageNavigation);
			CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
			dwr.engine.endBatch();
		}
	}
	
	centerImages();
	resizeCategoryTree();
}

function resizeCategoryTree() {
	if (currentCollection == "SearchResult" && document.getElementById("scrollNavContainer") && document.getElementById("scrollNavContent")) {
		var scrollFactor = getScrollFactor(13);
		var assetsBoxSize = document.getElementById("centerColumn").offsetHeight;
		assetsBoxSize += document.getElementById("centerColumn").offsetTop;
		var categoryTreeSize = document.getElementById("leftColumn").offsetHeight;
		categoryTreeSize += document.getElementById("leftColumn").offsetTop;
		categoryTreeSize -= document.getElementById("scrollNavContainer").offsetHeight;
		categoryTreeSize += document.getElementById("scrollNavContent").offsetHeight;
		categoryTreeSize -= scrollFactor;
		
		if (categoryTreeSize + 20 < getHeight()) {
			document.getElementById("scrollNavContainer").style.height = "";
			document.getElementById("scrollNavContent").style.top = "";
	//	} else if (assetsBoxSize > getHeight()) {
	//		document.getElementById("scrollNavContainer").style.height = assetsBoxSize - document.getElementById("categoryTree").offsetTop - document.getElementById("leftColumn").offsetTop - 41 + "px";
		} else {
			document.getElementById("scrollNavContainer").style.height = getHeight() - document.getElementById("categoryTree").offsetTop - document.getElementById("leftColumn").offsetTop - 41 + scrollFactor + "px";
		}
	}
}

function getScrollFactor(additionalFactor) {
		var scrollFactor;
		
		if (window.pageYOffset) {
			scrollFactor = window.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			scrollFactor = document.documentElement.scrollTop;
		} else if (document.body) {
			scrollFactor = document.body.scrollTop;
		} else {
			return 0;
		}
		
		if (scrollFactor > 0) {
			scrollFactor -= 111;
			
			if (additionalFactor) {
				scrollFactor += additionalFactor;
			}
		} else {
			scrollFactor = 0;
		}
		
		return scrollFactor;
}

function getLeftColumn() {
	var leftColumn = 155;

	try {
		var ele = document.getElementById("leftColumn");
		
		if (ele) {
			leftColumn = ele.offsetWidth;
		}
	} catch(e) {}

	return leftColumn;	
}

function getRightColumn() {
	var rightColumn = 155;
	
	try {
		var ele = document.getElementById("rightColumn");
		
		if (ele) { 
			rightColumn = ele.offsetWidth;
		}
	} catch(e) {}

	return rightColumn;
}

function getCols() {
	if (currentCollection == "CollBasket") {
		return 1;
	}
	
	var tmpCols = Math.floor((getWidth() - getLeftColumn() - getRightColumn() - 10) / assetBoxWidth);
	var colsSelector = "auto";

/*	try {
		colsSelector = dwr.util.getValue("colsSelector");
	} catch (e) {
		colsSelector = "auto";
	}*/
	
	if (colsSelector != "auto" || tmpCols >= colsSelector) {
		return colsSelector;
	}
	
	return tmpCols;
}

function getRows() {
	if (currentCollection == "CollBasket") {
		return 100;
	}
	
	var rowsSelector = "-1";
	
	try {
		if (exists("rowsSelector")) {
			rowsSelector = dwr.util.getValue("rowsSelector");
		}
	} catch (e) {
		rowsSelector = "-1";
	}
	
	if (rowsSelector != "-1") {
		return rowsSelector;
	}
	
	// not correct yet
	// should be fine now
	var assetTop = 184;
	
	try {
		var ele = document.getElementById("assets");
		
		if (ele) {
			assetTop = ele.offsetTop;
		}
	} catch (e) {}
	
	var height = assetBoxHeight;
	
	if (currentCollection == "CollBasket") {
		height = assetBoxHeightBasket;	
	}
	
	var newRows = Math.floor((getHeight() - assetTop) / (height));
	
	if (newRows < 2) {
	 newRows = 2;
	}
	
	return newRows;
}

function getWidth() {
	return document.body.clientWidth;
}

function getWindowWidth() {
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && document.documentElement.clientWidth ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && document.body.clientWidth ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
	return myWidth;
}

function getHeight() {
	return getWindowHeight();
}

function getWindowHeight() {
  var myHeight = 0;
  if( typeof( window.innerHeight ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && document.documentElement.clientHeight ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && document.body.clientHeight ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
	return myHeight;
}

function centerImages() {
	if (currentCollection != "CollBasket") {
		var	space =  Math.floor(((getWidth() - getLeftColumn() - getRightColumn() - 10) - (getCols() * assetBoxWidth)) / 2);
	
		/*if (space < 0) {
			document.getElementById("bod").style.width = getWidth() - space + "px";
			document.getElementById("assets").style.width = (getCols() * assetBoxWidth + 10) + "px";
		} else {
			document.getElementById("bod").style.width = "";
			document.getElementById("assets").style.width = "";
		}*/
		
		if (space < 5) {
			space = 5;
		}
	
		document.getElementById("assets").style.marginLeft = space + "px";
		document.getElementById("assets").style.marginRight = space - 10 + "px";
	
		if (navigator.appName == ("Microsoft Internet Explorer")) {
			document.getElementById("assets").style.width = (getCols() * assetBoxWidth + 10) + "px";
		}
	} else {
		document.getElementById("assets").style.marginLeft = "10px";
		document.getElementById("assets").style.marginRight = "10px";

		if (navigator.appName == ("Microsoft Internet Explorer")) {
			document.getElementById("assets").style.width = "";
		}
	}
}

var scrolling;

function scrollColumns() {
	if (!scrolling) {
		scrolling = true;
	
		var element;
		var top = getScrollFactor();
		
		if (top > 0) {
			top += 13;
		} else {
			top = 0;
		}
		
		element = document.getElementById("leftGlue");
		
		if (element) {
			element.style.marginTop = top + "px";
		}
	
		element = document.getElementById("rightGlue");
		
		if (element) {
			var oldTop = parseInt(element.style.marginTop);
			var rightCol = document.getElementById("rightColumn");
			var overSize = getHeight() - rightCol.offsetTop - rightCol.offsetHeight + oldTop;
			var overSizedTop = -1;
			
			if (overSize < 0) {
				if (top + overSize + 98 < 0) {
					overSizedTop = 0;
				} else {
					overSizedTop = top + overSize + 98;
				}

				if (overSizedTop < oldTop) {
					if (overSizedTop - oldTop > overSize + 98 && overSizedTop > 0) {
						scrolling = false;
	
						return;
					}
				} else {
					top = overSizedTop;
				}
			}
			
			element.style.marginTop = top + "px";
		}
		
		scrolling = false;
	}
}

function scale(size) {
	var thumbnailSize = 164;
	var floorSize = 82;
	var ceilingSize = 328;
	var images = document.getElementsByClassName("pic");
	
	currentSize = size;

	thumbnailSize = Math.floor(floorSize + (size * (ceilingSize - floorSize)));
	assetBoxWidth = thumbnailSize + 49;
	assetBoxHeight = assetBoxWidth + 51; // not correct yet!
	
	changeStyle("div.assetInfo", "width", assetBoxWidth+"px");
	changeStyle("div.assetInfoBody", "height", thumbnailSize+2+"px");
	changeStyle("img.dummypic", "height", thumbnailSize-34+"px");

	for (i=0; i < images.length; i++) {
		try {
			if (images[i].height >= images[i].width) {
				images[i].height = thumbnailSize;
			} else {
				images[i].width = thumbnailSize;
			}
		} catch (e) {}
	}
  
	CollectionHandler.setThumbnailSize(thumbnailSize);
	
	var images = document.getElementsByClassName("pic");
	
	for (i=0; i < images.length; i++) {
		try {
			var url = images[i].src;
            var index1 = url.indexOf(".");
            var index2 = url.indexOf(".", index1 + 1);
            var index3 = url.indexOf(".", index2 + 1);
			
            if (index3 > -1 && index2 > -1 && index1 > -1) {
                url = url.substring(0, index2 + 1) + thumbnailSize + url.substring(index3);
				
				images[i].src = url;
			}
		} catch (e) {}
	}

	CollectionHandler.setSize(getCols(), getRows(), showCurrentRecords);
	
	if (opener) {
		opener.scale(size);
	}
}

function showHourglass() {
	document.body.style.cursor = "wait";
}
	
function showDefaultPointer() {
	document.body.style.cursor = "auto";
}
			
function redirectError(message) {
	if (typeof message == "object" && message.name == "Error" && message.description) {
		alert(message.description);
	} else {
		try {
		var index = message.indexOf(":");
		
		if (index > -1) {
			alert(message.slice(index + 2));
			//window.location.href = "Login.jsp";
		} else {
			alert(message);
		}
		} catch (e) {
			alert(message);
		}
	}
}

function openCreditForm(catalogID, recordID, packaging) {
	sUrl = "CreditCardForm.jsp?recordView=" + currentRecordView;
	
	if (catalogID > -1) {
		sUrl += "&catalogID=" + catalogID;
	}

	if (recordID > -1) {
		sUrl += "&recordID=" + recordID;
	}

	sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=380,height=340";
	window.open(sUrl, "CreditCard", sOpt);
}

function warnExitIE() {
	if (needToConfirmExit) {
		alert("You are now leaving this page. Please always use the tabs to navigate the site.\nIf you clicked the Reload, Back- or Forward-Button of your browser, you may have to\nlog off/on if the web application is not responding.");
	}
	
	needToConfirmExit = true;
}

function confirmExit() {
	if (needToConfirmExit) {
		return "You are attempting to leave this page. Please always use the tabs to navigate the site.\nIf you clicked the Reload, Back- or Forward-Button of your browser, you may have to\nlog off/on if the web application is not responding. Are you sure you want to exit this page?";
  }
	
	needToConfirmExit = true;
}

function openPreview(index) {
	// width = size + 50; height = size + 80
	var sOpt = "toolbar=no,scrollbars=yes,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=562,height=592";
	var win = window.open("Preview.jsp?recordView=" + currentCollection + "_Preview&page=" + index, "Preview", sOpt);
	
	if (win) {
		win.focus();
	}
}

function openInfo(index) {
	var sOpt = "toolbar=no,scrollbars=yes,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=400,height=510";
	var win = window.open("RecordInfo.jsp?recordView=" + currentCollection + "_RecordInfo&page=" + index, "Info", sOpt);
	
	if (win) {
		win.focus();
	}
}

function findPos(obj) {
	 var curleft = curtop = 0;
	 
	 //If the browser supports offsetParent we proceed.
	 if (obj.offsetParent) {
	  //Every time we find a new object, we add its offsetLeft and offsetTop to curleft and curtop.
	  do {
	   curleft += obj.offsetLeft;
	   curtop += obj.offsetTop;
	 
	   //The tricky bit: return value of the = operator
	   //Now we get to the tricky bit:
	  } while (obj = obj.offsetParent);
	 }
	 
	 return [curleft,curtop];
}

function placePreferences(eleName, butName) {
	var ele = document.getElementById(eleName);
	var eleWidth = parseInt(ele.style.width, '10');
	var but = document.getElementById(butName);
	var butLeft;
	var butWidth = but.offsetWidth;
	var ua = navigator.userAgent;

	butLeft = findPos(but)[0];
	
	ele.style.left = butLeft + butWidth - eleWidth - 11 + "px";
	
	var header = document.getElementById("header");
	
	if (header) {
		ele.style.top = header.offsetHeight + 18 + "px";
	}
}

function showPreferences() {
	placePreferences("preferences", "butPreferences");	
	showhide('preferences', 'blind', { duration: 0.7 });
}

function showAdmin() {
	placePreferences("admin", "butAdmin");	
	showhide('admin', 'blind', { duration: 0.7 });
}

function showHelp() {
	placePreferences("help", "butHelp");	
	showhide('help', 'blind', { duration: 0.7 });
}

function showhideLast(eleName, effect, param) {
	var id;
	
	for (var tmpID in currentRecords[currentCollection]) {
		id = tmpID;
	}
	
	if (eleName == "contextMenu" + id) {
		var menu = document.getElementById(eleName);
		
		menu.style.visibility = "hidden";
		menu.style.display = "block";
		menu.style.top = 20 - menu.offsetHeight + "px";
		menu.style.display = "none";
		menu.style.visibility = "visible";
	}
	
	showhide(eleName, effect, param);
}

function showhide(eleName, effect, param) {
	Effect.toggle(eleName, effect, param);

	var menu = document.getElementById(eleName);
	if(menu.id.indexOf("contextMenu") == 0) {
		menu.style.overflow = "auto";
	}
}

function fadeout(eleName, time) {
	var sec = 1000;

	if (time) {
		sec = time * 1000;
	}
	
	clearTimeout(timeout[eleName]);
	timeout[eleName] = setTimeout("hide('" + eleName + "')", sec);
	cancel[eleName] = false;
}

function hide(eleName) {
	if (!cancel[eleName]) {
		Effect.BlindUp(eleName, { duration: 0.7 });
		
		if (eleName == "multipleCatalogSelect") {
			document.getElementById("singleCatalogSelect").style.display = "block";
		}
	}

	cancel[eleName] = false;
}

function hover(ele) {
	ele.style.color = '#FFFFFF';
	ele.style.backgroundColor = '#316AC5';
	ele.style.cursor = 'default';
}

function nohover(ele) {
 	ele.style.color = '#000000';
	ele.style.backgroundColor = '#FFFFFF';
	ele.style.cursor = 'auto';
}

function openCatalog(catalogNames) {
	var ele = document.getElementById("selectCat");
	var value = dwr.util.getValue(ele);

	if ((catalogNames && catalogNames.indexOf(value) > -1) ||value == "" || value == "&nbsp;" || value == "none") {
 		// do nothing
 	} else if (value == "Select multiple...") {
 		document.getElementById("singleCatalogSelect").style.display = "none";
 		showhide("multipleCatalogSelect", "blind", { duration: 0.7 });
 		fadeout("multipleCatalogSelect", 5);
 		ele.selectedIndex = 0;
 	} else if (value == "Greeting Cards") {
 		window.location.href = "greeting.jsp?loginAlert=true&language=" + currentLanguage;
 	} else {
 		if (catalogNames && catalogNames.indexOf("Greeting Cards") > -1) {
 	 		document.singleCatalogForm.action = "RecordViewPost.jsp";
 	 		document.singleCatalogForm.catalog.value = value;
 		}
 		
 		document.singleCatalogForm.rows.value = rows;
 		document.singleCatalogForm.cols.value = cols;
 		document.singleCatalogForm.submit();
 	}
}

function openMultiCatalog() {
// check if something is selected first!
	document.multipleCatalogForm.rows.value = rows;
	document.multipleCatalogForm.cols.value = cols;
	document.multipleCatalogForm.submit();
}

function switchToBasket() {
	if (currentCollection == "SearchResult") {
		leftColumnText = dwr.util.getValue("leftColumn");
		rightColumnText = dwr.util.getValue("rightColumn");
	}

	if (currentCollection == "Artist") {
		artistView = true;
	}
	
	currentRecordView = "CollBasket_ThumbnailView";
	currentCollection = "CollBasket";
	
	enableCollectionButtonGroup(false, false, true);

	dwr.util.setValue("leftColumn", getFilledDisplayLeftColumnTemplate());
	dwr.util.setValue("rightColumn", getFilledDisplayRightColumnTemplate());
	
	recordInfoShowing[currentCollection] = false;
	recordInfoBuildingUp[currentCollection] = false;
	recordInfoBuildingDown[currentCollection] = false;
	recordInfoHide[currentCollection] = false;
	
	CollectionHandler.setSize(getCols(), getRows(), showCurrentRecords);
	//CollectionHandler.getBasketInfo(displayBasketInfo, "CollBasket");
	
	fixIESwitch();
}

function switchToLightBox() {
	if (isGuest && !userEmail) {
		var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=340,height=125";
		var win = window.open("InitUserEmail.jsp", "Init", sOpt);
		
		if (win) {
			win.focus();
		}
		
		return;
	}
	
	if (currentCollection == "SearchResult") {
		leftColumnText = dwr.util.getValue("leftColumn");
		rightColumnText = dwr.util.getValue("rightColumn");
	}

	if (currentCollection == "Artist") {
		artistView = true;
	}
	
	currentRecordView = "LightBox_ThumbnailView";
	currentCollection = "LightBox";
	
	enableCollectionButtonGroup(false, true, false);
	
	dwr.util.setValue("leftColumn", getFilledDisplayLeftColumnTemplate());
	dwr.util.setValue("rightColumn", getFilledDisplayRightColumnTemplate());

	CollectionHandler.setSize(getCols(), getRows(), showCurrentRecords);
	loadCollectionList();
	//CollectionHandler.getBasketInfo(displayBasketInfo, "CollBasket");
	
	fixIESwitch();
}

function switchToSearchResult() {
	CollectionHandler.getRecentSearchQueries(displayRecentSearchQueries);
	
	if (currentCollection != "SearchResult") {
		if (leftColumnText != "" && rightColumnText != "") {
			dwr.util.setValue("leftColumn", leftColumnText);
			dwr.util.setValue("rightColumn", rightColumnText);
		} else {
			dwr.util.setValue("leftColumn", getFilledDisplayLeftColumnTemplate());
			dwr.util.setValue("rightColumn", getFilledDisplayRightColumnTemplate());
		}
	}

	if (artistView) {
		currentRecordView = "Artist_ThumbnailView";
		currentCollection = "Artist";
	} else {
		currentRecordView = "SearchResult_ThumbnailView";
		currentCollection = "SearchResult";
	}
	
	enableCollectionButtonGroup(true, false, false);
	
	CollectionHandler.setSize(getCols(), getRows(), function() {
		showCurrentRecords(currentPage);
	});
	//document.getElementById("basketInfo").style.display = "none";
	//CollectionHandler.getBasketInfo(displayBasketInfo, "CollBasket");

	fixIESwitch();
}

function fixIESwitch() {
	if (navigator.userAgent.indexOf("MSIE") >= 0) {
		window.setTimeout("fixIESwitch2()", 500);
	}
}
		
function fixIESwitch2() {
		if (document.getElementById("centerColumn").offsetTop == 101) {
			document.getElementById("centerColumn").style.marginTop = "5px";
		} else if (document.getElementById("centerColumn").offsetTop == 114) {
		} else if (document.getElementById("centerColumn").offsetTop == 127) {
			document.getElementById("centerColumn").style.marginTop = "-8px";
		}
}

function enableCollectionButtonGroup(searchResult, lightbox, basket) {
	handleCollectionButton(document.getElementById("butSearchResult"), searchResult);
	handleCollectionButton(document.getElementById("butLightBox"), lightbox);
	handleCollectionButton(document.getElementById("butBasket"), basket);
}

function handleCollectionButton(ele, on) {
	if (ele) {
		if (on) {
			ele.className = "current";
		} else {
			ele.className = "";
			ele.style.backgroundImage='url(images/img_centerNav_left.gif)';
		}
	}
}

function handleButtonStatus(ele, on) {
	if (ele.className != "current") {
		if (on) {
			ele.style.backgroundImage='url(images/img_centerNav_left_on.gif)';
		} else {
			ele.style.backgroundImage='url(images/img_centerNav_left.gif)';
		}
	}
}

function setAssetAction(catalogID, recordID) {
	var ele = document.getElementById("LoadingText");

	ele.style.left = (mouseX) + "px";
	ele.style.top = (mouseY + 21) + "px";
	ele.style.display = "block";

	var action = dwr.util.getValue("downloadOptions" + catalogID + "x" + recordID);

	CollectionHandler.setAssetAction(currentCollection, catalogID, recordID, action, assetActionSet);
}

function assetActionSet(action) {
	var ele = document.getElementById("LoadingText");
	ele.style.display = "none";

	if (!action) {
		alert(messages["conversion_failed"]);
	}
}

function setAssetActions(catalogID, recordID) {
	var ele = document.getElementById("LoadingText");

	ele.style.left = (mouseX) + "px";
	ele.style.top = (mouseY + 21) + "px";
	ele.style.display = "block";

	var action = dwr.util.getValue("conversionList" + catalogID + "x" + recordID);

	CollectionHandler.setAllAssetActions(currentCollection, action, assetActionsSet);
}

function assetActionsSet(action) {
	var ele = document.getElementById("LoadingText");
	ele.style.display = "none";

	if (!action) {
		alert(messages["conversion_failed"]);
	} else {
		var conversionLists = document.getElementsByClassName("conversionList");
	
		for (var i=0; i < conversionLists.length; i++) {
			dwr.util.setValue(conversionLists[i], action);
		}
	}
}

function setSorting(ele) {
	var collections = new Array(3);

	collections[0] = "SearchResult";
	collections[1] = "LightBox";
	collections[2] = "CollBasket";
	
	CollectionHandler.setSorting(collections, dwr.util.getValue(ele), sortingSet);
}

function sortingSet(success) {
	if (success) {
		if (numRecordsFound > 0) {
			showCurrentRecords();
		}
	} else {
		alert(messages["sorting_failed"]);
	}
}

function setSortingDirection(ele) {
	var collections = new Array(3);

	collections[0] = "SearchResult";
	collections[1] = "LightBox";
	collections[2] = "CollBasket";
	
	CollectionHandler.setSortingDirection(collections, dwr.util.getValue(ele), sortingDirectionSet);
}

function sortingDirectionSet(success) {
	if (success) {
		if (numRecordsFound > 0) {
			showCurrentRecords();
		}
	} else {
		alert(messages["sorting_failed"]);
	}
}

function search(){
	var formElements = searchWindow.document.forms[0].elements;
	var queryItems = new Array();
	var combine;
	var counter = 0;
	
	for(var i = 0;i < formElements.length; i++){
		if (formElements[i].name == "queryItem") {
			queryItems[counter++] = formElements[i].value;
		} else if (formElements[i].name == "combine") {
			combine = formElements[i].value;
		}
	}
	
	lastSearchWord = messages["advanced_search"];
	dwr.util.setValue("assets","<br /><br /><br /><br /><center>" + getLoadingText() + "</center>");
	CollectionHandler.search(currentCollection, queryItems, combine, displayResultRecords);
}

function fillSearchField(ele) {
	document.getElementById('searchfield').value = ele.innerHTML;
	hide('recentSearch');
	searchQuick("new");
}

function searchQuick(type) {
	var index = 0;
	var quickSearchFields = new Array();

	for (var i = 0; i < document.quickSearchForm.quickSearchField.length; i++) {
	   	if (document.quickSearchForm.quickSearchField[i].checked == true) {
				quickSearchFields[index] = createQuickSearchField(document.quickSearchForm.quickSearchField[i].value);
				index++;
	   	}
 	}

	quickSearchFields[index] = createQuickSearchField("Reference No");
	index++;
	
	if (index < 1) {
		alert(messages["select_search_field"]);
	} else {
		lastSearchWord = "\"" + document.getElementById('searchfield').value + "\"";
		dwr.util.setValue("assets", "<br /><br /><br /><br /><center>" + getLoadingText() + "</center>");
		
		dwr.engine.beginBatch();
		CollectionHandler.searchQuick(currentCollection, quickSearchFields, document.getElementById('searchfield').value, "and", type, displayResultRecords);
		CollectionHandler.getRecentSearchQueries(displayRecentSearchQueries);
		dwr.engine.endBatch();
	}
}

var catalogSearchTerm;
function searchCatalogs(searchTerm, doNotLog) {
	if (!doNotLog) {
		doNotLog = false;
	}

	var quickSearchFields = new Array();

	quickSearchFields[0] = createQuickSearchField("Artist");
	quickSearchFields[1] = createQuickSearchField("Categories");
	quickSearchFields[2] = createQuickSearchField("Keywords");
	quickSearchFields[3] = createQuickSearchField("Asset Name");

	catalogSearchTerm = searchTerm;
	
	$("searchLoading").style.display = "";
	
	CollectionHandler.searchCatalogs("Overview", quickSearchFields, catalogSearchTerm, "and", doNotLog, displayResultCatalogs);
}

function displayResultCatalogs(catalogs) {
	$("searchLoading").style.display = "none";

	$("flashResults").style.display = "none";
	$("contentResults").style.display = "";
	
	var count = 0;
	
	count += showCatalogValue(catalogs, "0-5 Years");
	count += showCatalogValue(catalogs, "5 Years To Young Adult");
	count += showCatalogValue(catalogs, "Older And Real Styles");
	count += showCatalogValue(catalogs, "Greeting Cards");
	count += showCatalogValue(catalogs, "Photography");
	count += showCatalogValue(catalogs, "Art For Posters");
	count += showCatalogValue(catalogs, "Art Licensing");

	dwr.util.setValue("resultsSearchTerm", catalogSearchTerm);
	dwr.util.setValue("resultsCount", count);
	
	initCloud();
}

function openResultCatalog(catalog) {
	if (catalog == "greet") {
		if (location.pathname.indexOf("greeting.jsp") > -1) {
			document.forms.login.searchTerm.value = catalogSearchTerm;
			
			loginAlert();
		} else {
			window.location.href = "greeting.jsp?loginAlert=true&searchTerm=" + escape(catalogSearchTerm) + "&language=" + currentLanguage;
		}
	} else {
		window.location.href = "RecordView.jsp?catalog=" + catalog + "&searchTerm=" + escape(catalogSearchTerm) + "&language=" + currentLanguage;
	}
}

function initGreeting(searchTerm, showLoginAlert, message) {
	if (showLoginAlert && showLoginAlert != "null") {
		loginAlert();
	}
	
	if (message && message == "wrongpass") {
		$("greetingMovies").style.display = "none";
		$("greetingMessage").style.display = "";
	}
}

function initCloud() {
	CollectionHandler.getSearchTerms(displayCloud);
}

function redoSearch(searchTerm) {
	if (searchTerm && searchTerm != "null") {
		searchCatalogs(searchTerm, true);

		dwr.util.setValue("searchfield", searchTerm);
	}
}

function displayCloud(searchTerms) {
	var text = "";
	var page = location.pathname;
	var index = page.lastIndexOf("/");
	
	if (index > -1) {
		page = page.substr(index + 1);
	}
	
	if (page.indexOf("?") > -1) {
		page += "&searchTerm=";
	} else {
		page += "?searchTerm=";
	}
	
	for (var i=0; i < searchTerms.length; i++) {
		text += " <a class=\"searchTermLinks\" href=\"" + page + searchTerms[i] + "&language=" + currentLanguage + "\">" + searchTerms[i] + "</a>";
	}
	
	dwr.util.setValue("tags", text);
}

/*
function loadArtist(artist) {
	dwr.util.setValue("assets","<br /><br /><br /><br /><center>" + getLoadingText() + "</center>");
	CollectionHandler.searchArtist(currentCollection, artist, displayResultRecords);
}
*/

function loadArtist(catalog, artist) {
	window.open("LoadArtist.jsp?catalogName=" + escape(catalog) + "&artist=" + artist + "&size=" + currentSize, "_blank", "height=715,location=no,menubar=no,status=no,toolbar=no,width=880,resizable=yes,scrollbars=yes");
}

function showCatalogValue(catalogs, name) {
	var count;
	
	if (catalogs) {
		count = catalogs[name];
	}
	
	if (!count || count < 1) {
		count = 0;
	}

	dwr.util.setValue("results" + name.replace(/ /g, ""), count);
	
	return count;
}

function searchCategory(catalogID, categoryID, categoryName) {
	var ele = document.getElementById("category" + catalogID + "x" + categoryID);
	lastSearchWord = messages["category"] + " \"" + categoryName + "\"";
	
	dwr.util.setValue("assets", "<br /><br /><br /><br /><center>" + getLoadingText() + "</center>");
	CollectionHandler.searchCategory(currentCollection, catalogID, categoryID, displayResultRecords);
}

function displayRecentSearchQueries(recentSearchesData) {
	if (recentSearchesData) {
		var text = "";
		
		for (i=0; i < recentSearchesData.length; i++) {
			text += "<div class=\"recentSearchItem\" onmouseover=\"hover(this);\" onclick=\"fillSearchField(this);\" onmouseout=\"nohover(this);\">" + recentSearchesData[i] + "</div>\n";
		}
		
		dwr.util.setValue("recentSearchQueries", text);
	} else {
		dwr.util.setValue("recentSearchQueries", "");
	}
}

function clearRecentSearchQueries() {
	hide('recentSearch');
	CollectionHandler.clearRecentSearchQueries(displayRecentSearchQueries);
}

function fillSearchQuery(ele) {
	document.getElementById('searchfield').value = ele.innerHTML;
	hide('recentSearch');
	lastSearchWord = messages["saved_query"] + " \"" + ele.innerHTML + "\"";
	dwr.util.setValue("assets", "<br /><br /><br /><br /><center>" + getLoadingText() + "</center>");
	CollectionHandler.searchRecordQuery(currentCollection, ele.innerHTML, displayResultRecords);
}

function findAll() {
	document.getElementById('searchfield').value = "";
	document.quickSearchForm.submit();
}

function displayResultRecords(num) {
	var ele = document.getElementById("LoadingText");
	ele.style.display = "none";
	
	if (currentCollection == "SearchResult") {
		document.getElementById('searchfield').value = "";
	}
	
	if (num > 0) {
		displayRecordsFound(num);
		showCurrentRecords();
		dwr.util.setValue("secondaryNav", getFilledDisplaySecondaryNavTemplate());
	} else {
		dwr.util.setValue("recordsFound", "<br />");
		dwr.util.setValue("pageNav", "<br />");
		dwr.util.setValue("secondaryNav", "<br />");
		dwr.util.setValue("assets", getNoRecordsText());
		dwr.util.setValue("recordsFound2", "<br />");
		dwr.util.setValue("pageNav2", "<br />");

		if (searchWindow && !searchWindow.closed) {
			searchWindow.closeIt();
		}
	}
}

function displayRecordsFound(num) {
	numRecordsFound = num;
	
	if (num > 0) {
		var text = getFilledDisplayRecordsFoundTemplate(num, Math.ceil(num / (cols*rows)));
		
		if (currentCollection == "SearchResult" && lastSearchWord && lastSearchWord.length > 2 && lastSearchWord != "null") {
			text += " for " + lastSearchWord;
		}
		
		dwr.util.setValue("recordsFound", text);
		dwr.util.setValue("recordsFound2", text);
	} else {
		dwr.util.setValue("recordsFound", "<br />");
		dwr.util.setValue("recordsFound2", "<br />");
	}
}

function showCurrentRecords(page) {
	dwr.util.setValue("secondaryNav", getFilledDisplaySecondaryNavTemplate());
	
	if (page) {
		showRecords(page);
	} else {
		showRecords(-1);
	}
	
	CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
}

function showRecords(page) {
	dwr.util.setValue("assets", "<br /><br /><br /><br /><center>" + getLoadingText() + "</center>");

	if (useJSPageDesignForRecords) {
		dwr.engine.beginBatch();
		CollectionHandler.getRecords(currentRecordView, recordDisplayFields, recordDisplayNotInCollectionNames, page, displayRecords);
		CollectionHandler.getPageNumbers(currentRecordView, maxPagesForNavigation, displayPageNavigation);
		if (currentCollection == "SearchResult") {
			CollectionHandler.getHistoryActions(displayHistoryActions);
		}
		if (isNaN(page) && page.indexOf("action: ") == 0) {
			CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
		}
		dwr.engine.endBatch();
	} else if (useXSL){
		displayRecordsXML("xml/Records.xml.jsp?collection=" + currentCollection + "&page=" + page, true, function() {
			dwr.engine.beginBatch();
			CollectionHandler.getPageNumbers(currentRecordView, maxPagesForNavigation, displayPageNavigation);
			if (isNaN(page) && page.indexOf("action: ") == 0) {
				CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
			} else if (currentCollection == "SearchResult") {
				CollectionHandler.getHistoryActions(displayHistoryActions);
			}
			dwr.engine.endBatch();
			
			if (currentCollection == "CollBasket") {
				colorCollBasket();
			}
		});
	} else {
		dwr.engine.beginBatch();
		CollectionHandler.getRecordsText(currentCollection, page, displayRecords);
		CollectionHandler.getPageNumbers(currentRecordView, maxPagesForNavigation, displayPageNavigation);
		dwr.engine.endBatch();
	}
}

function displayRecords(recordsData) {
	window.scrollTo(0, 0);

	var text = "";

	if (recordsData && isObject(recordsData)) {
		currentRecords[currentCollection] = new Object();
	
		if (recordsData.length < 1) {
			dwr.util.setValue("secondaryNav", "<br />");
		 	text = getNoRecordsText();
		} else {
			for (var i=0; i < recordsData.length; i++) {
				text += getFilledDisplayRecordsTemplate(recordsData[i]);
			
				var catalogID = recordsData[i].catalogID;
				var recordID = recordsData[i].recordID;
				currentRecords[currentCollection][catalogID + "x" + recordID] = recordsData[i];
			}
		} 
	} else {
		if (recordsData) {
			text = recordsData;
		} else {
			dwr.util.setValue("secondaryNav", "<br />");
			$("zoomSlider").style.display = "none";
	 		text = getNoRecordsText();
		} 
	}
	
	dwr.util.setValue("assets", text);
	
	if (searchWindow && !searchWindow.closed) {
		searchWindow.closeIt();
	}
	
	if (currentCollection == "CollBasket") {
		colorCollBasket();
	}
}

function displayHistoryActions(actions) {
	dwr.util.removeAllOptions("history");

	if (actions) {
		dwr.util.addOptions("history", actions);
		
		$("history").selectedIndex = $("history").length - 1;
	}
}

function redoAction() {
	var action = dwr.util.getValue("history");
	
	lastSearchWord = "";
	showRecords(action);
}

function historyBack() {
	var ele = $("history");
	
	if (ele.selectedIndex > 0) {
		ele.selectedIndex--;
		redoAction();
	}
}

function historyForward() {
	var ele = $("history");
	
	if (ele.selectedIndex < ele.options.length - 1) {
		ele.selectedIndex++;
		redoAction();
	}
}

function colorCollBasket() {
	var eles = getElementsByClass("div", "assetRows");
		
	for (var i=0; i < eles.length; i++) {
		if ((i+1) % 2 != 0) {
			eles[i].className = "odd assetRows";
		} else {
			eles[i].className = "assetRows";
		}
	}
}

function getElementsByClass(tagName, className) {
	var eles = new Array();
	var index = 0;
	var allEles = document.getElementsByTagName(tagName);
	
	for (var i=0; i < allEles.length; i++) {
		if (allEles[i].className.indexOf(className) > -1) {
			eles[index] = allEles[i];
			index++;
		}
	}

	return eles;
}

function displayPageNavigation(data) {
	if (data) {
		if (currentCollection == "SearchResult") {
			currentPage = data["currentPage"];
		}
		
 		var text = getFilledDisplayNavigationTemplate(data);
 	
		dwr.util.setValue("pageNav", text);
		dwr.util.setValue("pageNav2", text);
	} else {
		if (currentCollection == "SearchResult") {
			currentPage = "";
		}
		
		dwr.util.setValue("pageNav", "<br />");
		dwr.util.setValue("pageNav2", "<br />");
	}
}

function loadCategoryTree(rootCategory, page) {
	if (useXSL) {
		displayCategoryTreeXML("xml/" + page + ".xml.jsp?recordView=" + currentRecordView + "&rootFilterCategory=" + rootCategory, "scrollNavContent", false);
	} else {
		CollectionHandler.loadCategoryTree(currentRecordView, rootCategory, page, displayCategoryTree);
	}
}

function changeRootCategory(rootCategory, page) {
	if (useXSL) {
		displayCategoryTreeXML("xml/" + page + ".xml.jsp?recordView=" + currentRecordView + "&rootFilterCategory=" + rootCategory, "scrollNavContent", false);
	} else {
		CollectionHandler.changeRootCategory(currentRecordView, rootCategory, page, displayCategoryTree);
	}
}

function displayCategoryTree(data) {
	dwr.util.setValue("scrollNavContent", data);
	resizeCategoryTree();
}

function expandCollapse(catalogID, categoryID, categoryName, action, tree) {
	dwr.util.setValue("category" + catalogID + "x" + categoryID, getLoadingText());	

	if (useXSL) {
		displayCategoryTreeXML("xml/" + tree + ".xml.jsp?recordView=" + currentRecordView + "&catalogID=" + catalogID + "&categoryID=" + categoryID + "&action=" + action, "category" + catalogID + "x" + categoryID, true);
	} else {
		CollectionHandler.processCategory(catalogID, categoryID, categoryName, action, tree, displayCategory);
	}
}

function displayCategory(categoryData) {
	var text = getFilledDisplayCategoryTemplate(categoryData);
	
	if (categoryData["isExpanded"]) {
		for (var key in categoryData["subCategories"]) {
			var subCategoryData = categoryData["subCategories"][key];
			
			text += getFilledDisplaySubCategoryHeaderTemplate(subCategoryData);
			text += getFilledDisplayCategoryTemplate(subCategoryData);
			text += getFilledDisplaySubCategoryFooterTemplate(subCategoryData);
		}
	}

	dwr.util.setValue(getID(categoryData), text);	

	resizeCategoryTree();
}

function getID(categoryData) {
	return "category" + categoryData["catalogID"] + "x" + categoryData["id"];
}

function getLoadingText() {
	return "<div style='text-decoration:blinking; text-transform:uppercase; margin-top:10px; margin-bottom:10px'><blink>" + messages["loading"] + "</blink></div>";
}

function getNoRecordsText() {
	return "<br /><br /><br /><br /><center>" + messages["no_records"] + "</center>";
}

function showQuickInfo(index) {
	showHourglass();
	dwr.util.setValue("assetQuickInfo", "<br /><br /><center>" + messages["loading"] + "</center><br /><br />");
	CollectionHandler.getRecordInfo(currentRecordView, index, quickInfoDisplayFields, quickInfoDisplayNotInCollectionNames, displayQuickInfo);
}

var recordInfoShowing = new Object();
var recordInfoBuildingUp = new Object();
var recordInfoBuildingDown = new Object();
var recordInfoHide = new Object();
recordInfoShowing[currentCollection] = false;
recordInfoBuildingUp[currentCollection] = false;
recordInfoBuildingDown[currentCollection] = false;
recordInfoHide[currentCollection] = false;
function displayQuickInfo(recordInfo) {
	dwr.util.setValue("assetQuickInfo", getFilledDisplayQuickInfoTemplate(recordInfo));

	if (!recordInfoShowing[currentCollection]) {
		recordInfoShowing[currentCollection] = true;
		recordInfoBuildingUp[currentCollection] = true;
		Effect.BlindDown("assetQuickInfo", { afterFinish: recordInfoBuilt });
	}
}

function recordInfoBuilt(obj) {
	recordInfoBuildingUp[currentCollection] = false;
	
	if (recordInfoHide[currentCollection]) {
		hideQuickInfo(0);
		recordInfoHide[currentCollection] = false;
	} else {
		showDefaultPointer();
	}
}

function recordInfoGone(obj) {
	recordInfoShowing[currentCollection] = false;
	recordInfoBuildingDown[currentCollection] = false;
	showDefaultPointer();
}

function fadeoutQuickInfo(id, emptyLines) {
	var sec = 150;
	
	clearTimeout(timeout["QuickInfo" + id]);
	timeout["QuickInfo" + id] = setTimeout("hideQuickInfo('" + id + "', " + emptyLines + ")", sec);
	cancel["QuickInfo" + id] = false;
}

function hideQuickInfo(id, emptyLines) {
	if (recordInfoShowing[currentCollection] && !recordInfoBuildingDown[currentCollection] && !cancel["QuickInfo" + id]) {
		if (recordInfoBuildingUp[currentCollection]) {
			recordInfoHide[currentCollection] = true;
		} else {
			recordInfoBuildingDown[currentCollection] = true;
			showHourglass();
			Effect.BlindUp("assetQuickInfo", { afterFinish: recordInfoGone });
		}
	}
}
	
function displayBasketInfo(basketInfo) {
/*	var ele = document.getElementById("basketInfo");

	if (basketInfo["numOfRecords"] > 0) {
		if (dwr.util.getValue("basketInfo") == "" || dwr.util.getValue("basketInfo") == "<br /><br />" || dwr.util.getValue("basketInfo") == "<br><br>") {
			ele.style.display = "none";
		}
		
		dwr.util.setValue("basketInfo", getFilledDisplayBasketInfoTemplate(basketInfo));
		
		if (ele.style.display == "none") {
			Effect.BlindDown("basketInfo");
		}
	} else {
		Effect.BlindUp("basketInfo", { afterFinish: hideBasketInfo});
	}*/
}

function hideBasketInfo() {
/*	if (currentCollection == "SearchResult") {
		dwr.util.setValue("basketInfo", "");
	} else {
		dwr.util.setValue("basketInfo", "<br /><br />");
	}

	Effect.BlindDown("basketInfo");*/
}

function saveCollection(name, shared, overwriteID) {
	var collectionInfo = new Object();
	collectionInfo["name"] = name;
	collectionInfo["shared"] = shared;
	collectionInfo["id"] = overwriteID;

	newLightBox = name;
	
	CollectionHandler.saveCollection(currentCollection, collectionInfo, collectionSaved);
}

function collectionSaved(success) {
	var text = "";
	
	if (success) {
		if (opener) {
			opener.loadCollectionList();
		}

		text = messages["collection_saved"];
		
		dwr.util.setValue("LightBoxLink", messages["lightbox"] + " (" + currentLightBox + ")");
	} else {
		text = messages["collection_not_saved"];
	}
	
	text += "<br /><br /><a class=\"linkSecondary\" href=\"javascript:window.close();\">" + messages["close_window"] + "</a>";
	
	dwr.util.setValue("text", text);
}

function sendCollection(recipient, subject, text) {
	CollectionHandler.sendCollection(currentCollection, recipient, subject, text, collectionSent);
}

function collectionSent(success) {
	var text = "";
	
	if (success) {
		text = messages["collection_sent"];
	} else {
		text = messages["collection_not_sent"];
	}
	
	text += "<br /><br /><a class=\"linkSecondary\" href=\"javascript:window.close();\">" + messages["close_window"] + "</a>";
	
	dwr.util.setValue("text", text, { escapeHtml:false });
}

function preLoadCollectionList() {
	if (!isGuest || userEmail) {
		CollectionHandler.loadUserCollectionList(currentCollection, userCollectionListLoaded);
	}
}

function userCollectionListLoaded(collectionInfos) {
	userCollectionList = collectionInfos;
}

function loadCollectionList() {
	dwr.engine.beginBatch();
	CollectionHandler.loadUserCollectionList(currentCollection, displayUserCollectionList);
	dwr.engine.endBatch();
}

function displayUserCollectionList(collectionInfos) {
	displayCollectionList("privateCollections", collectionInfos, false);
	userCollectionList = collectionInfos;
}

function displaySharedCollectionList(collectionInfos) {
	displayCollectionList("sharedCollections", collectionInfos, true);
	sharedCollectionList = collectionInfos;
}

function displayCollectionList(id, collectionInfos, isShared) {
	var text = "";
	
	if (collectionInfos) {
		for (i=0; i < collectionInfos.length; i++) {
			if (isShared) {
				text += getFilledDisplaySharedCollectionListTemplate(collectionInfos[i]);
			} else {
				text += getFilledDisplayPrivateCollectionListTemplate(collectionInfos[i]);
			}
			//text += "<input type='checkbox' id='Col" + collectionInfos[i]["id"] + "' title='Delete Collection' alt='Delete Collection' onclick=\"deleteCollection('" + collectionInfos[i]["id"] + "');\"> <a href=\"javascript:loadCollection('"+ collectionInfos[i]["id"] + "', " + collectionInfos[i]["shared"] + ");\" class=\"linkColl\">" + collectionInfos[i]["name"] + "</a><br />";
		}
	}
	
	dwr.util.setValue(id, text);
}

function loadCollection(id, shared) {
	var collectionInfo = new Object();
	collectionInfo["id"] = id;
	collectionInfo["shared"] = shared;

	if (shared) {
		currentLightBoxName = "";
	} else {
		currentLightBoxName = id;
	}
	
	CollectionHandler.loadCollection(currentCollection, collectionInfo, collectionLoaded);
}

function collectionLoaded(success) {
	dwr.util.setValue("LightBoxLink", messages["lightbox"] + " (" + currentLightBoxName + ")");

	showRecords(-1);
	CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);

	if (dwr.util.getValue("secondaryNav").toLowerCase() == "<br />" || dwr.util.getValue("secondaryNav").toLowerCase() == "<br>") {
		dwr.util.setValue("secondaryNav", getFilledDisplaySecondaryNavTemplate());
	}
}

function createLightBox() {
	var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=340,height=255";
	var win = window.open("InitLightBoxForm.jsp?recordView=" + currentCollection + "_ThumbnailView&closeOnly=true", "Init", sOpt);
	
	if (win) {
		win.focus();
	}
}

function closeLightBox() {
	if (currentLightBoxName) {
		var ele = document.getElementById("LoadingText");

		ele.style.left = (mouseX) + "px";
		ele.style.top = (mouseY + 21) + "px";
		ele.style.display = "block";

		if (currentCollection == "SearchResult") {
			dwr.util.setValue("basketInfo", "");
		} else {
			dwr.util.setValue("basketInfo", "<br /><br />");
		}
		
		CollectionHandler.removeAllSaving(currentCollection, false, displayResultRecords);  	
	
		currentLightBoxName = null;

		dwr.util.setValue("LightBoxLink", messages["lightbox"]);
	}
}


function deleteCollection(id) {
	if (confirm(messages["really_delete_collection"])) {
		if (currentLightBoxName == id) {
			closeLightBox();
		}
		
		CollectionHandler.deleteCollection(id, collectionDeleted);
	}

	var ele = document.getElementById("Col" + id)
	
	if (ele) {
		ele.checked = false;
	}
}

function collectionDeleted(success) {
	if (success) {
		loadCollectionList();
	}
}

function handleCollection(collection, catalogID, recordID) {
	if (collection == "CollBasket" && displayBasketPermissionWarning) {
		displayBasketWarning();
	}
	
	if ((!currentLightBoxName || currentLightBoxName.length < 1) && collection == "LightBox") {
		var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=340,height=255";
		var win = window.open("InitLightBoxForm.jsp?recordView=" + collection + "_ThumbnailView&catalogID=" + catalogID + "&recordID=" + recordID, "Init", sOpt);
		
		if (win) {
			win.focus();
		}
	} else {
		if (isGuest && !userEmail) {
			var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=340,height=125";
			var additional = "";
			
			if (collection == "CollBasket") {
				additional = "?disableSwitch=true&catalogID=" + catalogID + "&recordID=" + recordID;
			}
			
			var win = window.open("InitUserEmail.jsp" + additional, "Init", sOpt);
			
			if (win) {
				win.focus();
			}
			
			return;
		}
		
		var ele = document.getElementById("LoadingText");

		ele.style.left = (mouseX) + "px";
		if (currentRecordView == currentCollection + "_Preview") {
			ele.style.top = (mouseY - 13) + "px";
		} else {
			ele.style.top = (mouseY + 21) + "px";
		}
		ele.style.display = "block";

		if (collection == "CollBasket") {
			//dwr.engine.beginBatch();
			CollectionHandler.change(collection, catalogID, recordID, changeImage);  	
			//CollectionHandler.getBasketInfo(displayBasketInfo, "CollBasket");
			//dwr.engine.endBatch();
		} else {
			CollectionHandler.change(collection, catalogID, recordID, changeImage);  	
		}
	}
}

function handleCollectionCurrentRecords(collection) {
	if (collection == "CollBasket") {
		displayBasketWarning();
	}
	
	if ((!currentLightBoxName || currentLightBoxName.length < 1) && collection == "LightBox") {
		var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=340,height=255";
		var win = window.open("InitLightBoxForm.jsp?recordView=" + collection + "_ThumbnailView&records=" + getCurrentRecordsList(), "Init", sOpt);
		
		if (win) {
			win.focus();
		}
	} else {
		if (isGuest && !userEmail) {
			var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=340,height=125";
			var additional = "";
			
			if (collection == "CollBasket") {
				additional = "?disableSwitch=true&records=" + getCurrentRecordsList();
			}
			
			var win = window.open("InitUserEmail.jsp", "Init", sOpt);
			
			if (win) {
				win.focus();
			}
			
			return;
		}
		
		var ele = document.getElementById("LoadingText");

		ele.style.left = (mouseX) + "px";
		ele.style.top = (mouseY + 21) + "px";
		ele.style.display = "block";

		if (collection == "CollBasket") {
			//dwr.engine.beginBatch();
			CollectionHandler.addCurrentRecords(collection, getCurrentRecordsList(), changeImages);  	
			//CollectionHandler.getBasketInfo(displayBasketInfo, "CollBasket");
			//dwr.engine.endBatch();
		} else {
			CollectionHandler.addCurrentRecords(collection, getCurrentRecordsList(), changeImages);  	
		}
	}
}

function handleCollectionAll(collection) {
	if (numRecordsFound > maxRecordsToProcess) {
		alert(messages["add_more_records_1"] + " " + maxRecordsToProcess + " " + messages["add_more_records_2"]);
		return;
	}
	
	if ((!currentLightBoxName || currentLightBoxName.length < 1) && collection == "LightBox") {
		var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=340,height=255";
		var searchWindow = window.open("InitLightBoxForm.jsp?recordView=" + collection + "_ThumbnailView", "Init", sOpt);
	} else {
		if (isGuest && !userEmail) {
			var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=340,height=125";
			var win = window.open("InitUserEmail.jsp", "Init", sOpt);
			
			if (win) {
				win.focus();
			}
			
			return;
		}
		
		var ele = document.getElementById("LoadingText");

		ele.style.left = (mouseX) + "px";
		ele.style.top = (mouseY + 21) + "px";
		ele.style.display = "block";

		if (collection == "CollBasket") {
			//dwr.engine.beginBatch();
			CollectionHandler.addAll(currentRecordView, collection, changeImages);  	
			//CollectionHandler.getBasketInfo("CollBasket", displayBasketInfo);
			//dwr.engine.endBatch();
		} else {
			CollectionHandler.addAll(currentRecordView, collection, changeImages);  	
		}
	}
}

function displayBasketWarning() {
	if (!basketPermissionsWarningDisplayed) {
		alert("You need to confirm trading terms with Advocate before you download.\nA message has been sent to Advocate who will contact you.\nNote office hours are UK GMT.\nA low res will be sent for presentation instead");
	}
	
	basketPermissionsWarningDisplayed = true;
}

function removeAll() {
	var ele = document.getElementById("LoadingText");

	ele.style.left = (mouseX) + "px";
	ele.style.top = (mouseY + 21) + "px";
	ele.style.display = "block";

	if (currentCollection == "SearchResult") {
		dwr.util.setValue("basketInfo", "");
	} else {
		dwr.util.setValue("basketInfo", "<br /><br />");
	}
	
	CollectionHandler.removeAllSaving(currentCollection, true, displayResultRecords);  	
}

function changeImages(collectionHandlerBeans) {
	for (var i=0; i < collectionHandlerBeans.length; i++) {
		changeImage(collectionHandlerBeans[i]);
	}
}

function changeImage(collectionHandlerBean, isAll) {
	var ele = document.getElementById("LoadingText");
	var left = ele.offsetLeft;
	var top = ele.offsetTop;
	
	ele.style.display = "none";

	var action = "";
	var actionOld = "";
	var collection = collectionHandlerBean["collection"];
	var inCollection = collectionHandlerBean["inCollection"];
	var catalogID = collectionHandlerBean["catalogID"];
	var recordID = collectionHandlerBean["recordID"];
	var image = document.getElementById("checkImage" + collection + catalogID + "x" + recordID);

	if (image) {
		if (!recordRemoved(collection, inCollection, catalogID, recordID)) {
			var additional = "";
			
			if (image.src.indexOf("_special") > -1) {
				additional = "_special";
			}
			
			if (inCollection) {
				image.src = "images/btn_" + collection.toLowerCase() + "_remove" + additional + ".gif";
				action = messages["remove_from"];
				actionOld = messages["add_to"];
				
				if (isAll) {
					showFadeText("ImagesAddedText", left, top);
				} else {
					showFadeText("ImageAddedText", left, top);
				}
			} else {
				image.src = "images/btn_" + collection.toLowerCase() + "_add" + additional + ".gif";
				action = messages["add_to"];
				actionOld = messages["remove_from"];

				if (isAll) {
					showFadeText("ImagesRemovedText", left, top);
				} else {
					showFadeText("ImageRemovedText", left, top);
				}
			}
		
			if (collection == "CollBasket") {
				collection = messages["basket"];
			} else {
				collection = messages["lightbox"];
			}
	
			var text = dwr.util.getValue("assetBox" + catalogID + "x" + recordID);
			text = text.replace(new RegExp(actionOld + " " + collection, "g"), action + " " + collection);
			dwr.util.setValue("assetBox" + catalogID + "x" + recordID, text);
		}
		
		if (opener) {
			opener.changeImage(collectionHandlerBean);
		}
	}
}

function showFadeText(sourceID, left, top) {
	if ($(sourceID)) {
		var ele = Element.clone($(sourceID), true);
		
		$("bod").appendChild(ele);
		
		ele.style.left = left + "px";
		ele.style.top = top + "px";
		ele.style.display = "block";
	
		Effect.Fade(ele, {
			duration: 2,
			afterFinish: function(effect) {
				effect.element.remove();
			}
		});
	}
}

function recordRemoved(collection, inCollection, catalogID, recordID) {
	if (currentCollection != "SearchResult" && currentCollection == collection && !inCollection) {
		if (!currentRecords[currentCollection]) {
			var found = false;
			var count = 0;
			var lastIndex;
			var assetsDiv = document.getElementById("assets");
			var assetBoxes = assetsDiv.childNodes;
	
			var oldOpenDetails = "openDetails\\(";
			
			for(var i = 0; i < assetBoxes.length; i++) {
				if(assetBoxes[i].className == "assetInfo" || assetBoxes[i].className == "assetRowContainer") {
					if(assetBoxes[i].getAttribute("id") == "assetBox" + catalogID + "x" + recordID) {
						found = true;
					}	else {
						count++;
						lastIndex = assetBoxes[i].getAttribute("index");
						
						if(found) {
							lastIndex--;
							assetBoxes[i].setAttribute("index", lastIndex);
							
							var newBracket = "(" + (lastIndex) + ")";
							
							assetBoxes[i].innerHTML = assetBoxes[i].innerHTML.replace(new RegExp(oldOpenDetails + (lastIndex + 1) + "\\)", "g"), "openDetails" + newBracket);
						}
					}
				}
			}
	
			var assetBox = document.getElementById("assetBox" + catalogID + "x" + recordID);
	
			try {
				document.getElementById("assets").removeChild(assetBox);
				numRecordsFound--;
			} catch (e) {
				var container = document.getElementById("container" + catalogID + "x" + recordID);
				
				document.getElementById("assets").removeChild(container);
				numRecordsFound--;
			}
	
			if(currentCollection == "CollBasket") {
				colorCollBasket();
			}
			
			if (count > 0) {
				if (useXSL){
					displayRecordsXML("xml/Records.xml.jsp?collection=" + currentCollection + "&lastIndex=" + lastIndex + "&num=" + 1, false, function() {
						if (currentCollection == "CollBasket") {
							colorCollBasket();
						}

						dwr.engine.beginBatch();
						CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
						CollectionHandler.getPageNumbers(currentRecordView, maxPagesForNavigation, displayPageNavigation);
						dwr.engine.endBatch();
					});
				} else {
					dwr.engine.beginBatch();
					CollectionHandler.getNewRecordText(currentCollection, lastIndex, 1, displayRecord);
					CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
					CollectionHandler.getPageNumbers(currentRecordView, maxPagesForNavigation, displayPageNavigation);
					dwr.engine.endBatch();
				}
			} else if (numRecordsFound > 0) {
				showRecords('previous');
				CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
			} else {
				dwr.util.setValue("recordsFound", "<br />");
				dwr.util.setValue("pageNav", "<br />");
				dwr.util.setValue("recordsFound2", "<br />");
				dwr.util.setValue("secondaryNav", "<br />");
				dwr.util.setValue("assets", getNoRecordsText());
				dwr.util.setValue("pageNav2", "<br />");
			}
		} else {
			var assetBox = document.getElementById("assetBox" + catalogID + "x" + recordID);
	
			try {
				document.getElementById("assets").removeChild(assetBox);
			} catch (e) {
				var container = document.getElementById("container" + catalogID + "x" + recordID);
				
				document.getElementById("assets").removeChild(container);
			}
	
			if (currentCollection == "CollBasket") {
				colorCollBasket();
			}
	
			var catalogIDs = new Array();
			var recordIDs = new Array();
			var index = 0;
			var found = false;
			
			for(var id in currentRecords[currentCollection]) {
				var catalogIDTmp = currentRecords[currentCollection][id]["catalogID"];
				var recordIDTmp = currentRecords[currentCollection][id]["recordID"];
				
				if (catalogID == catalogIDTmp && recordID == recordIDTmp) {
					delete currentRecords[currentCollection][id];
					numRecordsFound--;
					found = true;
				} else {
					catalogIDs[index] = catalogIDTmp;
					recordIDs[index] = recordIDTmp;
					index++;
					
					if (found) {
						currentRecords[currentCollection][id]["index"]--;
					}
				}
			}
			
			if (index > 0) {
				dwr.engine.beginBatch();
				CollectionHandler.getRecord(currentRecordView, catalogIDs, recordIDs, recordDisplayFields, recordDisplayNotInCollectionNames, displayRecord);
				CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
				CollectionHandler.getPageNumbers(currentRecordView, maxPagesForNavigation, displayPageNavigation);
				dwr.engine.endBatch();
			} else if (numRecordsFound > 0) {
				showRecords('previous');
				CollectionHandler.getNumberOfRecords(currentCollection, displayRecordsFound);
			} else {
				dwr.util.setValue("recordsFound", "<br />");
				dwr.util.setValue("pageNav", "<br />");
				dwr.util.setValue("recordsFound2", "<br />");
				dwr.util.setValue("secondaryNav", "<br />");
				dwr.util.setValue("assets", getNoRecordsText());
				dwr.util.setValue("pageNav2", "<br />");
			}
		}
		
		return true;
	}
	
	return false;
}

function displayRecord(recordData) {
	if (recordData && recordData != null) {
		if (currentRecords[currentCollection]) {
			for (var i=0; i < recordData.length; i++) {
				var text = getFilledDisplayRecordsTemplate(recordData[i]);
	
				var catalogID = recordData[i].catalogID;
				var recordID = recordData[i].recordID;
				currentRecords[currentCollection][catalogID + "x" + recordID] = recordData[i];
				numRecordsFound++;
		
				var newAssetBoxContainer = document.createElement("div");
				newAssetBoxContainer.setAttribute("id", "container" + catalogID + "x" + recordID);
	
				document.getElementById("assets").appendChild(newAssetBoxContainer);
			
				dwr.util.setValue("container" + catalogID + "x" + recordID, text);
			}
		} else {
			if(recordData) {
				var text = dwr.util.getValue("assets") + recordData;
		
				dwr.util.setValue("assets", text);
			}
		}
	} 

	if (currentCollection == "CollBasket") {
		colorCollBasket();
	}
}

function getCurrentRecordsList() {
	var recordsList = "";
	
	if (currentRecords[currentCollection]) {
		for (var index in currentRecords[currentCollection]) {
			if (recordsList.length > 0) {
				recordsList += ",";	
			}
		
			var recordData = currentRecords[currentCollection][index];
			recordsList += recordData.catalogID + ":" + recordData.recordID;
		}
	} else {
		var assetBoxes = document.getElementById("assets").childNodes;
	
		for(var i = 0; i < assetBoxes.length; i++) {
			if(assetBoxes[i].className == "assetInfo" || assetBoxes[i].className == "assetRowContainer") {
				if (recordsList.length > 0) {
					recordsList += ",";	
				}
	
				var assetBoxId = assetBoxes[i].id;
				var simpleId = assetBoxId.substring(8, assetBoxId.length);
				var catalogAndRecordId = simpleId.split("x");
				
				recordsList += catalogAndRecordId[0] + ":" + catalogAndRecordId[1];
			}
		}
	}
	
	return recordsList;
}

function openOldDownload(catalogID, recordID, packaging) {
	//openCreditForm(catalogID, recordID, packaging);
	var s = "Download.jsp?recordView=" + currentRecordView + "&catalogID=" + catalogID + "&recordID=" + recordID + "&packaging=" + packaging;
	var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=no,width=350,height=270";
	var win = window.open(s, "Download", sOpt);
	
	if (win) {
		win.focus();
	}
}

function openDownload(catalogID, recordID) {
	if (termsApproved) {
		var s = "NewDownload.jsp?collection=" + currentCollection + "&catalogID=" + catalogID + "&recordID=" + recordID;
		var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=no,width=330,height=75";
		var win = window.open(s, "Download", sOpt);
		
		if (win) {
			win.focus();
		}
	} else {
		downdloadTermsCallback = function() {
			var s = "NewDownload.jsp?collection=" + currentCollection + "&catalogID=" + catalogID + "&recordID=" + recordID;
			var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=no,width=330,height=75";
			var win = window.open(s, "Download", sOpt);
			
			if (win) {
				win.focus();
			}
		};
	
		var s = "Terms.jsp";
		var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=no,width=420,height=690";
		var win = window.open(s, "Terms", sOpt);
		
		if (win) {
			win.focus();
		}
	}
}

function openOldDownloadAll() {
	//openCreditForm(-1, -1, "zip");
	var s = "DownloadAll.jsp?recordView=" + currentRecordView + "&packaging=zip";
	var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=no,width=300,height=200";
	var win = window.open(s, "Download", sOpt);
	
	if (win) {
		win.focus();
	}
}

function openDownloadAll() {
	if (termsApproved) {
		openDownloadAllApproved();
	} else {
		downdloadTermsCallback = openDownloadAllApproved;
		
		var s = "Terms.jsp";
		var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=no,width=420,height=690";
		var win = window.open(s, "Terms", sOpt);
		
		if (win) {
			win.focus();
		}
	}
}

function openDownloadAllApproved() {
	var s = "NewDownload.jsp?collection=" + currentCollection;
	var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=no,width=330,height=75";
	var win = window.open(s, "Download", sOpt);
	
	if (win) {
		win.focus();
	}
}

function openPrintRecord(catalogID, recordID) {
	var s = "Print.jsp?recordView=" + currentRecordView + "&records=" + catalogID + ":" + recordID;
	var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=no,width=300,height=200";
	var win = window.open(s, "Print", sOpt);
	
	if (win) {
		win.focus();
	}
}

function openPrintCurrentRecords() {
	var s = "Print.jsp?recordView=" + currentRecordView + "&records=" + getCurrentRecordsList();
	var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=no,width=300,height=200";
	var win = window.open(s, "Print", sOpt);
	
	if (win) {
		win.focus();
	}
}

function openPrintAll() {
	if (numRecordsFound > maxRecordsToProcess) {
		alert(messages["print_more_records_1"] + " " + maxRecordsToProcess + " " + messages["print_more_records_2"]);
		return;
	}
	
	var s = "Print.jsp?recordView=" + currentRecordView;
	var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=no,width=300,height=200";
	var win = window.open(s, "Print", sOpt);
	
	if (win) {
		win.focus();
	}
}

function openSearch() {
	var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=100,height=100";
	searchWindow = window.open("SearchForm.jsp?recordView=" + currentRecordView, "Search", sOpt);
	
	if (searchWindow) {
		searchWindow.focus();
	}
}

function openSaveCollection() {
	var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=300,height=140";
	searchWindow = window.open("SaveCollectionForm.jsp?recordView=" + currentRecordView, "Save", sOpt);
	
	if (searchWindow) {
		searchWindow.focus();
	}
}

function openSendCollection() {
	var sOpt = "toolbar=no,scrollbars=no,status=no,menubar=no,resizable=no,location=no,dependent=yes,width=300,height=320";
	searchWindow = window.open("SendCollectionForm.jsp?recordView=" + currentRecordView, "Save", sOpt);
	
	if (searchWindow) {
		searchWindow.focus();
	}
}

function getElement(id,win) {
	doc = win ? win.document : document;
	elem = doc.getElementById ? doc.getElementById(id) : doc.all[id];
	if (!elem)
		alert("element " + id + " not found");
	return elem;
}

function createQuickSearchField(text) {
	var textParts = text.split(",");
	
	if (textParts.length == 1) {
		return new QuickSearchField(textParts[0]);
	}

	return new QuickSearchField(textParts[0], textParts[1]);
}

function Field(name, prefix, suffix, nullValue, length, indicator, removeExtension, type, dateFormat, separator, pathSeparator, categoryLinkText) {
	this.name = name;
	this.prefix = prefix;
	this.suffix = suffix;
	this.nullValue = nullValue;
	this.type = type;
	this.dateFormat = dateFormat;
	this.separator = separator;
	this.pathSeparator = pathSeparator;
	this.categoryLinkText = categoryLinkText;
	
	if (length == null) {
		this.length = -1;
	} else {
		this.length = length;
	}
	
	this.indicator = indicator;

	if (removeExtension == null) {
		this.removeExtension = false;
	} else {
		this.removeExtension = removeExtension;
	}
}

function QuickSearchField(name, comparator) {
	this.name = name;
	this.comparator = comparator;
}

function replace(text, names, values) {
	return replace(text, names, values, true);
}

function replaceAll(text, names, values) {
	return replace(text, names, values, true);
}

function replace(text, names, values, all) {
	for (k=0; k < names.length; k++) {
		var name = "";
		var value = "";
		var rexp = "";
				
		if (isObject(names[k])) {
			name = names[k].name;
		} else {
			name = names[k];
		}

		if (all) {
			rexp = new RegExp("<!--" + name + "-->", "g");
		} else {
			rexp = new RegExp("<!--" + name + "-->");
		}

		if (values[name]) {
			value = values[name];
		} else {
			value = "&nbsp;";
		}	

		text = text.replace(rexp, value);
	}

	return text;
}

function crop(text, length, indicator) {
	if (text.length > length && length > -1) {
		text = text.substring(0, length-1);
		
		if (indicator && indicator.length > 0) {
			text += indicator;
		}
	}
	
	return text;
}

var originalEscape = escape;
escape = function (text, escapeValues) {
	if (!escapeValues) {
		return originalEscape(text);
	}
	
	for (var i=0; i < escapeValues.length; i++) {
		text = text.replace(escapeValues.substr(i, 1), "\\" + escapeValues.substr(i, 1));
	}
	
	return text;
}

function isObject(a) {
    return (a && typeof a == 'object') || typeof a == 'function';
}

function exists(id) {
	var element = document.getElementById(id);
	
	if (element) {
		return true;
	}
	
	return false;
}

function loadXML(url, loadXMLCallback) {
	new Ajax.Request(url, {
		onSuccess: function(transport) {
			loadXMLCallback(transport.responseXML);
		},
		onFailure: function(){
			alert('Something went wrong...');
		}
	});
}

function checkXSL(counterName, checkXSLCallback) {
	if (counters[counterName] > 50) {
		alert("XSL could not be loaded");
		
		return;
	}
	
	counters[counterName]++;
	
	window.setTimeout(checkXSLCallback, 200);
}

var counters = new Object();
counters["xslRecords"] = 1;
function displayRecordsXML(url, overwrite, callbackFunction) {
	if (!xslRecords) {
		checkXSL("xslRecords", function() {
			displayRecordsXML(url, overwrite, callbackFunction);
		});
		
		return;
	}

	counters["xslRecords"] = 1;
	
	displayXML(url, xslRecords, "assets", overwrite, function(success) {
		if (!success) {
			dwr.util.setValue("secondaryNav", "<br />");
			dwr.util.setValue("assets", getNoRecordsText());
		}

		if (callbackFunction) {
			callbackFunction();
		}
	});
}

counters["xslCategoryTree"] = 1;
function displayCategoryTreeXML(url, eleName, overwrite) {
	if (!xslCategoryTree) {
		checkXSL("xslCategoryTree", function() {
			displayCategoryTreeXML(url, eleName, overwrite);
		});
		
		return;
	}
	
	counters["xslCategoryTree"] = 1;

	var ele = $(eleName);

	displayXML(url, xslCategoryTree, eleName, true, function(success) {
		if (!success) {
			dwr.util.setValue(eleName, "");
		} else {
			if (overwrite) {
				var child = ele.childNodes[0];
				ele.removeChild(child);
				ele.parentNode.replaceChild(child, ele);
			}
			
			resizeCategoryTree();
		}
	});
}

function displayXML(url, xsl, id, overwrite, displayXMLCallback) {
	loadXML(url, function(xml) {
		var collections = xml.getElementsByTagName("collection");
		
		if (collections && collections.length > 0) {
			var collection;
			
			if (window.ActiveXObject) {
				collection = collections[0].text;
			} else {
				collection = collections[0].textContent;
			}
			
			if (currentCollection != collection) {
				return;
			}
		}
		
		if (overwrite) {
			dwr.util.setValue(id, "");

			var nodes;
			
			if (window.ActiveXObject) {
				nodes = xml.lastChild;
			} else {
				if (xml.childNodes) {
					nodes = xml.childNodes[0];
				}
			}

			if (!nodes || !nodes.lastChild || !nodes.lastChild.childNodes || nodes.lastChild.childNodes.length == 0) {
				displayXMLCallback(false);
				
				return;
			}
		}

		// code for IE
		if (window.ActiveXObject) {
			var result = xml.transformNode(xsl);
			
			if (overwrite) {
				document.getElementById(id).innerHTML = result;
			} else {
				document.getElementById(id).innerHTML = dwr.util.getValue(id) + result;
			}
		} else if (document.implementation && document.implementation.createDocument) {
			// code for Mozilla, Firefox, Opera, etc.
			var xsltProcessor = new XSLTProcessor();

			xsltProcessor.importStylesheet(xsl);
			var result = xsltProcessor.transformToFragment(xml, document);

			document.getElementById(id).appendChild(result);
		}
		
		timeoutCounter = 30;

		displayXMLCallback(true);
	});
}

function closeIt() {
	setTimeout("window.close()", 100);
}

function executeScripts(div) {
	var scripts = div.getElementsByTagName("script");
	
    for (var i=0; i < scripts.length; i++) {  
        eval(scripts[i].text);  
   }  
}

var IE = document.all?true:false;

if (!IE) document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = getMouseXY;

var mouseX = 0;
var mouseY = 0;

function getMouseXY(e) {
  if (IE) {
  	try {
	    mouseX = event.clientX + document.body.scrollLeft;
	    mouseY = event.clientY + document.body.scrollTop;
    } catch (e) {}
  } else {
    mouseX = e.pageX;
    mouseY = e.pageY;
  }  

  if (mouseX < 0){mouseX = 0};
  if (mouseY < 0){mouseY = 0}; 

  return true;
}

function getkey(e) {
	if (window.event) {
		return window.event.keyCode;
	} else if (e) {
		return e.which;
	} else {
		return null;
	}
}

function handleSizeLinks(small, medium, large) {
	handleSizeLink(document.getElementById("sizeLinkSmall"), small);
	handleSizeLink(document.getElementById("sizeLinkMedium"), medium);
	handleSizeLink(document.getElementById("sizeLinkLarge"), large);
}

function handleSizeLink(ele, active) {
	if (ele) {
		if (active) {
			ele.style.fontWeight = "bold";
		} else {
			ele.style.fontWeight = "";
		}
	}
}

function sendHint() {
	var email = dwr.util.getValue("email")

	if (email && email.indexOf("@")!=-1) {
		var container = "greetingMovies";
		
		if ($("greetingMovies").style.display == "none") {
			container = "greetingNewUser";
		}
		
		dwr.util.setValue(container, getLoadingText());
		
		new Ajax.Updater(container, 'SendPasswordHint.jsp', {
			  parameters: { user: $F("email") }
		});
	} else {
		alert("Please provide your email address.");
		
		getElement('email',null).focus();
	}
}

function showNewUser() {
	$("greetingMovies").style.display = "none";
	$("greetingNewUser").style.display = "";
	$("greetingNewPassword").style.display = "none";
}

function postNewUser() {
	MM_validateForm('FirstName','','R','LastName','','R','Phone','','R','E-MailAddress','','RisEmail','Password1','','R','Password2','','R');
	
	if (document.MM_returnValue) {
		if (dwr.util.getValue('Password1') == dwr.util.getValue('Password2')) {
			new Ajax.Updater('greetingNewUser', 'NewUser.jsp', {
				  parameters: $("newUserForm").serialize(true)
			});
		} else {
			$('Password2').focus();
			alert("Passwords do not match");
		}
	}
}

function showNewPassword() {
	$("greetingMovies").style.display = "none";
	$("greetingNewUser").style.display = "none";
	$("greetingNewPassword").style.display = "";
}

function postNewPassword() {
	MM_validateForm('passwordUser','','R','oldPassword','','R','newPassword','','R','newPassword','','R','newPassword2','','R');
	
	if (document.MM_returnValue) {
		if (dwr.util.getValue('newPassword') == dwr.util.getValue('newPassword2')) {
			new Ajax.Updater('greetingNewPassword', 'NewPassword.jsp', {
				  parameters: $("newPasswordForm").serialize(true)
			});
		} else {
			$('newPassword').focus();
			alert("Passwords do not match");
		}
	}
}

function switchElements(id1, id2) {
	$(id1).style.display = "";
	$(id2).style.display = "none";
}

function switchLanguage(lang) {
	document.forms.languageForm.language.value = lang;
	document.forms.languageForm.submit();
}

function showAllArtists() {
	if ($("leftColumn")) {
		var left = 110;
		
		try {
			left += $("frame").offsetLeft;
		} catch (e) {}
		
		$("allArtistsMenu").style.left = left + "px";
	} else {
		$("allArtistsMenu").style.left = "";
	}
	
	$("allArtistsMenu").style.display="block";
}

function proceedWithDownload() {
	termsApproved = true;
	
	if (downdloadTermsCallback) {
		downdloadTermsCallback();
	}
}

function clearDownloadData() {
	downdloadTermsCallback = null;
	termsApproved = false;
}

function MM_findObj(n, d) { //v4.01
	  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	  if(!x && d.getElementById) x=d.getElementById(n); return x;
	}

function MM_validateForm() { //v4.0
	  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
	  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
	    if (val) { nm=val.name; if ((val=val.value)!="") {
	      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
	        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
	      } else if (test!='R') { num = parseFloat(val);
	        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
	        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
	          min=test.substring(8,p); max=test.substring(p+1);
	          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
	    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
	  } if (errors) alert('The following error(s) occurred:\n'+errors);
	  document.MM_returnValue = (errors == '');
	}

