/* Author: Stephan Pfaff (http://stephanpfaff.com)

*/


/* =========================================================================================================================
 * ############################################         Button         #####################################################
 * =========================================================================================================================
 */


/**
 * @author Stephan Pfaff (http://www.derdaumen.net)
 */

/**
 * The Button Object
 * @param vars object providing the button properties (loaded from the database)
 * @return
 */
function Button(vars, params, parent){
	if(vars != null) {
		try {
			Item.call(this, vars.prefix, vars.id, vars.type, vars.basename, vars.path, vars.label, vars.alias, vars.thumb, vars.thumb_enable, false, vars.item_class);
			this.category_id 	= parseInt(vars.category_id);
			this.project_id 	= parseInt(vars.project_id);
			if (vars.img != null && vars.img != '')
				this.img 		= vars.img;
			this.img_title		= vars.img_title;
			this.img_enable 	= vars.img_enable;
			this.lightbox_enable = vars.lightbox_enable;
			var img_rel = this.lightbox_enable ? 'lightbox['+this.prefix+']' : '';
			this.x				= parseInt(vars.x*site.gridSize);
			this.y				= parseInt(vars.y*site.gridSize);
			this.content_x		= parseInt(vars.content_x*site.gridSize);
			this.content_y		= parseInt(vars.content_y*site.gridSize);
			this.content_width	= parseInt((vars.content_width*site.gridSize)-7);
			this.content_height	= parseInt((vars.content_height*site.gridSize)-7);
			this.interactive	= vars.interactive;
			this.text			= vars.text;
			this.text_enable	= vars.text_enable;
			this.link			= vars.link;
			this.link_enable	= vars.link_enable;
			this.img_delete 	= false;

			this.div_id = this.prefix+"_"+this.id;
			var active = false;
			var class_active = '';
			if(this.id == params.btn_id) {
				active = true;
				class_active = 'active';
			} else {
				active = this.interactive ? false : true;
				class_active = this.interactive ? '' : 'active';
			}
			this.div_class = 'item '+this.prefix+' '+this.item_class+' '+class_active;
			this.div_x = active ? "left: "+this.content_x+"px;" : "left: "+this.x+"px;";
			this.div_y = active ? "top: "+this.content_y+"px;" : "top: "+this.y+"px;";
			this.div_width = active ? "width: "+this.content_width+"px;" : "";
			this.div_height = active ? " height: "+this.content_height+"px;" : "";
			this.bg_active = '#232323';
			if(this.label != "" || this.thumb != "")
				this.bg_inactive = '#232323';
			else
				this.bg_inactive = '#999';
			this.bg = active ? this.bg_active : this.bg_inactive;
			if(this.img_enable && this.img != "") var textClass = 'caption';
			else var textClass = 'text';
			
			//Externer Link nur erstellen wenn keine Lightbox aktiviert ist, 
			//oder falls lightbox aktiv ist, dann nur wenn dieser button nicht der aktive button ist
			var external_link = true;
			if (this.link != null) {
				if (external_link = this.link_enable) {
					if (this.lightbox_enable) {
						external_link = false;
					}
				}
			} else {
				external_link = false;
			}
			if(this.img != '') {
				var filetype = this.img.substring(this.img.lastIndexOf('.'));
				var filename = this.img.substring(0, this.img.lastIndexOf('.'));
				var preview = filename+'_preview'+filetype;
			}
			
			if(noPHPMode) {
				var html = ["<div id='"+this.div_id+"' class='"+this.div_class+"' style='"+this.div_x+" "+this.div_y+" "+this.div_width+" "+this.div_height+" background:"+this.bg+";'>\n"];
					if(this.thumb != "" && this.thumb_enable)		 				html.push("	<img id='thumb_"+this.div_id+"' class='thumb' src='"+this.thumb+"' alt='"+this.alias+"' width='73' height='73' />\n");
					if(this.label != "") 											html.push("	<div id='label_"+this.div_id+"' class='label'>"+this.label+"</div>\n");
					if(this.img != "" && this.img_enable && !this.lightbox_enable)	html.push("	<img id='img_"+this.div_id+"' class='img' src='"+preview+"' alt='"+this.img_title+"' title='"+this.img_title+"' width='"+this.content_width+"' height='"+this.content_height+"' />\n");
					if(this.img != "" && this.img_enable && this.lightbox_enable) 	html.push("	<a href='"+this.img+"' rel='"+img_rel+"' title='"+this.img_title+"' class='lightbox' target='blank'><img id='img_"+this.div_id+"' class='img' src='"+preview+"' alt='"+this.img_title+"' width='"+this.content_width+"' height='"+this.content_height+"' /></a>\n");
					if(this.text != "" && this.text_enable) 						html.push("	<div id='text_"+this.div_id+"' class='"+textClass+"'>\n"+this.text+"\n</div>\n");
					if(external_link)		 										html.push("	<a id='outerlink_"+this.div_id+"' class='link nav outer' href='"+this.link+"' target='_blank'></a>\n");
					html.push("</div>\n");
					this.$div = $(html.join(''));
					parent.$scrollWrapper.append(this.$div);
			} else {
				this.$div = $("#"+this.prefix+"_"+this.id);
			}
			if(noPHPMode && allowDraggable) {
				this.$div.draggable({
					revert: false,
					cancel: '.active',
					zIndex: 999
				});
			}
			//durch animationen ersetzte lins zum umschalten der buttons 
			//in der php Version entfernen
			$("#innerlink_"+this.div_id).remove();
			
			var handle = this;
			//hover
			this.$div.hover(function(event) {
				handle.activate($(this), event);
			},
			function(event) {
				handle.deactivate($(this), event);
			});
			//click
			this.$div.click(function(event) {
				handle.clickHandler($(this), event);
				//TODO URL handling
				//site.manipulateURL(handle);
			});
		} catch (e) {
			if(debug) alert('Initialization of Button failed, missing or wrong parameter! ('+e+')');
		}
	}
};
Button.prototype = new Item();
Button.prototype.category_id = 0;
Button.prototype.project_id = 0;
Button.prototype.x = 0;
Button.prototype.y = 0;
Button.prototype.content_x = 0;
Button.prototype.content_y = 0;
Button.prototype.content_width = 1;
Button.prototype.content_height = 1;
Button.prototype.interactive = 0;
Button.prototype.link = "";
Button.prototype.link_enable = false;
Button.prototype.text = "";
Button.prototype.text_enable = false;
Button.prototype.img = "";
Button.prototype.img_title = "";
Button.prototype.img_enable = false;
Button.prototype.lightbox_enable = false;
Button.prototype.img_delete = false;
Button.prototype.html = "";
Button.prototype.$div = null;
Button.prototype.div_id = null;
Button.prototype.div_class = null;
Button.prototype.div_x = null;
Button.prototype.div_y = null;
Button.prototype.div_width = null;
Button.prototype.div_height = null;
Button.prototype.bg_active = null;
Button.prototype.bg_inactive = null;
Button.prototype.bg = null;

