/**
 * Modified by Rommil Santiago to merge with Google Custom Search on concordia.ca
 *
 * Added:
 * - Default action for enter if no site selected
 * - Site link affordances
 * - ESC case
 * - IE6 and IE7 Styles
 * 
 *
 * Copyright (c) White Whale Web Services (http://www.whitewhale.net/)
 * but free for any use, with or without modification
 *
 * Version 1.0 (2008-06-03)
 *
 * Usage: $('.inputselector').quickaccess(settingsObject);
 * 	where .inputselector selects the container for the search input (preferred for friendliness to non-JS clients) OR the search input itself
 *	settingsObject may contain
 *  selector : the selector for the links that are to be searched (i.e. '#linkslist a' or 'a.quickaccess')
 *  results : the container in which the results will be placed (default:they'll be placed in a #qa_results created immediately after the search box)
 *	onSubmit : callback function for when the user hits the enter/return key; by default, this will take them to the selected link
 *  maxResults : the maximum number of results to show at any one time
 *  tooMany : the message to show when there are more matching results than maxResults (default: 'Keep typing...')
 *  noneFound : the message to show when no results are found
 *  topMatch : a message to be prepended to the top matching element (i.e. 'Top Match: ')
 *  focus : true/false; should the search element grab focus upon initialization?
 *
 * Example: $('#quicksearch').quickaccess({selector:'#offices li a', maxResults:10,noneFound:'Sorry, no matching links were found.');
 **/

var firstdown = true;
var searchtabcookie = readCookie('searchtab');
var host_name = window.location.hostname;
if(window.location.hostname === "concordia.ca")
	var host_name = "www." + host_name;
	
function livesearch_init(){

	var stylesheet_success = false;

	// Turn off autocomplete
	if (document.getElementById("search_toplevel_query")){
		$("#search_toplevel_query").attr('autocomplete','off');
	}
	
	// Attach the styles
	
	if(document.createStyleSheet) {	
		var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
		var gteIE7 = false /*@cc_on || @_jscript_version >= 5.7 @*/;

		stylesheet_success = document.createStyleSheet('http://'+host_name+'/globalmk/stylesheets/livesearch.css');
	
		if (gteIE7){
			stylesheet_success = document.createStyleSheet('http://'+host_name+'/globalmk/stylesheets/livesearch_ie7.css');
		}else if (IE6){
			stylesheet_success = document.createStyleSheet('http://'+host_name+'/globalmk/stylesheets/livesearch_ie6.css');
		}
	} else {
		var smartsearch_css = "@import url('http://"+host_name+"/globalmk/stylesheets/livesearch.css');";
		var new_smartsearch_css = document.createElement('link');
		new_smartsearch_css.rel='stylesheet';
		new_smartsearch_css.href='data:text/css,' + escape(smartsearch_css);
		document.getElementsByTagName("head")[0].appendChild(new_smartsearch_css);
	}
	
}


