/* USAGE:
		searchWindow = new AppWindowClass();
		searchWindow.id = 'searchWindow23';
		searchWindow.name = 'searchWindow';
		searchWindow.init();
*/

quickSearchContainerDisplayed = false;
var quickSearchCache = new Array();
var selectedQuickSearchResult = -1;
var quickSearchResults = new Array();

function searchInputChanged(evt) {
	if (navigator.appName=="Microsoft Internet Explorer") {
		keyCode = evt.keyCode;
	}
		
	if (navigator.appName=="Netscape") {
		keyCode = evt.which;
	}
	
	if(keyCode==13) {
		// Enter
		if(selectedQuickSearchResult==-1) {
			search();
		} else {
			if(quickSearchContainerDisplayed) {
				document.location.href = quickSearchResults[selectedQuickSearchResult]["url"];
			}
		}
	} else if(keyCode==27) {
		// Escape-Key
		hideQuickSearchResults();
	} else if(keyCode==38) {
		// Arrow-Up-Key
		if(quickSearchContainerDisplayed) {		
			if(selectedQuickSearchResult!=-1) {
				document.getElementById('Res' + selectedQuickSearchResult).className = quickSearchResults[selectedQuickSearchResult]["className"];
			}
			
			selectedQuickSearchResult--;
			
			if(selectedQuickSearchResult >= 0) {
				document.getElementById('Res' + selectedQuickSearchResult).className = quickSearchResults[selectedQuickSearchResult]["className"] + " hovered";
			} else {
				selectedQuickSearchResult = -1;
			}
		}
	} else if(keyCode==40) {
		// Arrow-Down-Key
		if(quickSearchContainerDisplayed) {		
			if(selectedQuickSearchResult!=-1 && selectedQuickSearchResult < quickSearchResults.length - 1) {
				document.getElementById('Res' + selectedQuickSearchResult).className = quickSearchResults[selectedQuickSearchResult]["className"];
			}
			
			selectedQuickSearchResult++;
			
			if(selectedQuickSearchResult < quickSearchResults.length) {
				document.getElementById('Res' + selectedQuickSearchResult).className = quickSearchResults[selectedQuickSearchResult]["className"] + " hovered";
			} else {
				selectedQuickSearchResult--;
			}
		}
	} else {
		searchString = document.getElementById('searchInputField').value;
		
		if(typeof(quickSearchCache[searchString])=='undefined') {
			var output = new Object();
			output.searchString = encodeURIComponent(document.getElementById('searchInputField').value);
				
			outputString = JSONstring.make(output);
		
			jsonPostData('json/search/quickSearch.php', escape(outputString), 'displayQuickSearchResults');
		} else {
			displayQuickSearchResults(quickSearchCache[searchString]);
		}
	}
}

function hideQuickSearchResults() {
	if(quickSearchContainerDisplayed) {
		document.getElementById("quickSearchContainer").style.display = 'none';
	}
}