Button.prototype.activate = function($div, event) {
	var buttons = site.getButtons().items;
	for (key in buttons) {
		if(buttons[key].$div.hasClass('active')){
			buttons[key].deactivate(buttons[key].$div, event);
		}
	}
	
	var div_id = this.div_id;
	if(!this.locked && this.interactive == true) {
		$div.clearQueue()
		.stop()
		.css('z-index', 103)
		.queue(function() {
			var $label = $("#label_"+div_id);
			var $thumb = $("#thumb_"+div_id);
			if($label.length > 0) {
				$thumb.fadeOut(site.btnAnimationDuration);
				$label.fadeOut(site.btnAnimationDuration, function() {
					$div.dequeue();
				});
			} else if($thumb.length > 0) {
				$label.fadeOut(site.btnAnimationDuration);
				$thumb.fadeOut(site.btnAnimationDuration, function() {
					$div.dequeue();
				});
			} else {
				$div.dequeue();
			}
		})
		.addClass("active", site.btnAnimationDuration)
		.animate({
			backgroundColor: this.bg_active,
			left: this.content_x,
			top: this.content_y,
			width: this.content_width,
			height: this.content_height
		}, site.btnAnimationDuration, function() {
			$("#img_"+div_id).fadeIn(site.btnAnimationDuration);
			$("#text_"+div_id).fadeIn(site.btnAnimationDuration);
		});
	}
};
Button.prototype.deactivate = function($div, event) {
	var div_id = this.div_id;
	if(!this.locked && this.interactive == true) {
		$div.clearQueue()
		.stop()
		.css('z-index', 102)
		.queue(function() {
			var $img = $("#img_"+div_id);
			var $text = $("#text_"+div_id);
			if($img.length > 0) {
				$text.fadeOut(site.btnAnimationDuration/2);
				$img.fadeOut(site.btnAnimationDuration/2, function() {
					$div.dequeue();
				});
			} else if($text.length > 0) {
				$img.fadeOut(site.btnAnimationDuration/2);
				$text.fadeOut(site.btnAnimationDuration/2, function() {
					$div.dequeue();
				});
			} else {
				$div.dequeue();
			}
		})
		.removeClass("active", site.btnAnimationDuration)
		.animate({
			backgroundColor: this.bg_inactive,
			left: this.x,
			top: this.y,
			width: 73,
			height: 73
		}, site.btnAnimationDuration, function() {
			$div.css('z-index', 0);
			$("#label_"+div_id).fadeIn(site.btnAnimationDuration);
			$("#thumb_"+div_id).fadeIn(site.btnAnimationDuration);
		});
	}
};
Button.prototype.clickHandler = function($div, event) {
	/*if($div.hasClass('active')) {
		this.deactivate($div, event);
	} else {
		this.activate($div, event);
	}*/
};



/* =========================================================================================================================
 * ###########################################         Project         #####################################################
 * =========================================================================================================================
 */

/**
 * The Project Object
 * @param vars object providing the project properties (loaded from the database)
 * @return
 */