(function($){
	$.fn.extend({
		quickaccess  :   function(s) {
			// initialize the settings with their defaults
			s = $.extend({
					selector			: 'a.qa',
					results				: null,
					onSubmit			: function() { 
												if($('.qa_selected').length){
													var destination = $('.qa_selected').eq(0).find('a').attr('href');
													if (document.location = destination){
														var deleteit = document.getElementById("page");
														deleteit.innerHTML = ''; // destroy the search to prevent default behaviour in FF/Mac and Opera/Mac ?!
														document.location = destination;
													}											
												}else{
												
												}
										  return false;
										  },
					maxResults			: 8,
					tooMany				: 'Too many site suggestions, please be more specific.',
					noneFound			: 'No suggested sites available, please press \'Search\'.',
					topMatch			: null,
					focus				: false
				},s);
			
			qa = { };

			if(this.is('input[type=text],textarea')){
				qa.search=this; // if the specified item is an input element, use it
			}else{ 
				qa.search = this.prepend('<input type="text" id="qa_search_query"/>').children().eq(0); // otherwise, add an input inside of it
			}
			if(s.results){
				qa.results=$(s.results).eq(0); // select the specified container
			}else if (!$('#qa_results').length){
				tempholder = qa.search.after('<div id="qa_results"></div>'); // otherwise, create a new container
			}

			qa.results = tempholder.next();
			if (!$('#qa_results_list').length){
				qa.results.append('<ul id="qa_results_list"><li></li></ul>'); // append results list to results div
			}
			
			qa.results_list = qa.results.find('ul#qa_results_list'); // results list is the ul we just added
		
			
			//if(s.focus) qa.search.focus(); // put cursor in search box
			
			qa.matches = qa.links =  $(s.selector).each(function() { $.data(this,'keywords',(this.innerHTML).toLowerCase().replace(/[,-\/]/g,' ').replace(/[^a-zA-Z 0-9]+/g,'')); });// grab links, attach data to match against
			
			qa.search.attr('autocomplete','off').keyup(function() { // on each keypress, filter the links
			

				var query = $.trim($(this).val().toLowerCase().replace(/[,\-\/\s]+/g,' ').replace(/[^a-zA-Z 0-9\.]+/g,'')),subquery; // grab query, sanitize it
							
				
				if(query==qa.lastquery) return; // do nothing if the query is unchanged
				if(!query.length || (query =='enter your query here') || (query =='saisir la recherche')) {
					qa.results_list.html('<li></li>');
					qa.results.addClass('qa_noquery');
					return;
				} else{
					qa.results.removeClass('qa_noquery');

				}
				if(query.indexOf(qa.lastquery)!=0) {  // if this query is NOT a subset of the last query, reinitialize the matches and search on all terms
					qa.matches = qa.links;
					subquery = query;
					if (!firstdown)
						firstdown = true;
				} else{ 
					subquery = query.substring(query.lastIndexOf(' ')+1,query.length); // otherwise, since this query IS a subset of the last query, no need to search the last query's terms
					if (!firstdown)
						firstdown = true;
				}
				if(query.length==0) { qa.lastquery=''; firstdown = true; return; } // return no results if there is no query
				qa.lastquery=query;
				$.each(subquery.split(' '),function() { // filter the result for each word in the query
					var search = this;
					qa.matches = qa.matches.filter(function() { return (' ' + $.data(this,'keywords')).indexOf(' ' + search)>=0; });
				});
				qa.results_list.empty();
				if(qa.matches.length>s.maxResults){
					qa.results_list.html('<li>'+s.tooMany+'</li>').parent().addClass('qa_toomany'); // if there are too many matches
					firstdown = false;
				}else if(!qa.matches.length){
					qa.results_list.html('<li>'+s.noneFound+'</li>').parent().addClass('qa_nonefound'); // if there are no matches
					firstdown = false;
				}else { // if the matches are just right
					var query_exp = new RegExp('(\\b' + query.replace(/\s/g,'|\\b') +')','ig'); // for highlighting the query terms
					$.each(qa.matches,function() { 
						var setclass;
						if (!$(this).hasClass('az')){
							setclass = ' class="local"';
						}else{
							setclass = '';
						}
						if ((document.getElementById('search_option_list').className != 'li_staff') && (searchtabcookie != 'li_staff')){
							var coords = '';
							if ($(this).attr("title") != ''){
								coords = '<span class="coords">'+$(this).attr("title")+'</span><br />';
							}
							qa.results_list.append('<li' + setclass + '><a href="'+$(this).attr('href')+'" title="Visit this site"><span class="suggestedsite">'+(' ' + $(this).text()).replace(query_exp,'<span class="qa_highlight">$1</span>')+'</span><br/>'+coords+'<span class="suggestedURL">'+linewrap($(this).attr('href'),60)+'</span></a></li>');
						}else{
							qa.results_list.append('<li' + setclass + '><a href="'+$(this).attr('href')+'" title="Visit this site"><span class="suggestedsite">'+(' ' + $(this).text()).replace(query_exp,'<span class="qa_highlight">$1</span>')+'</span><br/><span class="suggestedURL">View this website</span></a></li>');
						}
						}); // list the match, with highlighting
					qa.results.removeClass('qa_toomany').removeClass('qa_nonefound');
					
				}
			}).keydown(function(event) { // capture special keys on keydown
			
			
				switch(event.keyCode) {
					case 38: // up arrow
						event.preventDefault();
						qa.results_list.find('.qa_selected').removeClass('qa_selected').each(function() {
							if($(this).prev().length) $(this).prev().addClass('qa_selected');
							else qa.results_list.find('li:last-child').addClass('qa_selected');
						});					
						break;
					case 40: // down arrow
						event.preventDefault();
							if (firstdown){
								qa.results_list.children().eq(0).attr('id','qa_topmatch').attr('class','qa_selected').prepend(s.topMatch);
							firstdown = false;}
						else
						qa.results_list.find('.qa_selected').removeClass('qa_selected').each(function() {
							if($(this).next().length){
								$(this).next().addClass('qa_selected');
							}else 
								qa.results_list.children().eq(0).addClass('qa_selected');
						});
						break;
					case 13: // enter/return						
					
						if ($('.qa_selected').length){
							event.preventDefault();
							s.onSubmit();
							return false;
						}
						break;
					case 27: // Esc
						qa.results.addClass('qa_noquery');
					break;
				}
			});
			
			qa.search.keyup(); // run search in case field is pre-populated (e.g. in Firefox)
		}
	});

})(jQuery);

