(function($) {
	$.fn.loboGallery = function(options) {
		var settings = {};
		return this.each(function() {
			// If options exist, lets merge them
			// with our default settings
			if (options) {
				$.extend(settings, options);
			}
			// Plugin code here
			// Globale Variablen
			active_page = "";
			active_preview = null;
			prev_active_page = "";
			pluginMode = "";
			prevPluginMode = "";
			prevPage = "";
			overlay_open = "";
			active_nr = 0;
			random_case = "";
			random_about = "";
			amount_client_pages = 0;
			clients_show_end = false;
			overlay_open_set = false;
			ajax_success = true;
			clients_scroll_complete = true;
			amount_client_previews = 108;
			block_page_switch_complete = true;
			hashManager = {interval:null, current:null};
			randomCases = options.randomCases;
			randomCaseIndex = 0;
			playlistIndex = 0;
			playlistStartIndex = 0;
			projectPlaylist = 0;
			mayShowToolTop = true;
			followCases = false;
			initialized = false;
			play_next = 0;
			autoplay = false;
			movingClientsPage = false;
			isSingleProject = false;
			lastActiveURL = null;
			init();
			
			//Init beim ersten Laden
			function init() {
				var waitForNewContent = checkHash();
				initialized = true;
				
				hashManager.interval = setTimeout(checkHash, 20);
				
				pluginMode = $("span.newModeInformation").attr("rel");
				prevPage = $("span.previousPageInfo").attr("rel");
				prevPluginMode = pluginMode;
				active_page = $(".bottomNavActive").attr("id");
				prev_active_page = active_page;
				
				/*
				if (pluginMode == "CONTACT") {
					$(".topNavNumbers").css("display", "none");
					$(".neverEmpty").neverEmpty();
				} else {
					refreshOverlayInfo();
					$("#map").css({
						opacity: "0",
						top: "-9999px"
					});
					if (pluginMode != "CLIENTLIST") {
						$(".clientsPreviewsFrame").css({bottom: "-9999px"});
						$(".items").css({opacity: 0});
					}
					clientsSetup();
				}
				*/
				 
				$("#map").css({
					opacity: "0",
					top: "-9999px"
				});
				if (pluginMode != "CLIENTLIST") {
					$(".clientsPreviewsFrame").css({bottom: "-9999px"});
					$(".items").css({opacity: 0});
				}
				clientsSetup();
				
				window.onresize = resize;
				window.onresize();
				
				if (!waitForNewContent) {
					refreshOverlayInfo();
					$('#mainContent').css('display', 'block');
					$("#bg b i i img").fadeTo(options.fade_in_time, 1);
					refreshNav();
					play();
				} else {
					stop();
				}
				//location.href.indexOf("autoplay=on") > -1 ? play() : stop();
			}
			
			function checkHash(checkCases,auto) {
				var waitForNewContent = hashManager.current === null && window.location.hash != '';
				if ((hashManager.current === null || checkCases === true)) {
					//console.log(window.location.hash.indexOf('#/cases.html'));
					if (window.location.hash.indexOf('/cases.html') == 1 || window.location.hash.indexOf('/nc/cases.html') == 1) {
						followCases = true;
						randomCaseIndex = 0;
						//console.log('yup');
						window.location.hash = '#/'+randomCases[0];
					} else {
						followCases = false;
					}
				}
				if (hashManager.current != window.location.hash && (hashManager.current !== null || window.location.hash != '') ) {
					if (!auto) stop();
					ajaxLoadPage(window.location.hash.split('#').slice(1).join(''));
					hashManager.current = window.location.hash;
				} else {
				}
				if (hashManager.current === null) hashManager.current = '';
				clearTimeout(hashManager.interval);
				hashManager.interval = setTimeout(checkHash, 20);
				return waitForNewContent;
			}
			
			//Größe der Seite anpassen
			function resize() {
				var bodyWidth = $(window).width();
				var bodyHeight = $(window).height();
				var dbsize = {}; // needed to store body size
				//window.scrollTo(0, 0);
				if (bodyWidth != dbsize.w || bodyHeight != dbsize.h || $("#bg b i i img").attr("src") != imgsrc) { // check if size or img size has changed
					imgsrc = $("#bg b i i img").attr("src"); // store current src
					dbsize.w = bodyWidth; // store current body width
					dbsize.h = bodyHeight; // store current body height
					var newwidth = Math.round(dbsize.h * ($("#bg b i i img").width() / $("#bg b i i img").height()));
					$("#bg b i i img").width(dbsize.w > newwidth ? dbsize.w : newwidth);
				}
				if (pluginMode == "CLIENTLIST") {
					initTopNavNumbersClients();
				}
			};
			
			//Navi aktualisieren
			function refreshNav() {
				$(".topNavNumbers").css('display', 'block');
				$(".topNavPageName").css('display', 'block');
				$(".topNavNumbers").children().each(function(i) {
					if ($(this).attr("class") == "topNavNumbersActive") {
						active_nr = i;
					} else {
						if (pluginMode == "TEASER" || pluginMode == "CASESTUDY" || pluginMode == "BLOG" || pluginMode == "PROJECT") {
							$(this).bind("click", function() {
								//var target = $(this).attr("href").split("#");
								//if (ajax_success) ajaxLoadPage(target[1]);
								stop();
								checkHash();
							});
						}
					}
				});
				//Aktuelle Seite
				active_page = $(".bottomNavActive").attr("id");
				refreshBottomNav();
				refreshCufon();
			}
			
			//Seite mit AJAX nachladen
			function ajaxLoadPage(linkTarget) {
				mayShowToolTop = false;
				$("#btnBack").fadeTo(0, .5);
				$("#btnBack").css('cursor', 'default');
				
				$("#btnForward").fadeTo(0, .5);
				$("#btnForward").css('cursor', 'default');
				
				//console.log(prev_active_page);
				//News, Cases...
				overlay_open_set = false;
				ajax_success = false;
				$(".ajaxLoad").each(function(i) {
					this.className += ' OLD';
				});
				
				$("img.loadingAnimation").css("display", "block");
				
				$("#loadContainer").load(linkTarget + ' .ajaxLoad', function() {
					
					pluginMode = $("#loadContainer span.newModeInformation").attr("rel");
					prevPage = $("#loadContainer span.previousPageInfo").attr("rel");
					projectPlaylist = $("#loadContainer span.projectPlaylist").attr("rel").split(';');
					isSingleProject = $("#loadContainer span.isSingleProject").attr("rel") == '1';
					if (projectPlaylist.join('') == '') projectPlaylist = [];
					
					if (window.location.href.indexOf('autoplay=true')>-1) {
						play();
					}
					
					if (window.location.href.indexOf('&playlistitem=')>-1) {
						playlistIndex = parseInt(window.location.href.split('&playlistitem=').pop().split('&').shift());
					}
					if (window.location.href.indexOf('&startindex=')>-1) {
						playlistStartIndex = parseInt(window.location.href.split('&startindex=').pop().split('&').shift());
					}
					
					MRConvertLinks();
					
					$("#map").stop().fadeTo(options.fade_out_time, 0, function() {
						$(this).css("top", "-9999px");
					});
					
					if (pluginMode == "TEASER" || pluginMode == "CASESTUDY" || pluginMode == "BLOG" || pluginMode == "PROJECT") {
						$("#loadContainer img.ajaxLoad").css("opacity", "0");
						$("#loadContainer img.ajaxLoad").load(function() {
							if (prevPluginMode == "CLIENTLIST") {
								$(".items").fadeTo(options.fade_out_time, 0, function() {
									hideClientsElements();
									
									$("#bg b i i img.OLD").replaceWith($("#loadContainer img.ajaxLoad"));
									replaceElements();
									$("#bg b i i img").fadeTo(options.fade_in_time, 1);
									refreshAfterLoad();
								});
							} else {
								$("#bg b i i img").fadeTo(options.fade_out_time, 0, function() {
									$("#bg b i i img.OLD").replaceWith($("#loadContainer img.ajaxLoad"));
									replaceElements();
									$("#bg b i i img").fadeTo(options.fade_in_time, 1);
									refreshAfterLoad();
								});
							}
						});
					}
				
				
					if (pluginMode == "CLIENTLIST") {
						$(".items").css({opacity: 0});
						//$("#loadContainer img.ajaxLoad").css("opacity", "0");
						$("#bg b i i img").fadeTo(options.fade_out_time, 0, function() {
							mayShowToolTop = true
							replaceElements();
							clientsSetup();
							$(".clientsPreviewsFrame").css({
								bottom: "75px",
								left: "18px"
							});
							$(".items").fadeTo(options.fade_in_time, 1);
							initClientsFilters();
							amount_client_pages = 0;
							initTopNavNumbersClients();
							/*
							$(".overlayShortInfoFrame").bind("mouseenter", function(e) {
								$(".tooltipClientsFrame").fadeOut(300, function() {
									$(".tooltipOpen").removeClass("tooltipOpen");
								});
								active_preview.fadeTo(300, 0.5);
							});
							*/
							//clientItemsEventSetup();
							clients_show_end = false;
							//
							refreshAfterLoad();
						});
					}
					
					if (pluginMode == "CONTACT") {
						if (prevPluginMode == "CLIENTLIST") {
							$(".items").fadeTo(options.fade_out_time, 0, function() {
								hideClientsElements();
								replaceElements();
								showMap();
								refreshAfterLoad();
							});
						} else {
							$("#bg b i i img").fadeTo(options.fade_out_time, 0, function() {
								replaceElements();
								showMap();
								refreshAfterLoad();
							});
						}
						
						setTimeout(function() {$('#mailFormMessage')[0].focus()}, 1000);
					}
					
					
					if (autoplay) play();
					
					
				});
			};
			
			function hideClientsElements() {
				$(".clientsPreviewsFrame").css({
					bottom: "-9999px"
				});
				$(".tooltipClientsFrame").css({
					display: "none"
				});
			}
			
			function showMap() {

				$(".neverEmpty").neverEmpty();
				$(".topNavNumbers").css("display", "none");
				$("#map").stop();
				$("#map").css("top", "0px");
				$("#map").fadeTo(options.fade_in_time, 1);

			}
			
			function replaceElements() {
				$(".infoDiv.OLD").replaceWith($("#loadContainer .infoDiv"));
				$(".topNavNumbers.OLD").replaceWith($("#loadContainer .topNavNumbers"));
				$(".overlayShortInfoFrame.OLD").replaceWith($("#loadContainer .overlayShortInfoFrame"));
				$(".overlayShortInfoFrameBottom.OLD").replaceWith($("#loadContainer .overlayShortInfoFrameBottom"));
				$(".bottomNavButtons.OLD").replaceWith($("#loadContainer .bottomNavButtons"));
				$(".topNavPageName.OLD").replaceWith($("#loadContainer .topNavPageName"));
				$(".clientsPreviewsFrame.OLD").replaceWith($("#loadContainer .clientsPreviewsFrame"));
				$(".tooltipClientsFrame.OLD").replaceWith($("#loadContainer .tooltipClientsFrame"));
				$(".mapsScript.OLD").replaceWith($("#loadContainer .mapsScript"));
				
				document.title = 'LOBO: '+$('.topNavPageName').text();
			}
			
			function refreshAfterLoad() {
				prevPluginMode = pluginMode;
						
				$('#mainContent').css('display', 'block');
				$("#loadContainer *").remove();
				
				refreshNav();
				refreshOverlayInfo();
				ajax_success = true;
				prev_active_page = active_page;
				$("img.loadingAnimation").css("display", "none");
				$("#btnBack").css('cursor', 'pointer');
				$("#btnBack").fadeTo(0, 1);
			 	$("#btnForward").css('cursor', 'pointer');
				$("#btnForward").fadeTo(0, 1);
				window.onresize();
			}
			
			//Dynamische Schriftersetzung
			function refreshCufon() {
				//Cufon aktualiesieren
				Cufon.set("fontSize", "23px");
				Cufon.set("fontFamily", "AmericanTypewriter-Medium");
				Cufon.replace(".topNavNumbers a", {
					color: "#cccccc",
					hover: {color: "#ffffff"}
				});
				Cufon.set("fontFamily", "AmericanTypewriter-Bold");
				Cufon.replace('.topNavNumbers span.topNavNumbersActive, .topNavNumbers span.topNavNumbersPageActive', {color: "#ffffff"});
				
				//Pagename
				Cufon.replace('.topNavPageName', {
					color: "#cccccc",
					fontFamily: "AmericanTypewriter-Medium"
				});
				
				//bottomNav
				Cufon.set("fontSize", "9px");
				Cufon.set("fontFamily", "Avenir LT Std");
				Cufon.set("letterSpacing", "1.7px");
				
				Cufon.replace('.bottomNavButtons span.bottomNavActive', {color: "#ffffff"});
				
				Cufon.replace('.bottomNavButtons a', {
					color: "#a0a0a0",
					hover: {color: "#ffffff"}
				});
				
				if ($(".overlayShortInfoHeader") != null) {
					$('.overlayShortInfoHeader').each(function(i) {
						Cufon.replace($(this), {color: $(this).css('color')});
					});
					Cufon.replace('.tooltipClientsInfoHeader .tooltipColumn', {color: "#7e7e7e"});
				}
				
				if ($(".addressHeader") != null) {
					Cufon.set("fontSize", "12px");
					Cufon.replace('.addressHeader', {color: "#000000"});
				}
				
				if ($(".blockPageNav") != null) {
					Cufon.set("fontSize", "8px");
					Cufon.replace('.blockPageNav', {color: "#7e7e7e"});
					Cufon.replace('.blockPageActive', {color: "#000000"});
				}
			};
			
			
			//Gallerie-Funktionen
			//Zur nächsten Seite
			function next(auto) {
				if (!ajax_success) return;				
				if (active_nr < $('.topNavNumbers a').children().length) {

					if (pluginMode == 'CLIENTLIST') {
						if (clients_scroll_complete) {
							scrollToPage("cp" + (active_nr + 1));
							++active_nr;
						}
					} else {
						var nextPage = $($('.topNavNumbers').children()[active_nr+1]);
						window.location = nextPage.attr('href');
						checkHash(false, auto);
					}
				} else {
					if (projectPlaylist.length>0 && ((playlistIndex<projectPlaylist.length-1 && playlistStartIndex==0) || (playlistIndex != playlistStartIndex-1 && playlistStartIndex > 0))) {
						playlistIndex++;
						playlistIndex = playlistIndex-Math.floor(playlistIndex/projectPlaylist.length)*projectPlaylist.length;
						
						window.location.hash = '#/'+projectPlaylist[playlistIndex];
					} else if (followCases && randomCaseIndex<randomCases.length-1) {
						randomCaseIndex++;
						window.location.hash = '#/'+randomCases[randomCaseIndex];
					} else {
						if ((projectPlaylist.length>0 && playlistIndex == projectPlaylist.length-1) || isSingleProject) {
							stop();
						}
						
						playlistIndex = 0;
						var theListItem = $('#'+active_page)[0].parentNode;
						var theRoot = theListItem.parentNode;
						
						while (theListItem) {
							theListItem = $(theListItem).next()[0];
							if (!theListItem || theListItem.className == 'test') break;
						}
						
						active_page = theListItem ? $('a', theListItem).attr('id') : null;
						if (!active_page) active_page = $('li:first a', theRoot).attr('id');
						window.location = $('a#'+active_page).attr('href');
					}
					checkHash(false, auto);
				}
				
				
			}
			
			
			//Zur vorherigen Seite
			function prev() {
				if (!ajax_success) return;
				if (active_nr > 0 && $('.topNavNumbers').children().length > 0) {
					var prevPageAnchor = $($('.topNavNumbers').children()[active_nr-1]);
					if (active_page == '27') { // 27 = clients
						scrollToPage("cp" + (active_nr - 1));
					} else {
						window.location = prevPageAnchor.attr('href');
						//ajaxLoadPage(prevPageAnchor.attr('href').split('#').pop());
					}
				} else {
					if (followCases && randomCaseIndex>0) {
						randomCaseIndex--;
						//console.log('yup3');
						window.location.hash = '#/'+randomCases[randomCaseIndex];
					} else {
						if (active_page == '29') clients_show_end = true;
						overlay_open_set = false;
						window.location = 'http://'+window.location.href.split('http://').pop().split('/').shift()+'#/'+prevPage;
						//ajaxLoadPage(prevPage);
					}
					checkHash();
				}
			};
			
			function play() {
				clearTimeout(play_next);
				play_next = setTimeout(function() {next(true);}, parseInt(options.interval));
				autoplay = true;
				$("#btnPlayPause").css("background-position", "0px 0px");
			}
			
			function stop() {
				//console.log('stop');
				clearTimeout(play_next);
				autoplay = false;
				$("#btnPlayPause").css("background-position", "0 -153px");
			}
			
			$("#btnBack").click(function(e) {
				e.preventDefault();
				stop();
				//console.log(clients_scroll_complete);
				prev();
			});
			
			$("#btnForward").click(function(e) {
				e.preventDefault();
				stop();
				next();
			});
			
			$("#btnPlayPause").click(function(e) {
				e.preventDefault();
				if (autoplay) {
					stop();
				} else {
					play();
				}
			});
			
			//Notizzettel OverlayInfo
			function refreshOverlayInfo() {
				var overlay_amount_blocks = $('.overlayShortInfoFrameContainer > div').length;
				
				if (!overlay_open_set) {
					//overlay_open = true; // not at awards and about
					var newHash = window.location.hash.replace(/slide=\d*/ig, '');
					if (lastActiveURL != newHash) {
						overlay_open = $('.newOverlayStateInfo').attr('rel') == '1';
						lastActiveURL = newHash;
						overlay_open_set = true;
					}
				}
				
				var frame_width = (overlay_amount_blocks == 2) ? 505 : 752;
				var frame_height = (overlay_amount_blocks == 2) ? 303 : 445;
				$(".overlayShortInfoFrame").css("height", (!overlay_open ? 35 : frame_height) + "px");
				
				if (active_page == "26") {
					var cases_overlay_client_name = random_case[0];
					var cases_overlay_amount_pages = random_case[1];
					var cases_overlay_client_preview_path = random_case[2];
				}
				
				//Ein- und Ausfahren
				
				$(".overlayShortInfoHeader").bind("click", function() {
					if (overlay_open) {
						$(".overlayShortInfoFrame").stop().animate({
							"height": "35px"
						}, 500, function() {
							overlay_open = false;
						});
					} else {
						$(".overlayShortInfoFrame").stop().animate({
							"height": frame_height + "px"
						}, 500, function() {
							overlay_open = true;
						});
					}
				});
				
				$(".overlayShortInfoFrame").bind("mouseleave", function() {
					if (!ajax_success) return;
					if (this.wasAutoPlay) play();
					$(".overlayShortInfoFrame").stop().animate({
						"height": "35px"
					}, 500, function() {
						overlay_open = false;
					});
				});
				
				$(".overlayShortInfoFrame").bind("mouseenter", function() {
					if (!ajax_success) return;
					this.wasAutoPlay = autoplay;
					stop();
					$(".overlayShortInfoFrame").stop().animate({
						"height": frame_height + "px"
					}, 500, function() {
						overlay_open = true;
					});
				});
				
				//Headertext und Background
				for (var i = 0; i < overlay_amount_blocks; i++) {
					
					//if ((active_page == "cases") && (i == 0)) $(".block" + (i + 1)).css("background", "transparent url(\"" + cases_overlay_client_preview_path + "\") no-repeat");
					//Paging berücksichtigen
					var block = $(".block" + (i + 1) + " .overlayShortInfoHeader");
					if (block && block.attr("class") && block.attr("class").indexOf("paged") > -1) {
						block.unbind();
						$(".blockPageNav").append($("<span class=\"blockPageNavHead\">PAGE</span>"));
						//var active_block_page = options.cases_overlay_first_block_page;
						var active_block_page = '01';
						$(".blockPage").each(function(block_page_index) {
							var block_page_number = ((block_page_index + 1) < 10) ? "0" + (block_page_index + 1) : (block_page_index + 1) + "";
							//Initialisieren, aktive Seite sichbar machen
							if ($(this).attr("id") == "bp" + active_block_page) {
								var block_page_link = $("<span class=\"blockPageNavPageNumbers blockPageActive\">" + block_page_number + "</span>");
								$(this).css("display", "block");
							} else {
								var block_page_link = $("<span class=\"blockPageNavPageNumbers\">" + block_page_number + "</span>");
							}
							
							block_page_link.bind("click", function(e) {
								//Wenn inaktiv
								if ($(this).attr("class").indexOf("blockPageActive") == -1 && block_page_switch_complete) {
									block_page_switch_complete = false;
									var new_active_block_page = $(this).text();
									var new_active_link = $(this);
									$("#bp" + active_block_page).fadeOut(300, function() {
										$("#bp" + new_active_block_page).fadeIn(300, function() {
											$(".blockPageNavPageNumbers").removeClass("blockPageActive");
											new_active_link.addClass("blockPageActive");
											active_block_page = new_active_block_page;
											//Cufon aktualisieren
											Cufon.refresh(".blockPageNav");
											Cufon.refresh(".blockPageActive");
											block_page_switch_complete = true;
										});
									});
								}
							});
							$(".blockPageNav").append(block_page_link);
						});
					} else {
						refreshCufon();
					}
				}
			}
			
			//Untere Navigation
			function refreshBottomNav() {
				$(".bottomNavButtons a").each(function(i) {
					$(this).bind("click", function(e) {
						var newTarget = $(this).attr('href');
						e.preventDefault();
						overlay_open_set = false;
						//stop();
						if (ajax_success && clients_scroll_complete) {
							//active_page = $(this).attr("id");
							//ajaxLoadPage(newTarget);
							window.location = newTarget;
							checkHash(true);
						}
					});
				});
			}
			
			//Zufällige "About"-nr ziehen
			function selectRandomAbout() {
				return Math.floor(parseInt(options.about_amount_pages) * Math.random()) + 1;
			}
			
			//Clients
			function clientsSetup() {
				//initClientsFilters();
				initClientsPreviews();
				clientItemsEventSetup();
			}
			
			function resizeClientsPreviewContainer(pic_width, pic_height, margin_bottom_right) {
				$(".clientsPreviewsFrame").css({
					width: ($(window).width() - 18) + "px",
					height: ($(window).height() - 135) + "px"
				});
				var items_count = $(".items").children("div").size();
				var item_width = pic_width + margin_bottom_right;
				var item_height = pic_height + margin_bottom_right;
				var all_items_area = item_width * item_height * items_count;
				var all_items_area_height = item_height;
				var clients_previews_frame_width = $(".clientsPreviewsFrame").width();
				clients_previews_frame_width = (clients_previews_frame_width < item_width) ? item_width : clients_previews_frame_width;
				var clients_previews_frame_height = $(".clientsPreviewsFrame").height();
				clients_previews_frame_height = (clients_previews_frame_height < item_height) ? item_height : clients_previews_frame_height;
				//Höhe angleichen
				while (all_items_area_height < (clients_previews_frame_height - item_height)) 
					all_items_area_height += item_height;
				//Lange der .items nach der Höhe berechnen
				var all_items_area_width = (all_items_area / all_items_area_height) + item_width;
				$(".items").css({
					width: all_items_area_width + "px",
					height: all_items_area_height + "px"
				});
				//Navigation: Anzahl der Seiten berechnen
				return Math.floor(all_items_area_width / clients_previews_frame_width) + 1;
			}
			
			function initClientsPreviews() {
				//Items-Container vorbereiten
				resizeClientsPreviewContainer(142, 82, 8);
				$(".clientPreviewMask").each(function(i) {					
					this.clientTagContent = $('.clientTagLinks', this.parentNode).html();
					this.todoTagContent = $('.todoTagLinks', this.parentNode).html();
					this.otherTagContent = $('.otherTagLinks', this.parentNode).html();
					$('.clientTagLinks', this.parentNode).remove();
					$('.todoTagLinks', this.parentNode).remove();
					$('.otherTagLinks', this.parentNode).remove();
				});
				
				$("a.clientPreviewMask").css({
					opacity: 0.5
				});
				$(".items img").css({
					display: "block"
				});
				switchPreviews();
			}
			
			function initClientsFilters() {
				/* Filter setup */
				//console.log("clientsSetup");
				var all_todos_active = false;
				var all_branches_active = false;
				var amount_todos_filters = $("#filterTodosContainer").children("a").size();
				var amount_branches_filters = $("#filterBranchesContainer").children("a").size();
				
				//Zufälligen filter aktivieren
				var random_todos_filter;
				var locationParamArray = String(window.location).split('?').pop().split('&');
				var locationParams = [];
				for (var p=0;p<locationParamArray.length;++p) {
					var parameter = locationParamArray[p].split('=');
					locationParams[parameter[0]] = decodeURIComponent(parameter[1]);
				}
				
				
				//var random_branches_filter = Math.floor(amount_branches_filters * (Math.random()));
				
				$("a.filterBranches").each(function(i) {
					//if (i == random_branches_filter) 
						//$(this).addClass("clientFilterActive");
				});
				
				$("#showAllTodos").bind("click", function() {
					if (all_todos_active) {
						$("a.filterTodos").removeClass("clientFilterActive");
						all_todos_active = false;
						$(this).text("show all");
					} else {
						$("a.filterTodos").addClass("clientFilterActive");
						all_todos_active = true;
						$(this).text("hide all");
					}
					switchPreviews();
				});
				
				$("#showAllBranches").bind("click", function() {
					if (all_branches_active) {
						$("a.filterBranches").removeClass("clientFilterActive");
						all_branches_active = false;
						$(this).text("show all");
					} else {
						$("a.filterBranches").addClass("clientFilterActive");
						all_branches_active = true;
						$(this).text("hide all");
					}
					switchPreviews();
				});
				
				$("a.filterTodos").click(function() {
					$(this).toggleClass("clientFilterActive");
					if ($("#filterTodosContainer").children("a.clientFilterActive").size() == amount_todos_filters) {
						all_todos_active = true;
						$("#showAllTodos").text("hide all");
					}
					if ($("#filterTodosContainer").children("a.clientFilterActive").size() == 0) {
						all_todos_active = false;
						$("#showAllTodos").text("show all");
					}
					
					$("#filterBranchesContainer a.clientFilterActive").toggleClass("clientFilterActive");
					
					switchPreviews();
				});
				
				$("a.filterBranches").bind("click", function() {
					$(this).toggleClass("clientFilterActive");
					if ($("#filterBranchesContainer").children("a.clientFilterActive").size() == amount_branches_filters) {
						all_branches_active = true;
						$("#showAllBranches").text("hide all");
					}
					if ($("#filterBranchesContainer").children("a.clientFilterActive").size() == 0) {
						all_branches_active = false;
						$("#showAllBranches").text("show all");
					}
					
					$("#filterTodosContainer a.clientFilterActive").toggleClass("clientFilterActive");
					
					switchPreviews();
				});
				
				
				if (locationParams['tag']) {
					$("a.filterTodos").each(function(i) {
						//console.log( locationParams['tag']+" // "+$(this).attr('rel')+" // "+(locationParams['tag'] == $(this).attr('rel')) );
					});
					//console.log($('a.filterTodos[rel="'+locationParams['tag']+'"]'));
					$('a.filterTodos[rel="'+locationParams['tag']+'"]').trigger("click");
				} else {
					var randomFilterIndex = Math.floor(amount_todos_filters * (Math.random()));
					$( $("a.filterTodos")[randomFilterIndex] ).trigger('click');
				}
			}
			
			function switchPreviews() {
				var tags_array = [];
				$(".filterContainer a.clientFilterActive").each(function(i) {
					tags_array.push($(this).text());
				});
				
				if (tags_array.length == 0) {
					$(".items div").each(function(i) {
						var preview_mask = $(this).children("a.clientPreviewMask");
						if (preview_mask.hasClass("selected")) preview_mask.removeClass("selected");
						
						preview_mask.stop(false, false).fadeTo(300, 0.0);
						preview_mask.addClass("selected");
					});
				} else {
					$(".clientPreviewMask").stop(false, false).fadeTo(300, 0.5);
					$(".items div").each(function(i) {
						var item_tags_array = $(this).attr("tags").split(";");
						
						var preview_mask = $(this).children("a.clientPreviewMask");
						
						if (preview_mask.hasClass("selected")) preview_mask.removeClass("selected");
						
						$.each(item_tags_array, function(index, value) {
							if (value != "") {
								$.each(tags_array, function(index_tags, tags_array_value) {
									if (tags_array_value == value) {
										//console.log(preview_mask.parent("div").attr("tags"));
										preview_mask.stop(false, false).fadeTo(300, 0.0);
										preview_mask.addClass("selected");
									}
								});
							}
						});
					});
				}
			}
			
			
			
			function initTopNavNumbersClients() {
				var new_amount_client_pages = resizeClientsPreviewContainer(142, 82, 8);
				if (new_amount_client_pages != amount_client_pages) {
					$(".topNavNumbers").html("");
					for (var i=0;i<new_amount_client_pages;++i) {
						if (i == 0) {
							$(".topNavNumbers").append($("<span id=\"cp" + i + "\" class=\"topNavNumbersActive\">"+(i+1)+"</span>"));
						} else {
							var page_nr = $("<a id=\"cp" + i + "\">"+(i+1)+"</a>");
							page_nr.bind("click", function() {
								scrollToPage($(this).attr("id"));
							})
							$(".topNavNumbers").append(page_nr);
						}
					}
					if (clients_show_end) {
						showClientsPreviewPage('cp'+(new_amount_client_pages-1));
					} else {
						showClientsPreviewPage('cp0');
					}
					refreshCufon();
					amount_client_pages = new_amount_client_pages;
				}
			}
			
			function clientItemsEventSetup() {				
				$(".clientPreviewMask").bind("mouseenter", function() {
					if (movingClientsPage) return;
					if (active_preview != null && active_preview[0] != this && !active_preview.hasClass("selected")) active_preview.fadeTo(300, 0.5);
					if (!$(this).hasClass("selected")) $(this).stop(false,false).fadeTo(300, 0.0);
					
					clearClientInfoLayer();
					$(this).addClass("tooltipOpen");
					$(".tooltipClientsInfoContent div").each(function(i) {$(this).html("")});
					$(".tooltipClientsFrame").hide();
					showTooltip($(this));
					$(".items")[0].wasAutoPlay = autoplay;
					stop();
				});
				
				$(".clientPreviewMask").bind("mouseleave", function() {
					if (!$(this).hasClass("selected")) {
						active_preview = $(this);
					}
				});
				
				$(".tooltipClientsFrame").bind("mouseleave", function() {
					if (!$(".tooltipOpen").hasClass("selected")) $(".tooltipOpen").fadeTo(300, 0.5);						
					clearClientInfoLayer();
					$(".tooltipOpen").removeClass("tooltipOpen");
					$(this).hide();
				});
				
				$(".tooltipClientsInfoHeader").bind("click", function() {
					$(".tooltipClientsFrame").fadeOut(300, function() {
						clearClientInfoLayer();
						$(".tooltipOpen").removeClass("tooltipOpen");
					});
				});
				
				$(".items").bind("mouseleave", function(e) {
					var min_x = $(this).offset().left;
					var max_x = $(this).offset().left + $(this).width();
					var min_y = $(this).offset().top;
					var max_y = $(this).offset().top + $(this).height();
					if (e.clientX >= max_x || e.clientX <= min_x || e.clientY >= max_y || e.clientY <= min_y) {
						$(".tooltipClientsFrame").fadeOut(300, function() {
							clearClientInfoLayer();
							$(".tooltipOpen").removeClass("tooltipOpen");
						});
						if ($(".items")[0].wasAutoPlay) {
							play();
						}
						active_preview.fadeTo(300, 0.5);
					}
				});
			}
			
			function clearClientInfoLayer() {
				//if ($(".tooltipOpen").length && $(".tooltipOpen .clientTagLinks").length == 0 && $(".tooltipClientsInfoContent .clientTagLinks").length) $(".tooltipOpen")[0].appendChild($(".tooltipClientsInfoContent .clientTagLinks")[0]);
				//$(".tooltipOpen .clientTagLinks").css('display', 'none');
				
			}
			
			function scrollToPage(page_nr_id, fast) {
				movingClientsPage = true;
			
				$(".tooltipClientsFrame").fadeOut(300, function() {
					clearClientInfoLayer();
					$(".tooltipOpen").removeClass("tooltipOpen");
				});
				if (active_preview) active_preview.fadeTo(300, 0.5);
			
				page_nr = parseInt(page_nr_id.split("cp")[1]);
				
				var page_width = parseInt($(".items").width() / $(".topNavNumbers").children("a, span").size());
				var scroll_position = -(page_width * parseInt(page_nr));
				var fadeSpeed = fast ? 0 : 500;
				if (clients_scroll_complete) {
					clients_scroll_complete = false;
					$(".items").animate({
						left: scroll_position + "px"
					}, fadeSpeed, function() {
						var old_active_span = $(".topNavNumbers").children("span.topNavNumbersActive");
						var old_page_nr_id = old_active_span.attr("id");
						var new_inactive_a = $("<a id=\"" + old_page_nr_id + "\">" + (parseInt(old_page_nr_id.split("cp")[1])+1) + "</a>");
						new_inactive_a.bind("click", function() {
							if (clients_scroll_complete) 
								scrollToPage($(this).attr("id"));
						});
						old_active_span.replaceWith(new_inactive_a);
						var new_active_span = $("<span id=\"" + page_nr_id + "\" class=\"topNavNumbersActive\">" + (page_nr+1) + "</span>");
						$(".topNavNumbers").children("#" + page_nr_id).replaceWith(new_active_span);
						refreshCufon();
						active_nr = parseInt(page_nr);
						clients_scroll_complete = true;
						//console.log(scroll_position);
						movingClientsPage = false;
						
						if (autoplay) play();
					});
				}
			}
			
			function showClientsPreviewPage(page_nr_id) {
				clients_scroll_complete = false;
				page_nr = parseInt(page_nr_id.split("cp")[1]);
				var page_width = parseInt($(".items").width() / $(".topNavNumbers").children("a, span").size());
				var scroll_position = -(page_width * parseInt(page_nr));
				
				$(".items").css({
					left: scroll_position + "px"
				});
				var old_active_span = $(".topNavNumbers").children("span.topNavNumbersActive");
				var old_page_nr_id = old_active_span.attr("id");
				var new_inactive_a = $("<a id=\"" + old_page_nr_id + "\">" + (parseInt(old_page_nr_id.split("cp")[1])+1) + "</a>");
				new_inactive_a.bind("click", function() {
					scrollToPage($(this).attr("id"));
				});
				old_active_span.replaceWith(new_inactive_a);
				var new_active_span = $("<span id=\"" + page_nr_id + "\" class=\"topNavNumbersActive\">" + (page_nr+1) + "</span>");
				$(".topNavNumbers").children("#" + page_nr_id).replaceWith(new_active_span);
				refreshCufon();
				active_nr = parseInt(page_nr);
				clients_scroll_complete = true;
			}
			
			function showTooltip(preview_mask) {
				if (!mayShowToolTop) return;
				tooltip_pos_y = preview_mask.offset().top - 4;
				if (($(".clientsPreviewsFrame").width() / 2) < (preview_mask.offset().left + 100)) 
					tooltip_pos_x = preview_mask.offset().left - 501;
				else 
					tooltip_pos_x = preview_mask.offset().left + 146;
				
				/*
				var tags_array = preview_mask.parent().attr("tags").split(";");
				$.each(tags_array, function(index, value) {
					var tag_link = $("<a>" + value + "</a>");
					$(".tooltipClientsInfoContent").append(tag_link);
				});
				*/
				
				/*
				var client_link = $("<a>" + preview_mask.parent().attr("client") + "</a>");
				var case_study = $("<a href=\"" + preview_mask.attr("href") + "\">case study</a>");
				$(".tooltipClientsInfoContent").append(client_link).append(case_study).append($("<br />"));
				*/
				
				$(".tooltipClientsInfoContent .clientColumn").html(preview_mask[0].clientTagContent);
				$(".tooltipClientsInfoContent .todoColumn").html(preview_mask[0].todoTagContent);
				$(".tooltipClientsInfoContent .otherColumn").html(preview_mask[0].otherTagContent);
				
				$("a.branchFilterTrigger").bind("click", function() {
					if ($('a.filterBranches[tag='+$(this).attr('tag')+']').hasClass('clientFilterActive')) return;
					$('a.filterBranches[tag='+$(this).attr('tag')+']').click();
				});
				
				$(".tooltipClientsFrame").css({
					left: tooltip_pos_x + "px",
					top: tooltip_pos_y + "px"
				}).show(300, function() {
				
				});
			}
			//----------------------------------------------------------------------------------------------------------------------------------			
		});
	};
})(jQuery);