function Project(vars, params, parent){
	if (vars != null) {
		try {
			Item.call(this, vars.prefix, vars.id, vars.type, vars.basename, vars.path, vars.label, vars.alias, vars.thumb, vars.thumb_enable, false, vars.item_class);
			this.category_id 	= parseInt(vars.category_id);
			this.position		= vars.position*site.gridSize;
			this.link			= vars.link;
			this.link_enable	= vars.link_enable;
			this.bg_active 		= '#232323';
			this.bg_inactive 	= '#232323';
			this.border_active 	= '#0f0';
			this.border_inactive = '#999';
			
			//Überprüfung ob das element per php oder javascript erstellt wird
			if(noPHPMode) {
				//seite läuft koplett über AJAX, element muss per javascript erstellt werden
				var div_id = this.prefix+"_"+this.id;
				var div_class = params.prj_id == this.id ? 'item '+this.prefix+' active' : 'item '+this.prefix;
				var html 		= ["<div id='"+div_id+"'"+"class='"+div_class+"'"+"style='top: "+this.position+"px;'>\n"];
				if(this.thumb != "" && this.thumb_enable) 	html.push("	<img id='thumb_"+div_id+"' class='thumb' src='"+this.thumb+"' alt='"+this.alias+"'/>\n");
				if(this.label != "") 						html.push("	<div id='label_"+div_id+"' class='label'>"+this.label+"</div>\n");
				if(this.link != null && this.link_enable) 	html.push("	<a id='outerlink_"+this.div_id+"' class='link nav outer' href='"+this.link+"' target='_blank'></a>\n");
				html.push("</div>\n");
				this.$div = $(html.join(''));
				parent.$scrollWrapper.append(this.$div);
			} else {
				this.$div = $("#"+this.prefix+"_"+this.id);
			}
			
			//bei aktivem noPHPMode das Element draggable machen
			if(noPHPMode && allowDraggable)
				this.$div.draggable({
					revert: false,
					cancel: '.active',
					zIndex: 100
				});
			
			//content laden, falls das element aktiv ist
			if(this.id == params.prj_id) {
				this.loadChilds(params);
			}
			//zeiger auf das objekt um auch innerhalb von inline methoden darauf zugreifen zu können
			var handle = this;
			
			//hover
			this.$div.hover(
				function(event) {
					if(!handle.locked && !$(this).hasClass("active"))
					$(this).stop().animate({
						//outlineColor: handle.border_active
						borderTopColor: handle.border_active,
						borderRightColor: handle.border_active,
						borderBottomColor: handle.border_active,
						borderLeftColor: handle.border_active
					}, site.navAnimationDuration);
				},
				function(event) {
					if(!handle.locked && !$(this).hasClass("active"))
					$(this).stop().animate({
						//outlineColor: handle.border_inactive
						borderTopColor: handle.border_inactive,
						borderRightColor: handle.border_inactive,
						borderBottomColor: handle.border_inactive,
						borderLeftColor: handle.border_inactive
					}, site.navAnimationDuration);
			});
			//click
			this.$div.click(function() {
				if(noPHPMode) {
					if(!$(this).hasClass("active")) {
						handle.loadChilds(params);
						$(site.getProjects().$div).find(".active").animate({
							borderTopColor: '#999',
							borderRightColor: '#999',
							borderBottomColor: '#999',
							borderLeftColor: '#999'
						}, site.navAnimationDuration).removeClass('active');
						$(this).addClass("active");
					} else {
						handle.loadChilds({ctg_id: handle.category_id, prj_id: handle.id});
					}
					site.updateDocumentTitle(handle.label);
					//TODO url handling
					//site.manipulateURL(handle);
				}
			});
			
		} catch(e) {
			if(debug) alert('Initialization of Project failed, missing or wrong parameter! ('+e+')');
		}
	}
};

Project.prototype = new Item();
Project.prototype.category_id = 0;
Project.prototype.position = 0;
Project.prototype.link = "";
Project.prototype.link_enable = false;
Project.prototype.html = "";
Project.prototype.$div = null;
Project.prototype.bg_active = null;
Project.prototype.bg_inactive = null;
Project.prototype.border_active = '';
Project.prototype.border_inactive = '';

/**
 * Loads the project's children.
 */
Project.prototype.loadChilds = function(params) {
	if(noPHPMode) {
	//wenn kein parameter Objekt übergeben wird eines erzeugen, mit der ID dieser Kategorie
		if (params == null) { 
			params = {ctg_id: this.category_id,	prj_id: this.id};
		//wenn ein Parameter Objekt übergeben wird, ctg_id mit der ID dieser Kategorie synchronisieren
		} else {
			params.ctg_id = this.category_id;
			params.prj_id = this.id;
		}
	}
	site.getButtons().load(params, false);
	//site.getButtons().$div.fadeIn(site.navFadeDuration);
};



/* =========================================================================================================================
 * ##########################################         Category         #####################################################
 * =========================================================================================================================
 */

/**
 * The Category Object
 * @param vars object providing the category properties (loaded from the database)
 * @return
 */