function displayQuickSearchResults(Object) {
	var bgClassName = 'even';
	var validResults = false;
	var absResCnt = 0;
	
	if(Object) {
		if(Object["status"] && Object["string"]) {
			if(Object["status"]=='ok') {
				if(Object["categories"]) {
					if(Object["categories"].length >= 1) {
						// Cache Search-Results
						quickSearchCache[searchString] = Object;
						
						if(Object["string"] == document.getElementById('searchInputField').value) {
							selectedQuickSearchResult = -1;
							quickSearchResults = new Array();
							// Results are valid
							var searchString = Object["string"];
							validResults = true;
							
							// Add QuickSearchContainer to DOM if not already added
							if(!quickSearchContainerDisplayed) {
								quickSearchContainer = document.createElement("DIV");
								quickSearchContainer.id = 'quickSearchContainer';
								quickSearchContainer.className = 'quickSearchContainer';
								
								document.getElementById('mainContent').appendChild(quickSearchContainer);
								 
								quickSearchContainerDisplayed = true;
							}
							
							// Display QuickSearchContainer
							document.getElementById("quickSearchContainer").style.display = 'inline';
							// Empty QuickSearchContainer
							document.getElementById("quickSearchContainer").innerHTML = '';
							
							// Display Results
							for(catCnt=0; catCnt < Object["categories"].length; catCnt++) {
								if(Object["categories"][catCnt]["results"]) {
									if(Object["categories"][catCnt]["results"].length >= 1) {
										
										for(resCnt=0; resCnt < Object["categories"][catCnt]["results"].length; resCnt++) {
											
											quickSearchResultContainer = document.createElement("DIV");
											quickSearchResultContainer.className = 'quickSearchResultContainer';
	
											quickSearchResultContainerBg = document.createElement("DIV");
											quickSearchResultContainerBg.className = 'quickSearchResultContainerBg';
	
											quickSearchResultContainer.appendChild(quickSearchResultContainerBg);										
											
											if(resCnt==0) {												
												categoryContainer = document.createElement("DIV");
												categoryContainer.className = 'categoryContainer';
												categoryContainer.innerHTML = Object["categories"][catCnt]["title"] + ":";
												
												quickSearchResultContainer.appendChild(categoryContainer);
											}
											
											if(bgClassName=='even') {
												bgClassName = 'uneven';
											} else {
												bgClassName = 'even';
											}

											// Save Result
											quickSearchResults[absResCnt] = new Array();
											quickSearchResults[absResCnt]["className"] = 'resultContent ' + bgClassName + ' ' + Object["categories"][catCnt]["color"];
											quickSearchResults[absResCnt]["url"] = Object["categories"][catCnt]["results"][resCnt]["url"];
											
											resultContent = document.createElement("DIV");
											resultContent.id = 'Res' + absResCnt;
											resultContent.className = 'resultContent ' + bgClassName + ' ' + Object["categories"][catCnt]["color"];
											
											eval("resultContent.onclick = function() { document.location.href = '" + Object["categories"][catCnt]["results"][resCnt]["url"] + "'; };");
											eval("resultContent.onmouseover = function() { document.getElementById('" + resultContent.id + "').className = 'resultContent " + Object["categories"][catCnt]["color"] + " hovered'; };");
											eval("resultContent.onmouseout = function() { document.getElementById('" + resultContent.id + "').className = 'resultContent " + bgClassName + " " + Object["categories"][catCnt]["color"] + "'; };");
											
											
											resultTitle = document.createElement("DIV");
											resultTitle.className = 'quickSearchResultTitle';
											resultTitle.innerHTML = Object["categories"][catCnt]["results"][resCnt]["title"];
	
											resultSubTitle = document.createElement("DIV");
											resultSubTitle.className = 'quickSearchResultSubTitle';									
											resultSubTitle.innerHTML = Object["categories"][catCnt]["results"][resCnt]["subTitle"];
											
											resultThumbnailContainer = document.createElement("DIV");
											resultThumbnailContainer.className = 'quickSearchResultThumbnailContainer';
											
											if(Object["categories"][catCnt]["results"][resCnt]["imagePath"]) {
												resultThumbnail = document.createElement("IMG");
												resultThumbnail.src = Object["categories"][catCnt]["results"][resCnt]["imagePath"];
												resultThumbnail.className = 'quickSearchResultThumbnail';
												resultThumbnailContainer.appendChild(resultThumbnail);
											}
											
	
											resultContent.appendChild(resultTitle);
											resultContent.appendChild(resultSubTitle);
											resultContent.appendChild(resultThumbnailContainer);
											
											quickSearchResultContainer.appendChild(resultContent);
											
											document.getElementById("quickSearchContainer").appendChild(quickSearchResultContainer);
											
											absResCnt++;
										}
									}
								}
							}
							
							// Display Bottom-Border of Results
							quickSearchResultContainer = document.createElement("DIV");
							quickSearchResultContainer.className = 'quickSearchResultContainer bottomBorder';
	
							quickSearchResultContainerBg = document.createElement("DIV");
							quickSearchResultContainerBg.className = 'quickSearchResultContainerBg';
	
							quickSearchResultContainer.appendChild(quickSearchResultContainerBg);	
							
							resultContent = document.createElement("DIV");
							resultContent.className = 'resultContent';
							
							quickSearchResultContainer.appendChild(resultContent);
							
							document.getElementById("quickSearchContainer").appendChild(quickSearchResultContainer);
							
							bottomBorder = document.createElement("DIV");
							bottomBorder.className = 'bottomBorder';
							
							document.getElementById("quickSearchContainer").appendChild(bottomBorder);						
						}
					}
				}
			}
		}
	}
	
	// If no valid Results => hide QuickSearchContainer
	if(!validResults) {
		hideQuickSearchResults();		
	}
}

