/*
Required: prototype library and following extension */

var resizetimer;

Position.getWindowSize = function(w) {
	w = w ? w : window;
	var width = w.innerWidth || 
			(w.document.documentElement.clientWidth || w.document.body.clientWidth);
	var height = w.innerHeight || 
			(w.document.documentElement.clientHeight || w.document.body.clientHeight);
	return [width, height]
};



Element.centerElement = function(parent, child, minLeft, minTop) {
	
	minLeft = 0;
	minTop = 0;

	var parentPosition = Position.realOffset(parent);
	var parentDimensions = Element.getDimensions(parent);
	var childDimensions = Element.getDimensions(child);			

	var left = parentPosition[0] + Math.round((parentDimensions.width - childDimensions.width) / 2);
	var top = parentPosition[1] + Math.round((parentDimensions.height - childDimensions.height) / 2);

	var left = (left < minLeft) ? minLeft : left;
	var top = (top < minTop) ? minTop : top;
	
	// Position the child
	child.style.left = left + "px";
	child.style.top = top + "px";
};




/*
Class Navigator
***************************************************************************************************/
	
function Navigator(portfolio) {

	this.portfolio = portfolio;
	
	
	this.element = $("navigator");
	
	this.title = $("title");
	this.languageMenu = $("language-menu");
	this.menu = $("menu");

	this.accordionswitch = $("title");
	this.cover = $("cover");

	this.filter = new Object();
	this.filter.portfolio = portfolio;
	
	this.filter.menus = [];
	this.filter.selection = new Array();
	
	this.filter.labels = new Array("type", "material", "year", "forSale");
	
	this.filter.empty = "[ALL]";
	

	
	// Prepare the navigator
	this.prepare = function() {
	
		this.element.style.height = stage.element.style.height;
		var accswitch = document.getElementById("title");
		$('accordionswitch').style.width = accswitch.offsetWidth+'px';
		
		this.accordionswitch.onmousedown = function() {
			if (!controller.stage.accordion.showing) {
				controller.stage.accordion.show();
//				accswitch.style.textDecoration = "underline";
				// accswitch.style.color = "#efefef";
//				$('accordionswitch').innerHTML = 'Mecky van den Brink';
				$('accordionswitch').innerHTML = (globalLanguage=='nl')? 'Informatie': 'Information';
				this.onmouseout = '';
				this.onmouseover = function() {
					$('accordionswitch').innerHTML = 'Mecky van den Brink';
				};
				
				this.onmouseout = function() {
					$('accordionswitch').innerHTML = (globalLanguage=='nl')? 'Informatie': 'Information';
				};
				

			} else {
				controller.stage.accordion.hide();
				accswitch.style.textDecoration = "none";
				// accswitch.style.color = "black";
				this.onmouseout = '';
				$('accordionswitch').innerHTML = 'Mecky van den Brink';
				this.onmouseout = function() {
					$('accordionswitch').innerHTML = 'Mecky van den Brink';
				};
				this.onmouseover = function() {
					$('accordionswitch').innerHTML = (globalLanguage=='nl')? 'Informatie': 'Information';
				};
				

			}
		};

//		var yeartitle = (this.portfolio.language=='en')? 'Year':'Jaar';
//		$("filter-year-all").innerHTML = yeartitle;

		this.accordionswitch.onmouseover = function() {
			$('accordionswitch').innerHTML = (globalLanguage=='nl')? 'Informatie': 'Information';
		};
		
		this.accordionswitch.onmouseout = function() {
			$('accordionswitch').innerHTML = 'Mecky van den Brink';
		};
		this.cover.onmousedown = function() {
			controller.stage.accordion.hide();
			$('accordionswitch').innerHTML = 'Mecky van den Brink';
			$('accordionswitch').onmouseout = function() {
				this.innerHTML = 'Mecky van den Brink';
			};
		};
		
		this.languageMenu.prepare();
	
		for (var i = 0; i < this.filter.labels.length; i++) {
			this.buildFilterMenu(this.filter.labels[i]);
		}
		
		this.filter.rebuildSelection();
		this.filter.updateMenus();

		this.menu.style.visibility = "visible";
	};


	this.buildFilterMenu = function(label, values) {
	
		values = this.portfolio.index[label];
	
		var filterMenu = $("filter-menu-" + label);
		var filterMenuMaterial = $("filter-menu-material");
		var filterMenuType = $("filter-menu-type");
		var filterMenuYear = $("filter-menu-year");
		
		filterMenu.pf = this;
		filterMenu.label = label;
		filterMenu.selectedValue = this.filter.empty;
		turbo = "";
		// Is this filter a preview?
		filterMenu.isPreview = false;
		
		filterMenu.menuItems = new Array();

		
		// ALL item
		var menuItem = $("filter-" + label + "-all");
		menuItem.value = this.filter.empty;
		filterMenu.menuItems[0] = menuItem;
		
		
		var value = "";
		
		for (var i = 0; i < values.length; i++) {
		
			value = values[i].toLowerCase();
			menuItem = $("filter-" + label + "-" + value);
			
			if (!menuItem) {
			
				controller.debug("Value missing from menu: label: " + 
						label + ", value: \"" + value + "\"");
				continue;
			}
			menuItem.value = value;

			filterMenu.menuItems[filterMenu.menuItems.length] = menuItem;
		}
		
		
		for (var i = 0; i < filterMenu.menuItems.length; i++) {
			
			menuItem = filterMenu.menuItems[i];
			
			menuItem.label = label;
			menuItem.pf = this.portfolio;
			menuItem.menu = filterMenu;
			menuItem.navigator = navigator;			
			
			
			menuItem.onmousedown = function(event) {
			
				event = (event) ? event : window.event;
				
				if (this.className != "disabled") {
					
					this.style.color = "white";
					if (this.className == "selected") {
					
						if (this.value != controller.navigator.filter.empty) {
							this.className = "";
						}
						
						controller.navigator.filter.remove(this.label);
						
						// Select the ALL item
						filterMenu.menuItems[0].className = "selected";
						
						this.onmouseover(event);
						
					} else {
				
						controller.navigator.filter.add(this.label, this.value);
						
						this.className = "selected";
						
						/*var bgcolorlist = new Array("#ff69e6", "#ff70f2", "#ff92e6", "#ff83f4", 
								"#ffa2e6", "#ff80bd", "#c07cff", "#ff39fb", "#ff98d0", "#ffabcf", 
								"#ffa8fd", "#cf73ff", "#fa4dff", "#bd8aff");
						this.style.color = bgcolorlist[Math.floor(Math.random() * 
								bgcolorlist.length)];*/
						
					}
					
				} else {
					
					// Added to support clicking on disabled items

					controller.navigator.filter.removeAll();
					menuItem.menu.className == "";
					
					this.onmouseover();
					this.style.color = "white";
					controller.navigator.filter.add(this.label, this.value);
					if (label=="year"){
/*						alert("filtermenuYear")*/
						filterMenuMaterial.menuItems[0].className = "selected";
						filterMenuType.menuItems[0].className = "selected";
						
					}
					if (label=="material"){
/*						alert("filtermenuMaterial")*/
						filterMenuType.menuItems[0].className = "selected";
						filterMenuYear.menuItems[0].className = "selected";
						
					}
					if (label=="type"){
/*						alert("filtermenuType")*/
						filterMenuYear.menuItems[0].className = "selected";
						filterMenuMaterial.menuItems[0].className = "selected";
						
					}
					// controller.navigator.filter.updateMenus();
					this.className = "selected";
					
				}
				
				Event.stop(event);
				
			};
			
			menuItem.onmouseover = function(event) {
			
				// Event.stop(event);
				
				if (this.className != "disabled") {
					
					if (this.className == "") {

						this.className = "hover";
						
						if (this.value != controller.navigator.filter.empty) {
							if (turbo) { turbo=clearTimeout(turbo); }
							controller.navigator.filter.setPreview(this.label, this.value);
						}
				
				
/*	Timo
*********************************************/
						if (this.label =="material") {
							var bgcolorlist = new Array("#ff69e6", "#ff70f2", "#ff92e6", "#ff83f4", 
									"#ffa2e6", "#ff80bd", "#c07cff", "#ff39fb", "#ff98d0", 
									"#ffabcf", "#ffa8fd", "#cf73ff", "#fa4dff", "#bd8aff");
							this.style.color = bgcolorlist[Math.floor(Math.random() * 
									bgcolorlist.length)];
						}
						if (this.label == "type") {
							var bgcolorlist = new Array("#1aff5c", "#18ff37", "#1bff0f", "#12ff65", 
									"#44ff5e", "#00f268", "#10ff8c", "#4bff8a", "#7aff10", 
									"#01ff6e", "#00f47f", "#00e6a0", "#00f2a1", "#00ff52", 
									"#00ee76");
							this.style.color = bgcolorlist[Math.floor(Math.random() * 
									bgcolorlist.length)];
						}
						if (this.label == "year") {
							var bgcolorlist = new Array("#2472fa", "#3c9de7", "#1f9fff", 
									"#0031ff", "#2c8fff", "#2effe0", "#125bff", "#089bff", 
									"#1db5ff", "#67b3ff", "#5a8cff", "#007bf2");
							this.style.color = bgcolorlist[Math.floor(Math.random() * 
									bgcolorlist.length)];
						}
					}
				}
				else if (this.className == "disabled") {

					this.style.color = '#7c96c4';
				}	
/*	End Timo
*********************************************/				

				
			};
			
			menuItem.onmouseout = function(event) {

				if (this.className != "disabled") {
					if (this.className == "hover") {
						this.className = "";
					}
					
					if (this.className != "selected") {
						controller.navigator.filter.removePreview(this.label);
//						console.log('removePreview')
					}
				}
/*	Timo
*********************************************/
				this.style.color = ""
/*	End Timo
*********************************************/
			};
		}
		
		
		// Check for groups
		var divs = filterMenu.getElementsByTagName("div");
		
		filterMenu.groups = new Array();
		
		filterMenu.selectedGroup = null;
		
		var group = null;
		
		for (var i = 0; i < divs.length; i++) {
		
			var div = divs[i];
			
			if (div.className == "group") {
			
				group = divs[i];
				
				
				group.items = new Array();
				filterMenu.groups[filterMenu.groups.length] = group;
				
				var subDivs = group.getElementsByTagName("div");
				
				for (var j = 0; j < subDivs.length; j++) {
					
					var subDiv = subDivs[j];
					
					if (subDiv.className == "heading") {
						group.heading = subDiv;
						
						group.heading.menu = filterMenu;
						group.heading.group = group;
						
						group.heading.onmousedown = function() {
						
							if (this.group.heading.className != "heading disabled") {
							
								if (this.group.id != this.menu.selectedGroup.id) {
								
									// Collapse the currently expanded group
									for (var i = 0; i < this.menu.selectedGroup.items.length; i++) {
										this.menu.selectedGroup.items[i].style.display = "none";
									}
									
									// Expand this group
									for (var i = 0; i < this.group.items.length; i++) {
										this.group.items[i].style.display = "block";
									}
									
									this.menu.selectedGroup = this.group;
								}
							}
							else {

								// Added to support clicking on disabled items

								controller.navigator.filter.removeAll();

								this.onmouseover();

								controller.navigator.filter.add(this.label, this.value);

								this.className = "selected";
							}
						};
						
						group.heading.onmouseover = function() {
						
							if (this.className != "heading disabled") {	
								if (turbo) { turbo=clearTimeout(turbo); }
								controller.navigator.filter.showGroupPreview(this.group);
								this.className = "heading hover";
							
/*	Timo
*********************************************/

								var bgcolorlist = new Array("#2472fa", "#3c9de7", "#1f9fff", 
										"#0031ff", "#2c8fff", "#2effe0", "#125bff", "#089bff", 
										"#1db5ff", "#67b3ff", "#5a8cff", "#007bf2");
								this.style.color = bgcolorlist[Math.floor(Math.random() * 
										bgcolorlist.length)];
							}
							
							if (this.className == "heading disabled") {

								var bgcolorlist = new Array("#1a1a1a", "#3a3a3a", "#2b2b2b", 
										"#1a1a1a", "#494949");
								this.style.color = bgcolorlist[Math.floor(Math.random() * 
										bgcolorlist.length)];
							}	
/*	End Timo
*********************************************/
						};
						
						group.heading.onmouseout = function() {
							
							if (this.className != "heading disabled") {
								controller.navigator.filter.showAll();
//								alert('now')
//								turbo=setTimeout('controller.navigator.filter.showAll()', 90)
/*								controller.navigator.filter.showAll();*/
								this.className = "heading";
			
							}
							/*	Timo
							*********************************************/
							this.style.color = "";
							/*	End Timo
							*********************************************/
						};
						
						
					} else if (subDiv.id.indexOf("filter-" + label + "-") == 0) {
						group.items[group.items.length] = subDiv;
					}
				}
			}
		}
		
		// Make the first group the currently expanded group
		if (filterMenu.groups.length > 0) {
			filterMenu.selectedGroup = filterMenu.groups[0];
		}
		
		
		// Disable values that don't exist in the portfolio
		for (var i = 0; i < divs.length; i++) {
			var div = divs[i];
			if ((div.id.indexOf("filter-" + label + "-") == 0) && !div.label) {
				div.className = "disabled";
			}
		}
		
		this.filter.menus[label] = filterMenu;
		
	}; // END buildFilterMenu
	

	// Add a preview filter
	this.filter.setPreview = function(label, value) {
	
		var filterMenu = this.menus[label];
		filterMenu.isPreview = true;
		filterMenu.selectedValue = value;
		
		this.updatePreview();
	};
	
	
	// Remove a preview filter
	this.filter.removePreview = function(label) {
	
		var filterMenu = this.menus[label];
		
		if (filterMenu.isPreview) {
			filterMenu.selectedValue = this.empty;
			filterMenu.isPreview = false;

			// this.updatePreview();
			this.showAll();
			this.updateMenus();
		}
	};
	
	
	// Add a permanent filter
	this.filter.add = function(label, value) {
	
		// For "ALL" menu items
		if (value == this.empty) {
			this.remove(label);
			return true;
		}
	
		var filterMenu = this.menus[label];

		if (filterMenu.isPreview) {
		
			filterMenu.selectedValue = value;
			filterMenu.isPreview = false;
			this.rebuildSelection();

			controller.stage.displayThumbnails(true);
			this.updateMenus();
		}
	};
	
	
	// Remove a permanent filter
	this.filter.remove = function(label) {
	
		var filterMenu = this.menus[label];
		
		if (filterMenu.selectedValue != this.empty) {
			filterMenu.isPreview = true;
			filterMenu.selectedValue = this.empty;
			this.rebuildSelection();

			controller.stage.displayThumbnails(true);
			
			this.updateMenus();
		}
	};
	
	
	this.filter.removeAll = function() {
		for (var i = 0; i < this.labels.length; i++) {
			this.remove(this.labels[i]);
		}
	};

	
	// Set the state of all filter menu items
	this.filter.updateMenus = function() {
		for (var i = 0; i < this.labels.length; i++) {
			this.updateMenu(this.labels[i]);
		}
	};
	
	
	// Set the state of all items in one filter menu
	this.filter.updateMenu = function(label) {
	
		filterMenu = this.menus[label];			
		var menuItem = null;		

		for (var i = 0; i < filterMenu.menuItems.length; i++) {
			menuItem = filterMenu.menuItems[i];			
				
			// Is this the selected value for this menu?
			if (!filterMenu.isPreview && menuItem.value == 
					filterMenu.selectedValue) {
				menuItem.className = "selected";
				continue;
			}
			
			if (!filterMenu.isPreview && 
					filterMenu.selectedValue != this.empty) {
				
				if (menuItem.value != this.empty) {
					menuItem.className = "disabled";
				} else {
					menuItem.className = "";
				}
				continue;
			}
				
			// Are there portfolio items available for this filter
			if (this.testAvailable(menuItem.label, menuItem.value)) {
				menuItem.className = "";
			} else {
				menuItem.className = "disabled";
			}
		}
		
		
		// Handle groups
		for (var i = 0; i < filterMenu.groups.length; i++) {
			var group = filterMenu.groups[i];
			var disabled = true;
			for (var j = 0; j < group.items.length; j++) {
				var item = group.items[j];
				if (group.items[j].className != "disabled") {
					disabled = false;
				}
			}
			group.heading.className = (disabled) ? 
					"heading disabled" : "heading";
		}
	};
	
	
	
	// Rebuild the list of selected items, based upon the permanent filters
	this.filter.rebuildSelection = function() {
	
		this.selection = new Array(); // Clear the list
		for (var i = 0; i < this.portfolio.items.length; i++) {	
			var item = this.portfolio.items[i];
			if (this.test(item, false)) {
				this.selection[this.selection.length] = item;
			}
		}
	};
	
	
	
	// Update the display based upon the preview filter
	this.filter.updatePreview = function(label, value) {
		
		for (var i = 0; i < this.selection.length; i++) {
			var item = this.selection[i];
			if (this.test(item, true)) {
				item.thumbnail.style.visibility = "visible";
			} else {
				item.thumbnail.style.visibility = "hidden";
			}
		}
	};
	
	
	// Update the display based upon the preview filter
	this.filter.showGroupPreview = function(group) {
		
		for (var i = 0; i < this.selection.length; i++) {
		
			var item = this.selection[i];
			
			for (var j = 0; j < group.items.length; j++) {
		
				var menuItem = group.items[j];
				
				if (menuItem.className != "disabled") {
				
					if (item[menuItem.label].indexOf(menuItem.value) > -1) {
						item.thumbnail.style.visibility = "visible";
						break;
					} else {
						item.thumbnail.style.visibility = "hidden";
					}
				
				}
				
			}
		}
	};
	
	
	// Show all thumbnails
	this.filter.showAll = function() {	
		for (var i = 0; i < this.selection.length; i++) {
			var item = this.selection[i];
			item.thumbnail.style.visibility = "visible";
		}
	};
	
	
	
	// Test whether an item matches the currently set filters
	// Parameter includePreview determines whether or not preview filters are 
	// taken into consideration
	this.filter.test = function(item, includePreview) {

		for (var i = 0; i < this.labels.length; i++) {
		
			var filterMenu = this.menus[this.labels[i]];
			
			// Skip the preview filter if includePreview is false (or omitted)
			if (!includePreview && filterMenu.isPreview) {
				continue;
			}
			
			// All items match an empty value
			if (filterMenu.selectedValue == this.empty) {
				continue;
			}
			
			try {
				if (item[filterMenu.label].indexOf(filterMenu.selectedValue) > -1) {
					continue;
				} else {
					return false;
				}
			} catch(error) {
				debug(error.message + "\n" + error.description);
				return false;
			}
			
			
		}
		return true;
	};
	
	
	this.filter.testPreview = function(item, label, value) {

		var filterMenu = this.menus[label];

		if (label == filterMenu.label && value == this.empty) {
			return true;
		}
			
		try {
			if (item[label].indexOf(value) > -1) {
				return true;
			} else {
				return false;
			}
		} catch(error) {
			return false;
		}
	};
	
	// TO DO: Implement or remove this, finish it too
	this.filter.testPreviewArray = function(item, label, value) {

		var filterMenu = this.menus[label];

		if (label == filterMenu.label && value == this.empty) {
			return true;
		}
			
		try {
			if (item[label].indexOf(value) > -1) {
				return true;
			} else {
				return false;
			}
		} catch(error) {
			return false;
		}
	};
	
	
	// Does any of the items in the selection match this filter option?
	this.filter.testAvailable = function(label, value) {
	
		for (var i = 0; i < this.selection.length; i++) {
			var item = this.selection[i];
			if (this.testPreview(item, label, value)) {
				return true;
			}
		}
		return false;
	};
	
	
	
	this.translateMenus = function() {
		var translations = $("filter-menu-translation-" + this.portfolio.language);
		var divs = translations.getElementsByTagName("div");
		for (var i = 0; i < divs.length; i++) {
			var translation = divs[i];
			var menuItem = $(translation.id.substring(0, (translation.id.length - 
					this.portfolio.language.length - 1)));
			var value = menuItem.innerHTML;
			menuItem.innerHTML = translation.innerHTML;
		}

		globalLanguage = (this.portfolio.language=='en')? 'en': 'nl';
		var yeartitle = (this.portfolio.language=='en')? 'Year':'Jaar';
		$("filter-year-all").innerHTML = yeartitle;
	};
	
	
	/*
	Language selector */
	
	// Add behaviours to the language menu
	this.languageMenu.prepare = function() {
			
		this.setLanguage(controller.portfolio.language);
		
		var menuItems = this.getElementsByTagName("div");
	
		for (var i = 0; i < menuItems.length; i++) {
		
			var menuItem = menuItems[i];
			menuItem.menu = this;
			menuItem.language = menuItem.id.split("-")[1];

			if (menuItem.language == portfolio.language) {
				menuItem.className = "selected";
			}
			
			menuItem.onmousedown = function() {
			
				if (this.className != "selected") {
					$("language-" + portfolio.language).className = "";
					this.menu.setLanguage(this.language);
					
					this.className = "selected";
				}
			};
			
			menuItem.onmouseover = function() {
				if (this.className == "") {
					this.className = "hover";
				}
			};
			
			menuItem.onmouseout = function() {
				if (this.className == "hover") {
					this.className = "";
				}
			};
		}
	};
	
	this.languageMenu.setLanguage = function(languageCode) {
	
		// Translate item titles and descriptions
		controller.repository.loadLanguage(languageCode);

		// Translate the menus
		controller.navigator.translateMenus();
		
		// Translate the currently selected item
		if (controller.stage.fullSize.item) {
			controller.stage.fullSize.setDescription(controller.stage.fullSize.item);
		}
		
		// Translate the Accordion
		controller.stage.accordion.translate(languageCode);
	};
	
	
	// Debug
	this.filter.list = function() {
		var tmp = "- ";
		for (var i = 0; i < this.labels.length; i++) {
			var filterMenu = this.menus[this.labels[i]];
			tmp += filterMenu.label + ": " + filterMenu.selectedValue + " - ";
		}
		return tmp;
	};
}