function Category (vars, params, parent){
	if (vars != null) {
		try {
			Item.call(this, vars.prefix, vars.id, vars.type, vars.basename, vars.path, vars.label, vars.alias, vars.thumb, vars.thumb_enable, false, vars.item_class);
			this.start_x 	= parseInt(vars.start_x)*site.gridSize;
			this.start_y 	= parseInt(vars.start_y)*site.gridSize;
			this.position 	= vars.position*site.gridSize;
			this.bg_active 	= '#0f0';
			this.bg_inactive = '#232323';
			
			//check ob das menü item aktiv ist, entsprechende klasse zuweisen
			var div_class = params.ctg_id == this.id ? 'item '+this.prefix+' active' : 'item '+this.prefix;
			//absolute positionierung im preface, oder auf der hauptseite berechnen
			if (parent.type == 'preface') {
				var style = 'left: '+this.start_x+'px; top: '+this.start_y+'px;';
			} else {
				var style = 'left: '+this.position+'px;';
			}
			
			//Überprüfung ob das element per php oder javascript erstellt wird
			if(noPHPMode) {
			//seite läuft koplett über AJAX, element muss per javascript erstellt werden
				var div_id = this.prefix+"_"+this.id;
				var html 		= ["<div id='"+div_id+"'"
				+"class='"+div_class+"'"
				+"style='"+style+"'>\n"];
				if(this.thumb != "" && this.thumb_enable) html.push("	<img id='thumb_"+div_id+"' class='thumb' src='"+this.thumb+"' alt='"+this.alias+"'/>\n");
				if(this.label != "") html.push("	<div id='label_"+div_id+"' class='label'>"+this.label+"</div>\n");
				html.push("</div>\n");
				this.$div = $(html.join(''));
				parent.$scrollWrapper.append(this.$div);
			} else {
				this.$div = $("#"+this.prefix+"_"+this.id);
			}
			//id als data attribut einfügen, um im noPHPMode bei einem klick
			//das element im neu erstellten menü wieder aktiv setzen zu können
			this.$div.data('id', this.id);
			
			//bei aktivem noPHPMode das Element draggable machen
			if(noPHPMode && allowDraggable)
				this.$div.draggable({
					revert: false,
					cancel: '.active',
					zIndex: 100
				});
			
			//content laden, falls das element aktiv ist
			if(this.id == params.ctg_id) {
				this.loadChilds(params);
			}
			//zeiger auf das objekt um auch innerhalb von inline methoden darauf zugreifen zu können
			var handle = this;
			
			//hover
			this.$div.hover(
				function(event) {
					if(!handle.locked && !$(this).hasClass("active"))
					$(this).stop().animate({
						backgroundColor: handle.bg_active
					}, site.navAnimationDuration);
				},
				function(event) {
					if(!handle.locked && !$(this).hasClass("active"))
					$(this).stop().animate({
						backgroundColor: handle.bg_inactive
					}, site.navAnimationDuration);
			});
			
			//click
			this.$div.click(function(event) {
				if(noPHPMode) {
					//wenn preface angezeigt wird
					if(site.preface != null) {
						var targetID = $(event.target).data('id');
						site.preface.$div.fadeOut(site.containerFadeDuration, function() {
							$(this).remove();
							site.preface = null;
							site.getCategories().load({prefix: 'ctg', ctg_id: targetID}, false);
							$('#main').after('<div id="footer" class="footer" style="display: none;">'
									+'	<a href="index.php" target="_self">'
									+'		<img src="css/images/logo.png" alt="logo" />'
									+'	</a>'
									+'</div>');
							var $footer = $('#footer');
							$footer.fadeIn(site.containerFadeDuration);
						});
					//wenn die hauptseite angezeigt wird
					} else if(!$(this).hasClass("active")) {
							handle.loadChilds({ctg_id: handle.id});
						site.getCategories().$div.find(".active").animate({
								backgroundColor: handle.bg_inactive
						}, site.navAnimationDuration).removeClass('active');
						$(this).addClass("active");
					} else {
						handle.loadChilds({ctg_id: handle.id});
					}
					site.updateDocumentTitle(handle.label);
					//TODO url handling
					//site.manipulateURL(handle);
				}
			});
		} catch(e) {
			if(debug) alert('Initialization of Category failed, missing or wrong parameter! ('+e+')');
		}
	}
};
Category.prototype = new Item();
Category.prototype.start_x = 0;
Category.prototype.start_y = 0;
Category.prototype.position = 0;
Category.prototype.$div = null;
Category.prototype.bg_active = '#0f0';
Category.prototype.bg_inactive = '#232323';

/**
 * Loads the category's children.
 */
Category.prototype.loadChilds = function(params) {
	if(noPHPMode){
		//wenn kein parameter Objekt übergeben wird eines erzeugen, mit der ID dieser Kategorie
		if (params == null) { 
			params = {ctg_id: this.id};
		//wenn ein Parameter Objekt übergeben wird, ctg_id mit der ID dieser Kategorie synchronisieren
		} else {
			params.ctg_id = this.id;
		}
	}
	site.getProjects().load(params, false);
	//site.getProjects().$div.fadeIn(site.navFadeDuration);
	if(params.prj_id == null) {
		site.getButtons().load(params, false);
		//site.getButtons().$div.fadeIn(site.navFadeDuration);
	}
};