/**
* @param {String} string - the string to wrap
* @param {Integer} length - line length to wrap to
* @return {String} the wrapped string
*/
function linewrap(string, length)
{
	if (string.length > length){
	var num_wraps = Math.floor(string.length / length);
	
	var temp_string = new String();
	var start, end;
	
	for (var i=0; i<num_wraps; i++){
	start = i*length;
	end = start + length;
	
	temp_string += string.substring(start, end) + '<br>';
	}
	start = length*num_wraps;
	end = start + (string.length % length);
	return temp_string + string.substring(start, end);
	}
	else
	return string;
}

function togglesmartsearch(){
	// Interact with Smart Search

	firstdown = false;


	if (( typeof( window[ 'qa' ] ) != "undefined" ) && (document.getElementById("search_toplevel_query"))){
		
		// If Staff and Faculty - remove event handler
		
		if (document.getElementById('search_option_list').className == 'li_staff'){
			
			$("#qa_results").remove(); // hide directory
			
			$("#search_toplevel_query").unbind();
			movelisting();
			
			
			if (($("#search_toplevel_query")[0].value.toLowerCase()) != 'enter your query here' && ($("#search_toplevel_query")[0].value.toLowerCase()) != 'saisir la recherche')
				lookup($("#search_toplevel_query")[0].value);
			
			$('#search_toplevel_query').keyup(function(event) { // capture special keys on keydown			
			
				switch(event.keyCode) {
					case 38: // up arrow
						event.preventDefault();
						$("#staff_results_list").find('.qa_selected').removeClass('qa_selected').each(function() {
							if($(this).prev().length) $(this).prev().addClass('qa_selected');
							else $("#staff_results_list").find('li:last-child').addClass('qa_selected');
						});	
						break;
					case 40: // down arrow
						event.preventDefault();
							if (firstdown){
								$("#staff_results_list").children().eq(0).attr('id','qa_topmatch').attr('class','qa_selected');
								firstdown = false;
							}
						else
						$("#staff_results_list").find('.qa_selected').removeClass('qa_selected').each(function() {
							if($(this).next().length){
								$(this).next().addClass('qa_selected');
							}else 
								$("#staff_results_list").children().eq(0).addClass('qa_selected');
						});
						break;
					case 13: // enter/return
										
						if ($('.qa_selected').length){
							event.preventDefault();			
							var destination = $('.qa_selected').eq(0).find('a').attr('href');
							document.location = destination;
							return false;
						}
						break;
					case 27: // Esc
						$("#staff_results").addClass('qa_noquery');
					break;
					default: // rest
						lookup_timer_flag = true;
						lookup($("#search_toplevel_query")[0].value);
					break;
					
				}
			});
			
			//qa.search.focus(); // put cursor in search box
		
			
			
		}else if ((document.getElementById('search_option_list').className == 'li_thissite') || document.getElementById('search_option_list').className == 'li_entire'){
			//alert("here");
			// qa defined, but not staff tab
			$("#staff_results").remove(); // hide directory
			qa.results.addClass('qa_noquery'); // hide directory
			$("#search_toplevel_query").unbind();
			movelisting();
			$('#search_toplevel_query').quickaccess({selector:'#search_listing a'});
		}else{
			$("#staff_results").remove(); // hide directory
			qa.results.addClass('qa_noquery'); // hide directory
			$("#qa_results").remove(); // hide directory
		
			$("#search_toplevel_query").unbind();
			movelisting();
		} // else


	}else{
		// qa not defined or search not existant
		
	}
	

}