/**************************************************************************************************/




/*
Class stage
***************************************************************************************************/

function Stage(portfolio, navigator) {

	// The portfolio to display
	this.portfolio = portfolio;
	this.navigator = navigator;
	
	

	// Stage elements
	
	this.element = $("stage");
	$("closeclickfullsize").onmousedown = function(){
		$("full-size").hide();
	};

	$("navigator").onmousedown = function(){
		$("full-size").hide();
	};

	this.fullSize = $("full-size");
	this.fullSize.description = $("description");
	this.fullSize.description.width = 132;
	

	// this.menu = $("menu");
	
	this.cover = $("cover");
	this.accordion = new Accordion();
	this.progressbar = $("progressbar");
	
	// 
	this.thumbnailsLoaded = 0;

	
	// View settings
	this.stageWidth = 1191;
	this.stageHeight = 600;
	this.stageZ = 100;
	
	this.stagePadding = 11;
	this.menuWidth = 100;
	
	this.horSpacing = 6;
	this.horSpacingMin = 3;
	this.horSpacingMax = 9;
	
	this.vertSpacing = 1;
	
	this.maxThumbnailSize = 320; //220; strecht m
	this.maxFullSize = 550;
	this.fullSizeMargin = 160;
	
	this.numPerRow = 0;
	this.numRows = 0;
	
	this.vertScale = 0.85;
	
	// fine tuning the total size of thumbs
	var windowSize = Position.getWindowSize();
	var ww = windowSize[0];
	if(ww>=900) this.maxCompensation = 8;
	else if(ww<900&&ww>=700) this.maxCompensation = 52;
	else if(ww<700&&ww>=450) this.maxCompensation = 155;
	else if(ww<450&&ww>=0) this.maxCompensation = 240;
//	alert(ww+'//'+this.maxCompensation)
	

	
	
	this.prepare = function() {
	
		var windowSize = Position.getWindowSize();
		this.stageWidth = windowSize[0];
		this.stageHeight = windowSize[1];

		
		this.element.style.width = (windowSize[0] - this.menuWidth - 4) + "px";
		this.element.style.height = (windowSize[1]) + "px";
		
		this.fullSize.stage = this;
		this.fullSize.prepare();
		
		this.accordion.prepare();
		this.accordion.stage = this;
		this.accordion.maxHeight = (windowSize[1] - 60);

		
		// for IE:
		this.cover.style.height = this.stageHeight + "px";
		this.cover.prepare();

	};


	/*
	Load thumbnails */
	
	// Load all thumbnails
	this.loadThumbnails = function() {		
		for (var i = 0; i < this.portfolio.items.length; i++) {		
			this.loadThumbnail(this.portfolio.items[i]);
		}
	};
	
	// Reload all thumbnails
	this.reloadThumbnails = function() {		
		for (var i = 0; i < this.portfolio.items.length; i++) {		
			this.loadThumbnail(this.portfolio.items[i]);
		}

		controller.thumbnailsReloaded();
	};
	
	
	// Load one thumbnail
	this.loadThumbnail = function(item, forceImageReload) {
		
		var thumbnailId = "thumbnail-" + item.id;
		
		var reload = ($(thumbnailId)) ? true : false;
		
		if (!reload) {
		
			item.thumbnail = document.createElement("img");
			item.thumbnail.id = thumbnailId;
			item.thumbnail.className = "thumbnail";
	
			this.element.appendChild(item.thumbnail);
		
		} else {
		
			item.thumbnail = $(thumbnailId);

		}
		
		if (!item.thumbnail.scale) {
			item.thumbnail.scale = this.vertScale + Math.random() * 2 * (1 - this.vertScale);
		}


		item.thumbnail.stage = this;
		item.thumbnail.item = item;
		
		controller.repository.setImageUrls(item);
		
		item.thumbnail.onmousedown = function(event) {
			
			event = (event) ? event : window.event;
			
			if (!event.shiftKey) {
			
				if (stage.fullSize.item && stage.fullSize.item.id == this.item.id) {
				
					stage.fullSize.hide();
					
				} else {
				
					stage.fullSize.show(this.item, event);
					
				}
				
			} else {
				
				this.stage.thumbnailShiftClick(this.item);
			}
				
		};
	
		if (!reload) {
		
			item.thumbnail.onload = function() {
			
				this.stage.thumbnailLoaded();
				
			};

			// For IE, do not set the onload handler after the new src property
			item.thumbnail.src = item.thumbnailUrl;
			
		} else {
		
			item.thumbnail.onload = function() {
				return false;
			};
			
			if (forceImageReload) {
				item.thumbnail.src = repository.randomiseUrl(item.thumbnailUrl);
			} else {
			
			}
		}
	};
	
	
	// Callback function for the thumbnail onload event
	this.thumbnailLoaded = function() {
	
		this.thumbnailsLoaded++;
		
		this.progressbar.display.showProgress(this.thumbnailsLoaded);
		
		if (this.thumbnailsLoaded == this.portfolio.items.length) {
		
			controller.thumbnailsLoaded();
			
		}
	};
	
	// Placeholder for editor
	this.thumbnailShiftClick = function(item) {
	
		controller.debug("Shift click op item " + item.id);
		return false;
		
	};
	
	
	/*
	Full size view */
	
	this.fullSize.prepare = function() {
	
		this.transparentImageUrl = "themes/default/transparent.gif";
		
		this.item = null;
		
		this.onmousedown = function() {
			this.hide();
		};

		this.maxFullSize = stage.maxFullSize;
		this.fullSizeMargin = stage.fullSizeMargin;

		this.onmouseover = function() {
			if (this.description.innerHTML.length > 3) {
			
				this.description.style.visibility = "visible";				
				this.description.style.left = (stage.fullSize.left - this.description.width) + "px";
			}
		};
		
		this.onmouseout = function() {		
			this.description.style.left = stage.fullSize.left + "px";
			this.description.style.visibility = "hidden";		
		};
		
		this.onload = function() {
		
			if (this.src.indexOf(this.transparentImageUrl) == -1) {
			
				Element.centerElement($("stage"), $("full-size"), 0, 0);
				
				// var position = Position.realOffset($("full-size"));
				
				var SRCAry=[];
				var SRCCnt=0;
				var TO;
				var imageW = 0;
				var imageH = 0;

				function srcsize(img,swp,wth) {
					swp=swp||'';
					wth=wth||'';
					SRCCnt++;
					clearTimeout(TO);
					SRCAry[SRCCnt]=new Image();
					SRCAry[SRCCnt].src=img.replace(swp,wth);
					CkLoad();
				}

				function CkLoad(){
					if (!SRCAry[SRCCnt].complete){
						// alert('notcomplete')
						TO=setTimeout(CkLoad,100);
					}
					else {
//						alert(SRCAry[SRCCnt].width+' * '+SRCAry[SRCCnt].height);
//						controller.debug('realImageSize: '+SRCAry[SRCCnt].width+' * '+SRCAry[SRCCnt].height)
						imageW=SRCAry[SRCCnt].width;
						imageH=SRCAry[SRCCnt].height;
					}
				}
				srcsize(this.src);
				
				
				var windowSize = Position.getWindowSize();
				stageWidth = windowSize[0];
				stageHeight = windowSize[1];

				menuwidth = 80 ;

				if (imageW > imageH) {

					globalNewwidth = ((stageWidth - menuwidth - 2 * this.fullSizeMargin)<this.maxFullSize)? stageWidth - menuwidth - 2 * this.fullSizeMargin: 550;
					globalNewheight = imageH * globalNewwidth / imageW;
					
					if (globalNewheight > (stageHeight - 50 - 50)) {
						
						globalNewheight = stageHeight - 50 - 50;
						globalNewwidth = imageW * globalNewheight / imageH;
					}
					eserce = this.src;
					
					this.style.height = globalNewheight + "px";
					this.style.width = globalNewwidth + "px";
				
					Element.centerElement($("stage"), $("full-size"), 0, 0);
				}
				if (imageW < imageH) {

					globalNewheight = ((stageHeight - 50 - 50)<550)? stageHeight - 50 - 50: 550;
					globalNewwidth = imageW * globalNewheight / imageH;
					
						if ((globalNewwidth) > (stageWidth - menuwidth - 2 * this.fullSizeMargin)) {
							globalNewwidth = stageWidth - menuwidth - 2 * this.fullSizeMargin;
							globalNewheight = imageH * globalNewwidth / imageW;
						}
					eserce = this.src;
					this.style.width = globalNewwidth + "px";
					this.style.height = globalNewheight + "px";
				
					Element.centerElement($("stage"), $("full-size"), 0, 0);
				}

//				controller.debug('viewImageSize: '+globalNewwidth+' * '+globalNewheight)

				this.style.visibility = "visible";
				
				stage.fullSize.left = parseInt(stage.fullSize.style.left.split("p")[0]);

				stage.fullSize.top = parseInt(stage.fullSize.style.top.split("p")[0]);

				this.description.style.left = stage.fullSize.left + "px";
				
				this.description.style.top = (stage.fullSize.top + 30) + "px";
				
				// controller.debug("l: " + stage.fullSize.left + "\nt: " + stage.fullSize.top);
				
				this.description.style.visibility = "hidden";
				
				// If the full size view opens under the current mouse position
				if (this.openingClick) {
					if (this.openingClick.x >= stage.fullSize.left && 
							(this.openingClick.x <= stage.fullSize.left + stage.fullSize.width) && 
							this.openingClick.y >= stage.fullSize.top && 
							(this.openingClick.y <= stage.fullSize.top + stage.fullSize.height)) {
						
						// controller.debug("Opening click within full size");
						stage.fullSize.onmouseover();
						
					} else {
						// controller.debug("Opening click outside full size");
					}
				}
			}
		};
	};
	
	// Show the full size view of a selected item
	this.fullSize.show = function(item, event) {
	
	
		if (item.fullSizeUrl != this.src) {
			
			this.description.style.visibility = "hidden";
			this.style.visibility = "hidden";

			this.src = item.fullSizeUrl;

			this.item = item;
			
			this.setDescription(item);
			
			this.openingClick = null;
	

			if (event) {
				this.openingClick = {x: Event.pointerX(event), y: Event.pointerY(event)};
			
			} else {
				// controller.debug("No event");
			}
			

		} else {
			this.hide();
		}
	};
	
	this.fullSize.setDescription = function(item) {
		if (item.title.length > 3 || item.description.length > 3) {
			this.description.innerHTML = "<h1>" + item.title + "</h1>\n" +
					"<p>" + item.description + "</p>";
		} else {
			this.description.innerHTML = "";
		}
	};
	
	
	// Hide the full size view and item description
	this.fullSize.hide = function() {
		this.description.innerHTML = "";
		this.description.style.visibility = "hidden";
		this.style.visibility = "hidden";
		this.item = null;
		this.src = this.transparentImageUrl;
	};
	
	
	
	/* 
	Cover */
	this.cover.prepare = function() {		
		this.onmousedown = function() {
			// this.hide();
		};
	};
	
	this.cover.show = function() {
		this.style.display = "block";
	};
	
	this.cover.hide = function() {
		this.style.display = "none";
	};
	
	
	/*
	Progressbar */
	this.progressbar.show = function() {
		this.style.display = "block";
	};
	
	this.progressbar.hide = function() {
		this.style.display = "none";
	};
	
	
	/* 
	Accordion */
	this.accordion.show = function() {
		this.stage.cover.show();
		this.element.style.display = "block";
		this.showing = true;
	};
	
	this.accordion.hide = function() {
	
		this.element.style.display = "none";
		this.closeAll();
		this.showing = false;
		this.stage.cover.hide();
		
	};
	
	
	
	// Position the thumbnails on the screen
	this.displayThumbnails = function(flagFiltered) {
		flagFiltered = (flagFiltered) ? flagFiltered : false;
		
		var items = (flagFiltered) ? 
				controller.navigator.filter.selection : this.portfolio.items;
		
		
		var thumbnailSize = this.calculateThumbnailSize(items.length, this.vertScale);
		var rowHeight = Math.floor(thumbnailSize * this.vertScale);
	
		var w1, h1, w2, h2, t1, t2, l1, l2;
	
		var rowNum = 0;
		var item, thumbnail, itemThumbnailSize, itemSpacing;
		
	
		var nextZ = this.stageZ + this.numRows + 2;
		var nextBottom = this.stageHeight - this.stagePadding;
		
		var nextLeft = this.stagePadding;

		for (var i = 0; i < items.length; i++) {

			item = items[i];
		
			thumbnail = item.thumbnail;
			thumbnail.style.visibility = "visible";
				
			itemThumbnailSize = Math.round(item.thumbnail.scale * thumbnailSize);
			itemSpacing = Math.round(item.thumbnail.scale * this.horSpacing);
			
			w1 = thumbnail.width;
			h1 = thumbnail.height;
			
			if (h1 >= w1) {
				h2 = itemThumbnailSize;
				w2 = Math.round(w1 * (itemThumbnailSize / h1 ));			
			} else {
				w2 = itemThumbnailSize;
				h2 = Math.round(h1 * (itemThumbnailSize / w1 ));	
			}
			
			
			t1 = thumbnail.style.top;
			l1 = thumbnail.style.left;
			var recallLeft = nextLeft;

			if (nextLeft + w2 + itemSpacing > (this.stageWidth - this.stagePadding - this.menuWidth)) {


				recallLeft = nextLeft;
				nextLeft = this.stagePadding;
				nextBottom = nextBottom - rowHeight - this.vertSpacing;
				nextZ--;
				rowNum++;

				// RUN ARROUND MENU
				var nextTop = nextBottom - h2;

				if(nextTop<this.stagePadding){
					var elm = this;
//					alert('retry in 1 sec')
//					setTimeout(function(){
						elm.menuWidth = 80;
//						alert(elm.maxCompensation)
						elm.maxCompensation = Math.ceil(elm.maxCompensation*1.04);
//						alert(elm.maxCompensation)
						controller.stage.displayThumbnails();
//					},100)
					return false;
				}
//				console.log(nextTop)
				
				if(nextTop < 275 && nextTop > 210) {
//					 alert(nextBottom)
					this.menuWidth = 160;
				}
				else if(nextTop < 210 && nextTop > 80) {
					this.menuWidth = 350;
				}
//				else if(nextTop < 85) {
//					this.menuWidth = 470;
//				}
			}

			t2 = nextBottom - h2;
			l2 = nextLeft;
	
	
			thumbnail.style.zIndex = nextZ;

			thumbnail.style.top = t2 + "px";
			thumbnail.style.left = l2 + "px";
			thumbnail.width = w2;
			thumbnail.height = h2;

			if (recallLeft + w2 + itemSpacing < (this.stageWidth - this.stagePadding - this.menuWidth)) {
//				console.log(i)
				nextLeft = recallLeft + w2 + itemSpacing;
			}
			else{
				nextLeft += w2 + itemSpacing;
			}

		}
		this.menuWidth = 100;
		portfolio.loaded = true;

		window.onresize = function(){
			clearTimeout(resizetimer);
			resizetimer = setTimeout(function(){
				$("stage").innerHTML='<div id="closeclickfullsize"></div><hr class="clearing" />';
				portfolio = new Portfolio();
				repository = new Repository(portfolio);
				controller = new Controller(portfolio, repository);
				stage = new Stage(portfolio, navigator);	
				controller.stage = stage;
				controller.windowLoaded();
			},400);
		};
	};


	
	// Calculate the maximimum thumbnail size
	this.calculateThumbnailSize = function(number, factor) {
		var size;
		factor = (factor) ? factor : 1;
		for (size = this.maxThumbnailSize; true; size--) {
			this.numPerRow = Math.floor((this.stageWidth - this.stagePadding - 
					this.menuWidth + this.horSpacing) / (size + this.horSpacing));
			this.numRows = Math.floor((this.stageHeight - 2 * this.stagePadding + 
					this.vertSpacing) / (size * factor + this.vertSpacing));
			if ((this.numPerRow * this.numRows) > number+this.maxCompensation) {
				break;
			}
		}
		return size;
	};
}

/**************************************************************************************************/