/* =========================================================================================================================
 * ##############################################         Item         #####################################################
 * =========================================================================================================================
 */

function Item(prefix, id, type, basename, path, label, alias, thumb, thumb_enable, thumb_delete, item_class){
	try {
		this.locked 		= false;
		this.prefix 		= prefix;
		this.id 			= parseInt(id);
		this.type 			= type;
		this.basename 		= basename;
		this.path 			= path;
		this.label 			= label;
		this.alias 			= alias;
		if (thumb != null && thumb != '')
			this.thumb		= thumb;
		this.thumb_enable 	= thumb_enable;
		this.thumb_delete 	= thumb_delete;
		this.item_class		= item_class;
	} catch (e) {
		if(debug) alert('Initialization of new Item failed, missing or wrong '
				+'parameter! ('+e+')');
	}
};
Item.prototype.prefix = "";
Item.prototype.id = 0;
Item.prototype.type = "";
Item.prototype.basename = "";
Item.prototype.path = "";
Item.prototype.label = "";
Item.prototype.alias = "";
Item.prototype.thumb = "";
Item.prototype.thumb_enable = false;
Item.prototype.thumb_delete = false;
Item.prototype.item_class = "";
Item.prototype.locked = true;

/**
 * Loads the dedicated children of the item
 */
Item.prototype.loadChilds = function() {};



/* =========================================================================================================================
 * ####################################         Item Container         #####################################################
 * =========================================================================================================================
 */



/**
 * ItemContainer Klasse
 * @param type 		String - Typ des ItemContainers (preface, category, project oder button)
 * @param prefix 	String - Prefix der MySQL Datensätze die mit dem Containertyp verknüpft sind 
 * @param urlLoad 	String - URL des php Script welches die Inhalte des Containers liefert
 */
function ItemContainer(type, prefix, urlLoad) {
	try {
		this.type = type;
		this.prefix = prefix;
		this.urlLoad = urlLoad;
		this.items = null;
		if(this.type == 'preface')
			this.div_class = 'preface';
		else if(this.type == 'category')
			this.div_class = 'nav nav_horizontal';
		else if(this.type == 'project')
			this.div_class = 'nav nav_vertical';
		else if(this.type == 'button')
			this.div_class = 'content';

		var itemID = type+'Container';
		this.$div = $('#'+itemID);
		this.$scrollWrapper = $('#'+type+'ScrollBox');
		this.scrollThreshold = 100;
		if (!this.$scrollWrapper.length && noPHPMode) {
			var html = ['<div id="'+itemID+'" class="'+this.div_class+'" style="display: none;">'
			            +'<div id="'+type+'ScrollBox" class="scrollBox"></div>'];
			if(this.type == 'project') {
				/*html.push('<div id="" class="navTransparencyTop">');
				var i = 9;	
				for (i=9; i>0; i--) {
					html.push('<div id="" class="percent'+i*10+'" style="top:'+(9-i)*2, 'px; height: 2px; width: 75px; background-image: url(css/images/menu-transparency-'+i*10+'.png"></div>');
				}
				html.push('</div>');
				html.push('<div id="" class="navTransparencyBottom">');
				var j = 1;
				for (j=1; j<10; j++) {
					html.push('<div id="" class="percent', j*10, '" style="bottom:', (9-j)*2, 'px; height: 2px; width: 75px; background-image: url(css/images/menu-transparency-', j*10, '.png"></div>');
				}
				html.push('</div>');*/
			}
			html.push('</div>');
			$('#main').append(html.join(''));
			this.$div = $('#'+itemID);
			this.$scrollWrapper = $('#'+type+'ScrollBox');
		}
		
		if (this.type == 'project' || this.type == 'category') {
			var handle = this;
			this.$div.mousemove(function(e){
				handle.scroll(e);
			});
		}
	} catch(e) {
		if(debug) alert('Initialization of Preface failed, missing or wrong parameter! ('+e+')');
	}
};
/**
 * Typ des ItemContainers (preface, category, project oder button)
 */
ItemContainer.prototype.type = null;
/**
 * Prefix der MySQL Datensätze die mit dem Containertyp verknüpft sind
 */
ItemContainer.prototype.prefix = null;
/**
 * URL des php Script welches die Inhalte des Containers liefert
 */
ItemContainer.prototype.urlLoad = null;
/**
 * Objekt das die Inhalte des ItemContainers enthält
 */
ItemContainer.prototype.items = null;
/**
 * Das JQuery Objekt des DIVs welches den ItemContainer repräsentiert
 */
ItemContainer.prototype.$div = null;
/**
 * Der Klassename des Container DIVs
 */
ItemContainer.prototype.div_class = null;
/**
 * Der Wrapper für die Scrollfunktion
 */
ItemContainer.prototype.$scrollWrapper = null;
/**
 * Die tatsächliche Höhe des Menüs
 */
ItemContainer.prototype.height = 0;
/**
 * Die tatsächliche Breite des Menüs
 */
