var mouse_position = {x: 0, y: 0};

var technology_search = {
	/**
	 * 
	 */
	start_project : function(custom) {
		custom = typeof custom != 'undefined' ? custom : false;
		
		jQuery.post(doc_root + "includes/ajax/technology.search.exec.php", {
			type: 'start_project'
		}, function(data, status) {
			if (data.save_project) { // save project successful
				
				if (!custom) { // feedback if project has been started through a key user after search
					alert(gt.gettext("Ihre Suche wurde an den zuständigen TMG-Mitarbeiter übermittelt."));
					window.location.href = doc_root + 'page/front/';
					// meldung + umleitung zur start seite (persönlich)
					// meldung: Ihre Suche wurde an den zuständigen TMG-Mitarbeiter übermittelt.
								// Sie werden nun zur Startseite umgeleitet
				}
				else { // feedback if project started manually by an administrator
					// update "new projects" box
					projectroom.box.get('all-started-projects', gt.gettext("Lade Projekte ..."));
				}
			}
			else {
				alert(gt.gettext("Projekt konnte aus technischen Gründen nicht gestartet werden."));
			}
		
		}, "json");		
	},
	
	/**
	 * 
	 * @param {} page_is_search
	 */
	bind_events : function(page_is_search) {
		technology_search.add_click_event(page_is_search);
		technology_search.add_enter_key_event(page_is_search);
			
	},
	
	/**
	 * 
	 */
	unbind_events : function() {
		jQuery('#searchBtn').unbind('click');
		jQuery('#searchfield').unbind('keydown');
	},
	
	/**
	 * 
	 * @param {} page_is_search
	 */
	add_click_event : function(page_is_search) {
		jQuery('#searchBtn').click(function(e) {
			technology_search.execute(page_is_search);
		});
	},
	
	/**
	 * 
	 * @param {} page_is_search
	 */
	add_enter_key_event : function (page_is_search) {
		jQuery('#searchfield').keydown(function (e) {
			if (e.keyCode == 13) {
				technology_search.execute(page_is_search);	
			}
		});
	},
	
	/**
	 * 
	 */
	execute: function(page_is_search) {
				
		page_is_search = typeof page_is_search != 'undefined' ? page_is_search : false; 
		
		user.log('Button_Clicked', 'User_Technology_Searched');
		var searchvalue = jQuery.trim(jQuery('#searchfield').val());
		
		if (typeof searchvalue == 'string' && searchvalue != '') {
			// remove click and enter-key events to avoid double execution 
			technology_search.unbind_events();
			
			// check searchvalue to be a valid technology
			jQuery.post(doc_root + 'includes/ajax/technology.search.exec.php', {
				type:"check_technology", 
				value:searchvalue
			}, function(data, status) {
				if (data.validTechnology) {
					// submit search asyncronous
					jQuery.post(doc_root + 'includes/ajax/technology.search.exec.php', {
						type:"search", 
						value:searchvalue
					}, function() {
						if (page_is_search) {
							technology_search.render();						
						}
						else {
							window.location.href = doc_root + 'user/search';
						}
					}, 'json');
				}
				else {
					technology_search.bind_events(false);
					alert(gt.gettext("Die Technologie existiert nicht"));
				}
			}, "json");
		}
		else {
			alert(gt.gettext("Der eingegebene Begriff ist ungültig"));
		}		
	},

	
	/**
	 * Gets the value from the input field and 
	 * performs a search on it.
	 */
	perform_add_searchvalue : function() {
		var searchvalue = jQuery.trim(jQuery('#searchfieldADD').val());
//		alert(searchvalue);
		if (searchvalue.length <= 0) {
			alert(gt.gettext("Kein Begriff eingetragen"));
			return;
		}
		
		technology_search.add_searchvalue(searchvalue);
		jQuery('#searchfieldADD').val('');
		
	},
	
	/**
	 * 
	 * @param {} technology_id
	 */
	isolate : function(technology_id) {
		// to avoid multiple binding of the event click each time
		// the search_result cloud is beeing generated
//		jQuery(event.currentTarget).unbind("click");  
		
		
		var searchvalue = "verfeinern" + technology_id; 
		
		jQuery.post(doc_root + 'includes/ajax/technology.value.get.php', {
			id:searchvalue
		}, function(data, status) {
			if ('success' == status) {  
				searchvalue = data.tech_headline;
				
				technology_search.add_searchvalue(searchvalue);
			}
		}, "json");
		
		//animate( params, [duration], [easing], [callback] ) 
	},

	/**
	 * Adds a searchvalue to the current search.
	 * @param {} searchvalue
	 */
	add_searchvalue : function(searchvalue) {
		// perform serach with the clicked and found value
		// see comments in the php file for how it works exactely
		jQuery.post(doc_root + 'includes/ajax/technology.search.exec.php', {
			type:"add", 
			value:searchvalue
		}, technology_search.render, "json");		
	},
	
	/**
	 * Removes an search-term from current-search-values. 
	 * depth and index are coordinates for the 2-dim array where the term is.
	 * @param {} depth
	 * @param {} index
	 */
	remove_searchvalue : function(depth, index) {
		jQuery.post(doc_root + 'includes/ajax/technology.search.exec.php', {
			type : 'remove',
			depth : depth,
			index : index
		}, technology_search.render, 'json');
	},
	
	/**
	 * @param element_id - String - DOM-id of an element
	 * @param data - Array - of objects with search data to populate the element with
	 */
	update_element : function(element_id, data) {
		var update_html = ""; 
		if (typeof data == 'object') {
			for (var i = 0; i < data.length; i ++) {
				update_html += '<div>' + data[i] + '</div>';
			}
		}
		else {
			update_html += data;
		}
		jQuery(element_id).html(update_html);
	},
	
	/**
	 * 
	 */
	disableArrowButtons : function (identifier, direction) {
		jQuery('#bt-history-' + identifier).unbind();
		jQuery('#bt-history-ff-' + identifier).unbind();
		jQuery('#bt-history-' + identifier).css('background', 'url(' + doc_root + 'misc/icons/bt_arrow_' + direction + '_disabled.gif) no-repeat');
		jQuery('#bt-history-ff-' + identifier).css('background', 'url(' + doc_root + 'misc/icons/bt_doublearrow_' + direction + '_disabled.gif) no-repeat');
	},
	
	/**
	 * 
	 */
	addEventArrowButtons : function (identifier, direction, search_type, next_load_index) {
		jQuery("#bt-history-" + identifier).unbind('click');
		jQuery("#bt-history-" + identifier).one('click', function() {
			var url = doc_root + "includes/ajax/technology.search.exec.php";
			jQuery.post(url, {
				type: search_type,
				load: next_load_index
			}, technology_search.render);
		});
		jQuery("#bt-history-ff-" + identifier).unbind('click');
		jQuery("#bt-history-ff-" + identifier).one('click', function() {
			var url = doc_root + "includes/ajax/technology.search.exec.php";
			jQuery.post(url, {
				type: search_type,
				load:"last"
			}, technology_search.render);
		});
		jQuery('#bt-history-' + identifier).css('background', 'url(' + doc_root + 'misc/icons/bt_arrow_' + direction + '.gif) no-repeat');
		jQuery('#bt-history-' + identifier).hover(function() {
			jQuery(this).css('background', 'url(' + doc_root + 'misc/icons/bt_arrow_' + direction + '_hover.gif) no-repeat');
		}, function() {
			jQuery(this).css('background', 'url(' + doc_root + 'misc/icons/bt_arrow_' + direction + '.gif) no-repeat');
		});
		
		jQuery('#bt-history-ff-' + identifier).css('background', 'url(' + doc_root + 'misc/icons/bt_doublearrow_' + direction + '.gif) no-repeat');
		jQuery('#bt-history-ff-' + identifier).hover(function() {
			jQuery(this).css('background', 'url(' + doc_root + 'misc/icons/bt_doublearrow_' + direction + '_hover.gif) no-repeat');
		}, function() {
			jQuery(this).css('background', 'url(' + doc_root + 'misc/icons/bt_doublearrow_' + direction + '.gif) no-repeat');
		});
	},	

	/**
	 * Function to call via onlick attribute in htmlcode (without var).
	 * @param String from - previous or next searches
	 * @param Integer arrIndex - which index of array with search has to be loaded  
	 */
	load_search : function(from, arrIndex) {
		jQuery.post(doc_root + "includes/ajax/technology.search.exec.php", {
			type: from,
			load: arrIndex
		}, technology_search.render);
	},	
	
	/**
	 * 
	 */
	render : function() {
//		if (jQuery("#submittedSearchvalue").length > 0) {
//			var submittedSearchValue = $("#submittedSearchvalue").val();
//			$("#submittedSearchvalue").remove();
////			alert('remove: ' + submittedSearchValue);
//			submitSearch(submittedSearchValue);
//		}
		
		// empty the search field
		jQuery("#searchfield").val(""); 
		
		// update search history
		jQuery.post(doc_root + 'includes/ajax/technology.search.history.get.php', {
		}, function (data, status) {
			// disable buttons if prev_searches emtpy
//			if (data.prev_searches.length > 0) {
//				technology_search.addEventArrowButtons('back', 'left', 'prev', data.prev_searches_goto_index);
//			}
//			else {
//				technology_search.disableArrowButtons('back', 'left');
//			}
//			
//			if (data.next_searches.length > 0) {
//				technology_search.addEventArrowButtons('fwd', 'right', 'next', data.next_searches_goto_index);
//			}
//			else {
//				technology_search.disableArrowButtons('fwd', 'right');
//			}
			
			// update prev searches box
			technology_search.update_element("#prev-searches", data.prev_searches);

			// update next searches
			technology_search.update_element("#next-searches", data.next_searches);
			
			// update current search values (so the user sees what he searched)
			technology_search.update_element("#current-search-values", data.current_search_values);
			
			if (data.search_result_cloud != "" && data.search_result_cloud != null) {
				// do some animation
				jQuery("#search-result").fadeOut("slow", function(){
					jQuery("#search-result").empty();
					
					jQuery("#search-result").append(data.search_result_cloud); 
					//window.setTimeout(hovertipInit, 1);
					
					jQuery("#search-result").fadeIn("slow", function() {});
				});
			}
			else {
				jQuery("#search-result").html('<span style="font-weight:bold;">' + gt.gettext("Der Suchbegriff lieferte keine Ergebnisse") + '</span>');
				//window.setTimeout(hovertipInit, 5);
			}
			
			window.setTimeout(function() {
				//alert($(".mainsearchli").length);
				if (jQuery(".mainsearchli").length < 10) {
					jQuery("#search-result").css('height', 150);
					jQuery("#search-result").css('overflow', 'auto');
				} 
				else if (jQuery(".mainsearchli").length < 15) {
					jQuery("#search-result").css('height', 200);
					jQuery("#search-result").css('overflow', 'auto');
				} 
				else if (jQuery(".mainsearchli").length < 20) {
					jQuery("#search-result").css('height', 300);
					jQuery("#search-result").css('overflow', 'auto');
				} 
				else {
				 	jQuery("#search-result").css('height', 400);
					jQuery("#search-result").css('overflow', 'auto');
				}	
				
				
				// add onclick-event again
				technology_search.bind_events(false);
				
			}, 1000);
		}, "json");	
	},
	
	get_mouseclick_position : function() {
		jQuery().click(function(e) {
			mouse_position.x = e.pageX;
			mouse_position.y = e.pageY;
		});
	},
	cloud : {
		additional_options : {
			/**
			 * 
			 * @param {} technology_id
			 */
			show : function(technology_id) {
				jQuery('#list_' + technology_id).css('visibility', 'visible');
			},
			
			/**
			 * 
			 * @param {} technology_id
			 */
			hide: function(technology_id) {
				jQuery('#list_' + technology_id).css('visibility', 'hidden');
			},
			
			/**
			 * Opens the tree of the subelements at the position of the
			 * value in the field with search results.
			 
			 * Gets the tree and inserts it in to the value 
			 */
			show_subelements : function(technology_id) {
				jQuery('.technology-tree-get').hide(); // hide all other open subtrees
				
				
				var techId = technology_id;
				var closeTimeout;
				

				jQuery.post(doc_root + 'includes/ajax/technology.tree.get.php', {
					id:techId
				}, function(data, status) {
					if ('success' == status) {  
						var target_elem = 'j' + techId;
						var srcObj = jQuery(data.tree_part);
						
						// on click close subtree of the element
						srcObj.bind('click', function() {
							jQuery(this).fadeOut('normal');						
						});
//										
						// close after 10 sec if no action are performed
						closeTimeout = window.setTimeout(function() {
							srcObj.fadeOut(500);
						}, 10000);
//						
//						
						// if mouse is over the divelement with the sub-tree inside closing will be
						// performed via mousout event ..
						srcObj.bind('mouseover', function() {
							// so the 10 sec timeout will be cleared
							window.clearTimeout(closeTimeout);
							
							jQuery(this).bind('mouseout', function(e) {
								// javascript interpretes an mouseover of en childelement of "this" 
								// as an mouseout from "this" element
								// this function prevents the tree-container from closing when mouse is 
								// over an child element of the tree-container
								if (reallyMouseOut(this, e)) {
									jQuery(this).fadeOut(500);
								}
							});
							
						});
//						
//						
//						// position where the tree-container will be positioned
//						var trg_position = jQuery(document.getElementById(target_elem).parentNode).offset();
						
						
//						
//						
//						
						// add onclick events on links (actually they are listelements)
						// to start a new search in this search in a new deeper Level
						srcObj.find(".subtree_link").bind('click', function(e) {
								technology_search.cloud.additional_options.add_searchvalue_sub(this.id, this.id, e); // function can be found in technology.search.js
						});
						
						srcObj.css({
							position:'absolute',
							opacity: 0.0,
							top: mouse_position.y, 
							left: mouse_position.x - 170
						});
						
						// add tree-container to body element
						jQuery('body').append(srcObj.fadeTo("slow", 1.0));

					}
				}, "json");
				
				return false;
			},
			
			/**
			 *
			 */
			add_searchvalue_sub : function(dbid, event) {
				// to avoid multiple binding of the event click each time
				// the search_result cloud is beeing generated
				jQuery(event.currentTarget).unbind("click");  
				technology_search.isolate(dbid);
			}			
		},
		
		/**
		 * loads the url of the wikipedia artikel (or whatever comes from wikipedia page)
		 * in Iframe.
		 * Iframe will be created during the replacement of the div with id "wikipedia-content" 
		 */
		load_iframe : function (wikipedia_url) {
			jQuery('#wikipedia-box').css({
				'position' : 'absolute',
				'width' : '77%'
			});
			
			jQuery('#wikipedia-box').appendTo('#mainCol');
			
			jQuery('#wikipedia-box').fadeIn();
			
			jQuery('#wikipedia-iframe').attr({src: wikipedia_url});
		}
	}
	
	
	
	
	
};

/*********************************************************************
 * No onMouseOut event if the mouse pointer hovers a child element 
 * *** Please do not remove this header. ***
 * This code is working on my IE7, IE6, FireFox, Opera and Safari
 * 
 * Usage: 
 * <div onMouseOut="fixOnMouseOut(this, event, 'JavaScript Code');"> 
 *		So many childs 
 *	</div>
 *
 * @Author Hamid Alipour Codehead @ webmaster-forums.code-head.com		
**/
function is_child_of(parent, child) {
	if( child != null ) {			
		while( child.parentNode ) {
			if( (child = child.parentNode) == parent ) {
				return true;
			}
		}
	}
	return false;
}
/*********************************************************************/

function reallyMouseOut(element, event) {
	var current_mouse_target = null;
	if( event.toElement ) {				
		current_mouse_target 			 = event.toElement;
	} else if( event.relatedTarget ) {				
		current_mouse_target 			 = event.relatedTarget;
	}
	
	return !is_child_of(element, current_mouse_target) && element != current_mouse_target 
	
	//) {
		// then mouse is out of parent element
		//eval(JavaScript_code);
	//}
}