function movelisting(){

	if (( typeof( window[ 'qa' ] ) != "undefined" ) && (document.getElementById("search_toplevel_query"))){
	
		if (document.getElementById('search_option_list').className == 'li_entire'){ // Make All of Concordia active
			$("#local_site_list").appendTo("#search_listing");
			$("#az_site_list").appendTo("#search_listing");
			$("#search_staff_directory").appendTo("#search_listing_disabled");
		}else if (document.getElementById('search_option_list').className == 'li_thissite'){ // Make Dept or Group active
			$("#local_site_list").appendTo("#search_listing");
			$("#az_site_list").appendTo("#search_listing_disabled");
			$("#search_staff_directory").appendTo("#search_listing_disabled");
		}
		/*
		else if (document.getElementById('search_option_list').className == 'li_staff'){ // Make Staff and directory active
			alert('here');
			$("#az_site_list").appendTo("#search_listing_disabled");
			$("#local_site_list").appendTo("#search_listing_disabled");
			$("#search_staff_directory").appendTo("#search_listing");
		}
		else
		{
			$("#search_staff_directory").appendTo("#search_listing_disabled");
			$("#local_site_list").appendTo("#search_listing_disabled");
			$("#az_site_list").appendTo("#search_listing_disabled");
		}
		*/
	}
}

// Staff and Faculty Directory

var lookup_url;

function staffDirectory(url){
	baseURL = '';
	lookup_url = url + '/scripts/smartsearch_ajax.php';
}


var lookup_timer;
var lookup_timer_flag = true;


function lookup(inputString) {
	
	var matches;
	var links;	
	
	window.clearTimeout(lookup_timer);
	//alert("timer set");
	
	inputString = $.trim(inputString.toLowerCase().replace(/[,\-\/\s]+/g,' ').replace(/[^a-zA-Z 0-9\.]+/g,'')); // grab query, sanitize it
		
	if ($("#staff_results").length == 0){
		$("#search_toplevel_query").after('<div id="staff_results"><ul id="staff_results_list"></ul></div>');
	}
		
	var query_url = lookup_url + '?lastname=' + removeSpaces(inputString);
	
	if((inputString.length != 0) && (inputString.toLowerCase() != 'enter your query here') && (inputString.toLowerCase() != 'saisir la recherche')) {
			$("#search_staff_directory").load(query_url, function(){
			$("#staff_results").removeClass('qa_noquery');
					
			matches = links =  $("#search_staff_directory a").each(function() { $.data(this,'keywords',(this.innerHTML).toLowerCase().replace(/[,-\/]/g,' ').replace(/[^a-zA-Z 0-9]+/g,'')).replace(/ext./,''); });// grab links, attach data to match against
			
			$("#staff_results_list").empty();
			
			if(matches.length > 10){
					$("#staff_results_list").html('<li>Too many matches, please be more specific</li>'); // if there are too many matches
					firstdown = false;
			}else if(!matches.length){
					$("#staff_results_list").html('<li>No matches found.<br /> Please press \'Search\' to try an advanced search.</li>'); // if there are no matches
					firstdown = false;
			}else {// if the matches are just right
					firstdown = true;
			
					var staff_query_exp = new RegExp('(\\b' + inputString.replace(/\s/g,'|\\b') +')','ig'); // for highlighting the query terms
					
					$.each(matches,function() { 
					var setclass;
					if (!$(this).hasClass('az')){
						setclass = ' class="local"';
					}else{
						setclass = '';
					}
					$("#staff_results_list").append('<li' + setclass + '><a href="'+$(this).attr('href')+'" title="'+ $(this).attr('rel') +'"><span class="suggestedsite">'+(' ' + $(this).text()).replace(staff_query_exp,'<span class="qa_highlight">$1</span>')+'</span><br/><span class="suggestedURL">View this person\'s contact page</span></a></li>');

				}); // list the match, with highlighting
			}
		
		});	
			

	
	} else {
		$("#staff_results").addClass('qa_noquery');

	}// if
	
	lookup_timer = window.setTimeout(function(){
		if (lookup_timer_flag){
			lookup ($("#search_toplevel_query")[0].value);
			lookup_timer_flag = false;
		}else{
			window.clearTimeout(lookup_timer);
		}
	} , 500);
	
} // lookup

function removeSpaces(string) {
	var tstring = "";
	var i;
	var splitstring;
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
	tstring = tstring + splitstring[i] + '@@';
	return tstring;
}