ItemContainer.prototype.width = 0;
/**
 * Die Höhe des sichtbaren Menubereichs
 */
ItemContainer.prototype.visibleAreaY = 0;
/**
 * Die Breite des sichtbaren Menubereichs
 */
ItemContainer.prototype.visibleAreaX = 0;
/**
 * Threshold für den Scrollbereich
 */
ItemContainer.prototype.scrollThreshold = 0;
/**
 * Berechnet die Anzahl an Inhalt Elementen im Container
 * @return int - Anzahl der Inhalt Elemente
 */
ItemContainer.prototype.length = function(){
	if (this.items != null) {
		var i = 0;
		for (key in this.items) {
			i++;
		}
		return i;
	} else {
		return -1;
	}
};
/**
 * Löscht alle HTML Elemente im Container-DIV
 * @return void
 */
ItemContainer.prototype.clear = function() {
	this.$scrollWrapper.empty();
};
/**
 * Erstellt Item Objekte aus den geladenen Daten (Category, Project oder Button) und zeigt das Content Grid an
 * @param items_temp 	Object - die geladenen MySQL Datensätze
 * @param params 		Object - Parameter Objekt: {prefix, ctg_id und prj_id} 
 * @param autoSelect	Boolean - Gibt an ob automatisch ein Inhalt-Element ausgewählt werden soll
 * @return
 */
ItemContainer.prototype.createItems = function(items_temp, params, autoSelect) {
	if(noPHPMode) {
		this.clear();
		if(this.type == 'button' || this.type == 'preface')
			var btn_coords = new Array();
	}
	var interactive = new Boolean(true);
	var i = 0;
	for(key in items_temp) {
		//key = itemID
		var item = items_temp[key];
		//Die geladenen Objekte erstellen und in items speichern
		switch (this.type) {
		case 'preface':
			if(item.type == 'category') {
				this.items[key] = new Category(item, params, this);
				if(noPHPMode) btn_coords.push(""+item.start_x+""+item.start_y);
			} else if(item.type == 'button'){
				this.items[key] = new Button(item, params, this);
				if(noPHPMode) btn_coords.push(""+item.x+""+item.y);
			}
			break;
		case 'category':
			if(i == 0 && params.ctg_id == null && autoSelect) params.ctg_id = key;
			this.items[key] = new Category(item, params, this);
			break;
		case 'project':
			if(i == 0 && params.prj_id == null && autoSelect) params.prj_id = key;
			this.items[key] = new Project(item, params, this);
			break;
		case 'button':
			if(i == 0 && params.btn_id == null && autoSelect) params.btn_id = key;
			this.items[key] = new Button(item, params, this);
			if(noPHPMode) btn_coords.push(""+item.x+""+item.y);
			interactive = new Boolean(item.interactive);
			break;
		}
		i++;
	}
	if(this.type == 'button' || this.type == 'preface') {
		if(noPHPMode){
			var dummies = ["<div id='dummies'>"];
			var max_x = site.grid_w;
			if (this.type == 'preface')
				var max_y = site.grid_h+1;
			else
				var max_y = site.grid_h;
			for(var x=0; x < max_x; x++) {
				for(var y=0; y < max_y; y++) {
					var left = x*site.gridSize;
					var top = y*site.gridSize;
					if($.inArray(""+x+""+y, btn_coords) < 0) {
						dummies.push("<div id='dummy_"+x+""+y+"' class='dummy item' style='left: "+left+"px; top: "+top+"px;'></div>\n");
					}
				}
			}
			dummies.push("</div>");
			this.$scrollWrapper.append(dummies.join(''));
			$('.dummy').draggable({
				revert: true,
				revertDuration: site.navAnimationDuration
			});
		}
	}
	this.visibleAreaX = this.$div.width();
	this.visibleAreaY = this.$div.height();
	if (this.$div.hasClass('nav_horizontal')) {
		this.height = site.gridSize - 5;
		this.width = this.length()*site.gridSize - 5;
	} else if (this.$div.hasClass('nav_vertical')) {
		this.height = this.length()*site.gridSize - 5;
		this.width = site.gridSize - 5;
	} else {
		this.height = site.grid_h*site.gridSize - 5;
		this.width = site.grid_w*site.gridSize - 5;
	}
    /*Shadowbox.clearCache();
    Shadowbox.setup(".lightbox", {
    	gallery:            "Project Gallery",
        overlayColor: 		"#232323",
    	overlayOpacity: 	0.95,
    	continuous:			true
    });*/
};
/**
 * Lädt Item-Daten aus der Datenbank, instanziiert damit Item-Objekte
 * die im Item-Container-Objekt gespeichert und anschließend angezeigt werden.
 * 
 * @param params 		Parameter Objekt: {prefix, ctg_id und prj_id}
 * @param preSelection	ID des Items das nach dem laden ausgewählt werden soll.
 * @param autoselect	Automatische auswahl des ersten Items wenn true
 * @return
 */