function SearchWindowClass() {
	var currentPage = 1;
	var type = 'user';
	var generalSearch = true;
	
	this.init = function() {
		this.buildContainer();
		this.box = document.getElementById(this.id + 'windowContainer');
		
		scrollPosition = getCurrentScrollPosition();
		
		topPos = scrollPosition["top"] + 150;
		if(topPos < 170) {
			topPos = 170;
		}
		
		topPos = topPos + Math.floor(Math.random()*100);
		
		this.box.style.top = topPos + "px";	
		leftPos = Math.ceil((scrollPosition["width"] / 2) - 470) + Math.floor(Math.random()*60);		
		
		if(leftPos < 0) {
			leftPos = 10;
		}
		
		this.box.style.left = leftPos + "px";		

		this.show();

		this.search();
	}
	
	this.show = function() {
		this.box.style.zIndex = windowManager.getCurrentZIndex() + 1;
		this.box.style.display = 'block'; 
	}
	
	this.search = function() {
		currentPage = 1;
		this.searchStringValue = document.getElementById(this.id + 'searchInputField').value;
		this.searchInt();
	}
	
	this.searchInt = function() {
		var output = new Object();
		output.searchString = encodeURIComponent(this.searchStringValue);
		output.searchType = type;
		output.limit = 20;
		output.page = currentPage;
			
		outputString = JSONstring.make(output);

		jsonPostData('json/search/search.php', escape(outputString), this.name + '.displayResults');		
	}

	this.displayResults = function(Object) {
		var showErrorMessage = true;
		document.getElementById(this.id + 'resultsList').innerHTML = '';
		
		if(Object) {
			if(Object["status"]) {
				if(Object["status"]=='ok') {
					this.tabController.addBatchToTab(0, Object["userCounter"], false);
					//this.tabController.changeTab(1, "Gruppen (" + Object["groupsCounter"] + ")");
					this.tabController.addBatchToTab(1, Object["eventsCounter"], false);
					this.tabController.addBatchToTab(2, Object["locationsCounter"], false);
					this.tabController.addBatchToTab(3, Object["schoolsCounter"], false);					
					//this.tabController.changeTab(5, "Bilder (" + Object["photosCounter"] + ")");
					//this.tabController.changeTab(5, "Blogs (" + Object["blogsCounter"] + ")");
					//this.tabController.changeTab(5, "Live-Blogs (" + Object["liveBlogsCounter"] + ")");
				
					if(Object["results"]) {
						if(Object["counter"]) {
							pageCounter = Math.ceil(Object["counter"] / 20);
							if(currentPage == 1) {
								prevPageLink = '<img src="/images/style/arrows/greyArrowLeft.gif" class="arrowLeftIcon"/>';				
							} else {
								prevPageLink = '<a href="JavaScript:' + escape(this.name) + '.prevPage();"><img src="/images/style/arrows/greyArrowLeftActive.gif" class="arrowLeftIcon"/></a>';							
							}
							
							if(currentPage == pageCounter) {
								nextPageLink = '<a href="#"><img src="/images/style/arrows/greyArrowRight.gif" class="arrowRightIcon"/></a>';
							} else {
								nextPageLink = '<a href="JavaScript:' + escape(this.name) + '.nextPage();"><img src="/images/style/arrows/greyArrowRightActive.gif" class="arrowRightIcon"/></a>';							
							}								

							document.getElementById(this.id + 'upperPageBar').innerHTML = prevPageLink + 'Seite ' + currentPage + ' von ' + pageCounter + nextPageLink;	
							document.getElementById(this.id + 'bottomPageBar').innerHTML = prevPageLink + 'Seite ' + currentPage + ' von ' + pageCounter + nextPageLink;	
						}
						
						showErrorMessage = false;
						
						if(Object["results"].length > 0) {
							evenString = 'even';
							for(resCnt = 0; resCnt <= Object["results"].length - 1; resCnt++) {
								var listContainer = document.createElement("DIV");
								listContainer.id = this.id + 'lC' + resCnt;
								listContainer.className = 'listContainer ' + evenString;
								
								eval("listContainer.onmouseover = function() { document.getElementById('" + this.id + 'lC' + resCnt + "').className = '" + listContainer.className + " hovered' };");
								eval("listContainer.onmouseout = function() { document.getElementById('" + this.id + 'lC' + resCnt + "').className = '" + listContainer.className + "' };");
								eval("listContainer.onclick = function() { newWindow = window.open('" + Object["results"][resCnt]["URL"] + "', 'Suchfenster'); };");
																												
								var listThumbnailContainer = document.createElement("DIV");
								listThumbnailContainer.className = 'listThumbnailContainer';
								
								if(Object["results"][resCnt]["ImagePath"]) {
									var listThumbnail = document.createElement("IMG");
									listThumbnail.className = 'listThumbnail';
									listThumbnail.src = Object["results"][resCnt]["ImagePath"];
									
									listThumbnailContainer.appendChild(listThumbnail);
								}
								
								listTitle = document.createElement("DIV");
								listTitle.className = 'listTitle';
								if(Object["results"][resCnt]["Title"].length > 39) {
									Object["results"][resCnt]["Title"] = Object["results"][resCnt]["Title"].slice(0, 38);
									Object["results"][resCnt]["Title"] = Object["results"][resCnt]["Title"] + '...';
								}
								listTitle.innerHTML = Object["results"][resCnt]["Title"];
								
								listSubTitle = document.createElement("DIV");
								listSubTitle.className = 'listSubTitle';
								listSubTitle.innerHTML = Object["results"][resCnt]["SubTitle"];
								
								listLink = document.createElement("A");
								listLink.href = Object["results"][resCnt]["URL"];
								listLink.className = 'listLink';
								listLink.innerHTML = '&raquo;';
								
								listContainer.appendChild(listThumbnailContainer);
								listContainer.appendChild(listTitle);
								listContainer.appendChild(listSubTitle);
								listContainer.appendChild(listLink);
								
								document.getElementById(this.id + 'resultsList').appendChild(listContainer);
								
								if(evenString=='even') {
									evenString = 'uneven';
								} else {
									evenString = 'even';
								}
							}
						}
					}
				}
			}
		}
		
		if(showErrorMessage) {
			document.getElementById(this.id + 'upperPageBar').innerHTML = '';
			document.getElementById(this.id + 'bottomPageBar').innerHTML = '';
			
			var errorMessage = document.createElement("DIV");
			errorMessage.className = 'errorMessage';
			errorMessage.innerHTML = '<h1>Oooh ...</h1> Zu diesem Suchbegriff konnten wir nichts finden!';
			document.getElementById(this.id + 'resultsList').appendChild(errorMessage);
			
			if(generalSearch) {
				if(Object["userCounter"] >= 1) {
					this.tabController.setActiveTab(0);
				} else if(Object["eventsCounter"] >= 1) {
					this.tabController.setActiveTab(1);				
				} else if(Object["locationsCounter"] >= 1) {
					this.tabController.setActiveTab(2);				
				} else if(Object["schoolsCounter"] >= 1) {
					this.tabController.setActiveTab(3);				
				}
			}
		}
		
		generalSearch = false;
	}

	this.close = function() {
		this.box.style.display = 'none';
		this.box.innerHTML = '';
	}

	this.setHeader = function(headerString) {
		document.getElementById(this.id + 'ContainerHeader').innerHTML = headerString;
	}

	this.setSubHeader = function(headerString) {
		document.getElementById(this.id + 'ContainerSubHeader').innerHTML = headerString;
	}

	this.dragWindow = function(evt) {
		var mousePosition = getMousePosition(evt);
		
		windowManager.draggedWindow = this.box;	
		windowManager.windowPositionRelativeToMousePosition = getElementPositionRelativeToMousePosition(document.getElementById(this.id + 'windowContainer'), mousePosition);
		
		// Set Event-Handler for Dragging
		eval("document.onmousemove = " + this.name + ".mousemoveEventHandler;");
		eval("document.onmouseup = " + this.name + ".dropWindow;");
		  	
		// Disable Text-Selection
		disableTextSelection(document.getElementsByTagName("body")[0]);
	}
	
	this.dropWindow = function() {	
		document.onmousemove = null;
		document.onmouseup = null;

		enableTextSelection(document.getElementsByTagName("body")[0]);
		
		windowManager.draggedWindow = false;
	}

	this.mousemoveEventHandler = function(evt) {
		var mousePosition = getMousePosition(evt);
		
		mousePosition["x"] = mousePosition["x"] - windowManager.windowPositionRelativeToMousePosition["x"];
		mousePosition["y"] = mousePosition["y"] - windowManager.windowPositionRelativeToMousePosition["y"];

		// Set DragBox-Position
		windowManager.draggedWindow.style.top = mousePosition["y"] + "px";
		windowManager.draggedWindow.style.left = mousePosition["x"] + "px";	
	}
	
	this.setToTop = function() {
		this.box.style.zIndex = windowManager.increaseZIndex();
	}

	this.tabSelected = function(id) {
		var bkpType = type;
		
		if(id==0) {
			type='user';
		} else if(id==1) {
			type='events';
		} else if(id==2) {
			type='locations';			
		} else if(id==3) {
			type='schools';
		} else if(id==4) {
			//type='photos';
			type='liveBlogs';
		} else if(id==6) {
			type='liveBlogs';
		} else if(id==7) {
			//type='liveBlogs';
		}
		
		if(bkpType != type) {
			currentPage = 1;
			this.search();
		}
	}

	this.nextPage = function() {
		currentPage++;
		this.searchInt();
	}
	
	this.prevPage = function() {
		if(currentPage >= 2) {
			currentPage--;
			this.searchInt();
		}
	}

	this.buildContainer = function() {
		var windowContainer = document.createElement("DIV");
		windowContainer.id = this.id + 'windowContainer';
		windowContainer.className = 'searchWindowContainer';
		eval("windowContainer.onclick = function() { " + this.name + ".setToTop(); };");
		
		windowDragBar = document.createElement("DIV");
		windowDragBar.id = this.id + 'windowDragBar';
		windowDragBar.className = 'searchWindowDragBar';
		eval("windowDragBar.onmousedown = function(event) { " + this.name + ".dragWindow(event); };");
			
		var windowBackground = document.createElement("DIV");
		windowBackground.className = 'searchWindowBackground';
		
		// CloseLink + Container
		var closeLinkContainer = document.createElement("DIV");
    	closeLinkContainer.id = this.id + "CloseLink";
    	closeLinkContainer.className = "searchWindowContainerCloseLink";
	
 		var closeLink = document.createElement("A");
    	closeLink.href = "JavaScript:" + this.name + ".close();";
    	closeLink.innerHTML = "X";
    	closeLinkContainer.appendChild(closeLink); 	

    	windowContainer.appendChild(windowBackground);  	
		windowContainer.appendChild(windowDragBar);
    	windowContainer.appendChild(closeLinkContainer);  
    	// End CloseLink
	    	
    	// Header
		var containerHeader = document.createElement("DIV");
    	containerHeader.id = this.id + "ContainerHeader";
    	containerHeader.className = "searchWindowContainerHeader";
		containerHeader.innerHTML = 'Suchergebnisse ...';
		
		var tabContainer = document.createElement("DIV");
		tabContainer.id = this.id + 'tabContainer';
		tabContainer.className = 'tabContainer';

		var searchBar = document.createElement("DIV");
		searchBar.className = 'searchBar';
		
		var searchForm = document.createElement("FORM");
		searchForm.action = 'javaScript:' + this.name + '.search();';
		
		var searchInputField = document.createElement("INPUT");
		searchInputField.type = 'text';
		searchInputField.id = this.id + 'searchInputField'
		searchInputField.className = 'searchInputField';
		searchInputField.value = this.searchString;
		
		var searchButton = document.createElement("INPUT");
		searchButton.type = 'image';
		searchButton.className = 'searchButton';
		searchButton.src = '/images/style/searchButton.jpg'
		
		searchForm.appendChild(searchInputField);
		searchForm.appendChild(searchButton);
		searchBar.appendChild(searchForm);		

		var containerContent = document.createElement("DIV");
		containerContent.id = this.id + 'content';
		containerContent.className = 'containerContent';
		
		var searchResultsContainer = document.createElement("DIV");
		searchResultsContainer.id = this.id + 'searchResultsContainer';
		searchResultsContainer.className = 'searchResultsContainer';
		
		var upperPageBar = document.createElement("DIV");
		upperPageBar.id = this.id + 'upperPageBar';
		upperPageBar.className = 'pageBar';

		var resultsList = document.createElement("DIV");
		resultsList.id = this.id + 'resultsList';
		resultsList.className = 'resultsList';

		var bottomPageBar = document.createElement("DIV");
		bottomPageBar.id = this.id + 'bottomPageBar';		
		bottomPageBar.className = 'pageBar bottom';

		searchResultsContainer.appendChild(upperPageBar);		
		searchResultsContainer.appendChild(resultsList);
		searchResultsContainer.appendChild(bottomPageBar);		
		
		containerContent.appendChild(searchResultsContainer);
		
		// Add Header
    	windowContainer.appendChild(containerHeader);
    	windowContainer.appendChild(tabContainer);
		windowContainer.appendChild(containerContent);
		
		windowContainer.appendChild(searchBar);
		
		document.getElementsByTagName("body")[0].appendChild(windowContainer);
		
		// Initialise Tab-Container
		this.tabController = new TabControllerClass();		
		this.tabController.id = this.id + "tabContainer";
		this.tabController.name = this.name + ".tabController";
		this.tabController.eventHandler = this;
		this.tabController.init();
		// Set Tabs
		this.tabController.addTab(0, "Personen");
		//this.tabController.addTab(1, "Gruppen");
		this.tabController.addTab(1, "Events");
		this.tabController.addTab(2, "Locations");
		this.tabController.addTab(3, "Schulen / Unis");
		//this.tabController.addTab(5, "Bilder");
		//this.tabController.addTab(5, "Blogs");
		//this.tabController.addTab(5, "Live-Blogs");
		// Set initial active Tab
		this.tabController.setActiveTab(0);			
	}
}
