/*
 * All java script logic for the search suggestions.
 *
 * The code relies on the MooTools JS library to
 * be also loaded.
 *
 * Creates an app object
 */
 
var testing;
var divs ;
var app = {
		util : {
		// disables browser auto completion for the given element
		disableAutoComplete : function(elemId) {
			$(elemId).set("autocomplete", "off");
		},

		// trims a prefix from a given string, this can be used to trim
		// a certain prefix from DOM element IDs for further processing on the ID
		trimPrefix : function(str, prefix) {
			return str.substring(prefix.length);
		},

		// appends the parameter with the given name and
		// value to the given url and returns the changed url
		appendParamToURL : function(url, name, value) {
			var c = "?";
			if(url.indexOf(c) != -1) {
				c = "&";
			}
			return url + c + name + "=" + encodeURIComponent(value);
		},

		// dynamically loads a CSS file
		loadCSSFile : function(url) {
			var elem = document.createElement("link");
			elem.setAttribute("rel", "stylesheet");
			elem.setAttribute("type", "text/css");
			elem.setAttribute("href", url);

			if(typeof elem != "undefined") {
				document.getElementsByTagName("head")[0].appendChild(elem);
				app.util.loadedCSSFiles.push(url);
			}
		},

		// array to keep track of the dynamically loaded CSS files
		loadedCSSFiles : [],

		// removes all dynamically loaded CSS files
		clearDynamicCSS : function() {
			for(var i=0; i<app.util.loadedCSSFiles.length; i++) {
				app.util.unloadCSSFile(app.util.loadedCSSFiles[i]);
			}
		},

		// dynamically unloads a CSS file
		unloadCSSFile : function(url) {
			var candidates = document.getElementsByTagName("link");
			for(var i=candidates.length; i>=0; i--) {
				if(candidates[i] && candidates[i].getAttribute("href") != null && candidates[i].getAttribute("href").indexOf(url) != -1) {
					candidates[i].parentNode.removeChild(candidates[i]);
				}
			}
		},

		// checks if cookies are enabled
		cookiesEnabled : function() {
			var currentCookie = document.cookie;
			document.cookie = "Enabled=true";
			var cookieValid = document.cookie;
			var result = false;

			if(cookieValid.indexOf("Enabled=true") != -1) {
				result = true;
			}

			document.cookie = currentCookie;
			return result;
		}
	},
	searchsuggest : {
			// configuration parameters and required object instances
			acListTotal   :  0,
			acListCurrent : -1,
			acDelay       : 300,
			acURL         : null,
			acFormId      : null,
			acSearchId	  : null,
			acResultsId	  : null,
			acSearchField : null,
			acResultsDiv  : null,
			fieldDefault  : null,
			submitId	  : null,
			
			init : function(formId, fieldId, submitId, fieldDefault, resultsId, url) {
				// initialize vars
				app.searchsuggest.acFormId = formId;
				app.searchsuggest.acSearchId = fieldId;
				app.searchsuggest.acResultsId = resultsId;
				app.searchsuggest.acURL = url;
				app.searchsuggest.fieldDefault = fieldDefault;
				app.searchsuggest.submitId = submitId;
				
				// disable browser auto comlete
				app.util.disableAutoComplete(fieldId);
				
				// create the results div
				var div = new Element('div', {'id' : resultsId});
				//div.inject($(document.body), 'top');
				document.body.appendChild(div);
				//jQuery("body").append("<div id=\"" + resultsId + "\"></div>");
			
				// register mostly used vars (jQuery object)
				app.searchsuggest.acSearchField = $(app.searchsuggest.acSearchId);
				app.searchsuggest.acResultsDiv = $(app.searchsuggest.acResultsId);
			
				// reposition div
				app.searchsuggest.repositionResultsDiv();
			
				// on blur listener
				app.searchsuggest.acSearchField.blur(function(){ setTimeout("app.searchsuggest.clear()", 200) });
			
				// on key up listener
				app.searchsuggest.acSearchField.addEvent( 'keydown', function( e ){
					// get keyCode (window.event is for IE)
					var keyCode = e.code;
					var lastVal = app.searchsuggest.acSearchField.value;
					// check an treat up and down arrows
					if(app.searchsuggest.updownArrow(keyCode)){
						return;
					}
					// check for an ENTER or ESC
					if(keyCode == 27) {
						app.searchsuggest.clear();
						return;
					}
					
					// if is text, call with delay
					setTimeout(function() { app.searchsuggest.suggest(lastVal) }, app.searchsuggest.acDelay);
				});
								
				// on focus listener (clear default value)
				app.searchsuggest.acSearchField.addEvent( 'focus', function() {
					var val = app.searchsuggest.acSearchField.value;
					if(val == app.searchsuggest.fieldDefault)
					{
						app.searchsuggest.acSearchField.value = '';
					}
				});
				
				// on submit we do not submit the form, but change the window location
				// in order to avoid https to http warnings in the browser
				$(app.searchsuggest.acFormId).addEvent( 'submit', function() {
					var searchUrl = $(app.searchsuggest.acFormId).attr("action");
					var searchTerm = app.searchsuggest.acSearchField.value;
					window.location = app.util.appendParamToURL(searchUrl, "q", searchTerm);
					return false;
				});
			},
			
			// trigger suggest action
			suggest : function(lastValue)
			{
				// get the field value
				var part = app.searchsuggest.acSearchField.value;
			
				// if it's empty clear the resuts box and return
				if(part == "") {
					app.searchsuggest.clear();
					return;
				}
			
				// if it's equal the value from the time of the call, allow
				if(lastValue == part) {
					return;
				}
				
				// build the request url
				var reqUrl = app.util.appendParamToURL(app.searchsuggest.acURL, "q", part);
				
				// get remote data as JSON
				var jsonRequest = new Request.JSON({url: reqUrl, onSuccess: function(json){
						// get the total of results
					
					var ansLength = app.searchsuggest.acListTotal = json.suggestions.length;
			
					// if there are results populate the results div
					if(ansLength > 0) {
					
					var newData = "";
						// create a div for each result
						for(i=0; i < ansLength; i++) {
							newData += "<div class=\"unselected\" id=\"suggestionsdiv" + i + "\"><p class=\"suggestionterm\">" + json.suggestions[i].suggestion + "</p>";
							newData += "<span class=\"hits\">" + json.suggestions[i].hits + "</span><div style=\"clear: both;\"></div></div>";
						}
						// update the results div
						app.searchsuggest.acResultsDiv.innerHTML = newData;
						app.searchsuggest.acResultsDiv.setStyle("display","block");
						
						// for all divs in results
						divs = $(app.searchsuggest.acResultsId).getElements("div");
						
						// on mouse over clean previous selected and set a new one
						divs.addEvent("mouseover", function() {
							this.className = "selected";
						});
						
						divs.addEvent("mouseout", function() {
							this.className = "unselected";
						});
						
						// on click copy suggestion to search field, hide the list and submit the search
						divs.addEvent("click", function() {
							app.searchsuggest.acSearchField.value = this.childNodes[0].innerHTML;
							app.searchsuggest.clear();
							$(app.searchsuggest.submitId).click();
							//$(app.searchsuggest.acFormId).submit();
						});
					} else {
						app.searchsuggest.clear();
					}
				}}).get();				
			},

			// clear suggestions
			clear : function()
			{
				app.searchsuggest.acResultsDiv.innerHTML = "";
				app.searchsuggest.acResultsDiv.setStyle("display","none");
			},
			
			// reposition the results div accordingly to the search field
			repositionResultsDiv : function()
			{
				// get the input position
				var inPos = app.searchsuggest.acSearchField.getOffsets();
				var inTop = inPos.y;
				var inLeft = inPos.x;
				
				// get the field size
				var inHeight = app.searchsuggest.acSearchField.getHeight();
				var inWidth = app.searchsuggest.acSearchField.getWidth();
				
				// apply the css styles
				app.searchsuggest.acResultsDiv.addClass("suggestions");
				app.searchsuggest.acResultsDiv.setStyle("position","absolute");
				app.searchsuggest.acResultsDiv.setStyle("left", inLeft); // to tweak
				app.searchsuggest.acResultsDiv.setStyle("top", inTop + inHeight);
				app.searchsuggest.acResultsDiv.setStyle("width", inWidth + 53); // to tweak
				app.searchsuggest.acResultsDiv.setStyle("z-index", "7777");
			},
			
			// treat up and down key strokes defining the next selected element
			updownArrow : function(keyCode) {
				if(keyCode == 40 || keyCode == 38) {
					if(keyCode == 38) { // keyUp
						if(app.searchsuggest.acListCurrent == 0 || app.searchsuggest.acListCurrent == -1) {
							app.searchsuggest.acListCurrent = app.searchsuggest.acListTotal-1;
						} else {
							app.searchsuggest.acListCurrent--;
						}
					} else { // keyDown
						if(app.searchsuggest.acListCurrent == app.searchsuggest.acListTotal-1) {
							app.searchsuggest.acListCurrent = 0;
						} else {
							app.searchsuggest.acListCurrent++;
						}
					}
					
					// loop through each result div applying the correct style
					for (var i = 0; i < app.searchsuggest.acListTotal; i ++) {
						$("suggestionsdiv" + i).className = "unselected";
					}
					$("suggestionsdiv" + app.searchsuggest.acListCurrent).className = "selected";
					app.searchsuggest.acSearchField.value = $("suggestionsdiv" + app.searchsuggest.acListCurrent).childNodes[0].innerHTML;
					return true;
				} else {
					// reset
					app.searchsuggest.acListCurrent = -1;
					return false;
				}
			}
		} // end searchsuggest
	};