ItemContainer.prototype.load = function(params, autoSelect) {
	if(params) {
		if(noPHPMode && fadeContent) {
			this.$div.hide();
		}
		if (this.type == 'project')
			this.$div.scrollTop(0);
		if(this.type == 'preface') {
			params.prefix = 'ctg';
			this.items = new Object();
			var handle = this;
			$.getJSON(this.urlLoad, params, function(response){
				//wenn anfrage erfolgreich und items nicht leer
				if(response.result && response.items != null) {
					var items_temp = response.items;
					params.prefix = 'btn';
					params.ctg_id = 0;
					$.getJSON(handle.urlLoad, params, function(response){
						//wenn anfrage erfolgreich und items nicht leer
						if(response.result && response.items != null) {
							var items_temp2 = response.items;
							for(key in items_temp2) {
								items_temp['btn'+key] = items_temp2[key];
							}
							handle.createItems(items_temp, params, autoSelect);
						} else {
							if(debug) alert('load ' + handle.type + ' failed:\n'
									+ 'error: ' +response.error +"\n"
									+ 'items: ' +response.items +"\n"
									+ 'itemContainer: ' +(handle.$div.length > 0));
						}
					});
				} else {
					if(debug) alert('load ' + handle.type + ' failed:\n'
							+ 'error: ' +response.error +"\n"
							+ 'items: ' +response.items +"\n"
							+ 'itemContainer: ' +(handle.$div.length > 0));
				}
			});
		} else {
			params.prefix = this.prefix;
			this.items = new Object();
			var handle = this;
			$.getJSON(this.urlLoad, params, function(response){
				//wenn anfrage erfolgreich und items nicht leer
				if(response.result && response.items != null) {
					handle.createItems(response.items, params, autoSelect);
				} else {
					if(debug) alert('load ' + handle.type + ' failed:\n'
							+ 'error: ' +response.error +"\n"
							+ 'items: ' +response.items +"\n"
							+ 'itemContainer: ' +(handle.$div.length > 0));
				}
			});
		}
	} else {
		if(debug) alert("Fehlende Parameter für load"+this.type+"()!");
	}
	if(noPHPMode) {
		this.$div.fadeIn(site.containerFadeDuration);
		this.$scrollWrapper.stop().animate({top: 0, left: 0}, 1000, 'easeOutQuad');
		
	   
		$(".lightbox").fancybox({
			openEffect: 'fade',
			closeEffect: 'fade',
			nextEffect: 'fade',
			prevEffect: 'fade',
			padding: 1,
			closeBtn: false,
			helpers	: {
				title	: {
					type: 'inside'
				},
				overlay	: {
					opacity : 0.95,
					css : {
						'background-color' : '#232323'
					}
				},
				thumbs	: {
					width	: 70,
					height	: 70
				}
			}
			
		});
	}
};

/**
 * Scrollt MenuContainer wenn er mehr Menü Items enthält als darstellbar sind
 * 
 * @param e eventHandler des mousmove listeners
 * @return void
 */
var lastMouseY = 0;
var lastMouseX = 0;
ItemContainer.prototype.scroll = function(e) {
	if (Math.abs(e.pageY - lastMouseY) > 0 || Math.abs(e.pageX - lastMouseX) > 50) {
		this.$scrollWrapper.stop().animate({top: this.scrollVertical(e), left: this.scrollHorizontal(e)}, 1000, 'easeOutQuad');
		lastMouseY = e.pageY;
		lastMouseX = e.pageX;
	}
};
ItemContainer.prototype.scrollVertical = function(e) {
	var mouse = e.pageY - this.$div.offset().top - this.scrollThreshold;
	if (mouse < 0) mouse = 0;
	var mouseQuantized = mouse / (this.visibleAreaY - this.scrollThreshold*2);
	if (mouseQuantized > 1) mouseQuantized = 1;
	var menuSurplus = this.height - this.visibleAreaY;
	return -(mouseQuantized * menuSurplus);
};
ItemContainer.prototype.scrollHorizontal = function(e) {
	var mouse = e.pageY - this.$div.offset().left - this.scrollThreshold;
	if (mouse < 0) mouse = 0;
	var mouseQuantized = mouse / (this.visibleAreaX - this.scrollThreshold*2);
	if (mouseQuantized > 1) mouseQuantized = 1;
	var menuSurplus = this.width - this.visibleAreaX;
	return -(mouseQuantized * menuSurplus);
};


/* =========================================================================================================================
 * ###############################################         Site        #####################################################
 * =========================================================================================================================
 */


/**
 * wenn true, Fehlermeldungen ausgeben
 */
var debug = true;
/**
 * Site Objekt
 */
var site = null;
/**
 * wenn true, Funktionalität ohne PHP, ausschließlich über JavaScript und AJAX
 */
var noPHPMode = true;
/**
 * wenn true, werden buttons verrückbar
 */
var allowDraggable = false;
/**
 * wenn true, wird der Content nach einem klick ausgeblendet und eingefadet
 */
var fadeContent = false;


var imageRoot = 'images/';
var url = location.href;
var urlTemp = url.substring(0, url.lastIndexOf('/'));
var siteRoot = url.substring(0, urlTemp.lastIndexOf('/')+1);


/**
 * Die Site Klasse
 */
function Site(div){
	this.gridSize = 80;
	this.grid_w = 6;
	this.grid_h = 5;
	this.navAnimationDuration = 500;
	this.btnAnimationDuration = 300;
	this.containerFadeDuration = 1000;
	this.libPath = 'lib/php/';
	this.preface = this.getPreface();
	this.categories = this.getCategories();
	this.projects = this.getProjects();
	this.buttons = this.getButtons();
	this.$div = $(div);
};
/**
 * Abstand zwischen den selben Seiten zweier Gitterkästchen
 */
Site.prototype.gridSize = null;
/**
 * Horizontale Kästchenanzahl
 */
Site.prototype.grid_w = null;
/** 
 * Vertikale Kästchenanzahl
 */
Site.prototype.grid_h = null;
/** 
 * Dauer der Fade Animationen
 */
Site.prototype.navAnimationDuration = null;
/** 
 * Dauer der Container Fade Animationen
 */
Site.prototype.containerFadeDuration = null;
/**
 * Pfad zu den PHP Scripten
 */
Site.prototype.libPath = null;
/**
 * Der Preface Container
 */
Site.prototype.preface = null;
/**
 * Der Kategorie Container
 */
Site.prototype.categories = null;
/**
 * Der Projekte Container
 */
Site.prototype.projects = null;
/**
 * Der Content-Buttons Container
 */
Site.prototype.buttons = null;
/**
 * Das Jquery Objekt des main content divs
 */
Site.prototype.$div = null;

/**
 * Preface Getter
 * @return ItemContainer preface
 */
Site.prototype.getPreface = function(){
	if(this.preface == null) {
		this.preface = new ItemContainer('preface',
				'pre',
				this.libPath+'load.php');
	}
	return this.preface;
};
/**
 * Categories Getter
 * @return ItemContainer categories
 */
Site.prototype.getCategories = function(){
	if(this.categories == null) {
		this.categories = new ItemContainer('category',
				'ctg',
				this.libPath+'load.php');
	}
	return this.categories;
};
/**
 * Projects Getter
 * @return ItemContainer projects
 */
Site.prototype.getProjects = function(){
	if(this.projects == null) {
		this.projects = new ItemContainer('project',
				'prj',
				this.libPath+'load.php');
	}
	return this.projects;
};
/**
 * Buttons Getter
 * @return ItemContainer buttons
 */
Site.prototype.getButtons = function(){
	if(this.buttons == null) {
		this.buttons = new ItemContainer('button',
				'btn',
				this.libPath+'load.php');
	}
	return this.buttons;
};

Site.prototype.manipulateURL = function(item) {
	var uri = new Uri($(location).attr('href'));
	switch (item.type) {
		case 'category':
			uri.setQuery('ctg_id='+item.id);
			break;
		case 'project':
			uri.setQuery('ctg_id='+item.category_id+'&prj_id='+item.id);
			break;
		case 'button':
			uri.setQuery('ctg_id='+item.category_id+'&prj_id='+item.project_id+'&btn_id='+item.id);
			break;
	}
	//window.location = uri;
	//window.location.replace(uri);
};
Site.prototype.updateDocumentTitle = function (string) {
	document.title = 'Kuner Architekten :: '+string;
}
/**
 * Lädt die Inhalte des Preface oder der Startseite
 * @param params Object - Parameter Objekt: {prefix, ctg_id und prj_id}
 * @return void
 */
Site.prototype.load = function(params, autoselect) {
	if(params.ctg_id == null) {
		this.preface.load(params, autoselect);
	} else {
		this.categories.load(params, autoselect);
	}
};
/**
 * Animiert das Text-Intro der Seite und fadet danach die Seite ein.
 * @return void
 */
Site.prototype.animateIntro = function() {
	$('#intro_animation').delay(1000).fadeIn(1000).delay(2000).fadeOut(1000).delay(1000).delay(1000, function(){
		$(this).remove();
		site.$div.fadeIn(site.containerFadeDuration*2);
	});
};
/**
 * Site Getter
 * @param div String - die id des Divs welches den gesamten Content enthält.
 * @return Site site
 */
function getSite(div) {
	if(site == null) {
		site = new Site(div);
	}
	return site;
}
/**
 * Initialisiert die Seite.
 * Blendet den Content-Container Div aus, falls die Startseite aufgerufen wird. 
 * @param params Object - Parameter Objekt: {prefix, ctg_id und prj_id}
 * @return void
 */
function init(params) {
	site = getSite('#container');
	if(params.ctg_id == null || params.ctg_id == '0'){
		site.$div.hide();
		site.load(params, false);
		$('body').append('<div id="intro_animation" style="display: none;">'
				+'<span class="logo_part1">Kuner</span> <span class="logo_part2">Architekten</span>'
			+'</div>');
		site.animateIntro();
	} else {
		site.load(params, false);
	}
	//PHP Scrolling - unfinished
	/*
	$('#projectUp').remove();
	$('#projectDown').remove();
	*/
	
	/*Shadowbox.init({
	    // skip the automatic setup again, we do this later manually
	    skipSetup: true
	});*/
}





