// no-op firebug emulation.
if(!window.console) { window.console = {info: function() {}, warn: function(){}, error: function(){}}};

/** 
  submitSearch - when Search button or search link are clicked
**/

function submitSearch(page) {
	if (!page) page = 1;
	gi('pge').value = page;
	

	var searchbookmark = new Array();
	searchbookmark.length = 0; //nasty bit here where array is not getting cleared on initialization
	
	var elements = new Array();
	var allelements = gi("searchform").getElementsByTagName('*');
	
	for( var x = 0; x < allelements.length; x++ ) {
		var node = allelements[x];
		
		if( node.value && node.tagName.match(/input|select/i) && node.type != 'submit' ) {
			elements.push(node);
		}
	}
	
	for (var i = 0; i < elements.length; i++) {
		var node = elements[i];
		
		// THIS MAY NOT ACCOMADATE ALL FORM INPUT TYPES, HAD TO ADD checkbox AND select-multiple
		if(node.type == 'checkbox'){
			if(node.checked){
				searchbookmark.push(node.name);
				searchbookmark.push(node.value);
			}
		} else if(node.type == 'select-multiple'){
			var options = node.options;
			for(var j = 0; j < options.length; j++){
				optionNode = options[j];
				if(optionNode.selected){
					searchbookmark.push(node.name+optionNode.value);
					searchbookmark.push(optionNode.value);
				}
			}
		} else {
			searchbookmark.push(node.name);
			searchbookmark.push(node.value);
		}
	}

	updateSearchHistory(searchbookmark.join('|'));
	return false;
}

/** 
  updateSearchHistory updates top.location.hash to include search bookmark
**/

function updateSearchHistory(searchbookmark) {
	try {
		var currentsearch = YAHOO.util.History.getCurrentState("srch");
		if (searchbookmark != currentsearch) YAHOO.util.History.navigate("srch", unescape(searchbookmark));

	} catch(e) {
		warn('Could not update history for search: '+ e);
	}
}

/**
   showSearchResults will fill in the appropriate search results div
  */
function showSearchResults(searchbookmark) {
	// if there's no div to display results, get out
	var searchnode = gi('searchdisplay');
	if (!searchnode) return false;

	// if there are elements in the bookmark array
	if (searchbookmark) {
		var bookmarkarray = searchbookmark.split("|");
		
		document.body.style.cursor = "wait";
		var anchors = document.body.getElementsByTagName("a"); 
		for (var i = 0; i < anchors.length; i++) { 
			anchors[i].style.cursor = "wait"; 
		}

		var callback = { 
				success: function(content) {
					searchnode.innerHTML = content.responseText;

					document.body.style.cursor = "default";
					for (var i = 0; i < anchors.length; i++) { 
						anchors[i].style.cursor = "pointer"; 
					}
				},

				failure: function(e) { 
					searchnode.innerHTML = 'Failed to retrieve search results';
					document.body.style.cursor = "default";
					for (var i = 0; i < anchors.length; i++) { 
						anchors[i].style.cursor = "pointer"; 
					}
				}
		};

		// assign any value that's not assigned in case the form was not submitted but url was simply loaded with bookmark
		// i.e. if (gi('pge')) gi('pge').value = bookmark;
		for(var i = 0; i < bookmarkarray.length; i=i+2) {
			var node = gi(bookmarkarray[i]);
			if (node) {
				node.value = bookmarkarray[i+1];
				if(node.type == 'checkbox') {
					node.checked = 'checked';
				} else if(node.nodeName == 'OPTION') {
					node.setAttribute('selected', 'true');
					var temp = node.id;
					var filtername = temp.replace(node.value, '');
					if(gi(filtername+'any') && node.id != filtername+'any'){
						gi(filtername+'any').selected = '';
						gi(filtername+'any').removeAttribute('selected');
					}
				}
			}
    		}
    	
		// get form elements before we async call the search url
		var elements = document.forms[0].elements;
		var queryComponents = new Array();

		for (var i = 0; i < elements.length; i++) {
			var node = elements[i];

			// THIS MAY NOT ACCOMADATE ALL FORM INPUT TYPES, HAD TO ADD checkbox AND select-multiple
			if(node.type && node.type == 'checkbox'){
				if(node.checked){
					queryComponents.push(node.name+'='+node.value);
				}
			} else if(node.type && node.type == 'select-multiple'){
				var options = node.options;
				for(var j = 0; j < options.length; j++){
					optionNode = options[j];
					if(optionNode.selected){
						queryComponents.push(node.name+optionNode.value+'=1');
					}
				}
			} else {
				queryComponents.push(node.name+'='+node.value);
			}
		}

		queryComponents.push('excludecontenttype=1');

		var searchurl = '../htsearch.cgi?'+queryComponents.join('&');
		YAHOO.util.Connect.asyncRequest('GET', searchurl, callback);

		updateSearchHistory(searchbookmark);

	} else {
		searchnode.innerHTML = '';
	}

	return false;
}

function parseBookmark() {
	// Remove the hash if any
	var bookmark = window.location.href;
	var idx = bookmark.lastIndexOf("#");

	if (idx >= 0) {
		var hashstring = bookmark.substr(idx + 1);
		var hashparams = hashstring.split("&");

		for (i = 0, len = hashparams.length; i < len; i++) {
			var tokens = hashparams[i].split("=");
			if (tokens.length >= 2) {
				if (tokens[0] == 'srch') return unescape(tokens[1]); // srch=[pagenumber]|[method]|[words]|... etc
			}
		}
	}

	return '';
}

YAHOO.util.Event.onDOMReady(function () {
	var searchbookmark = YAHOO.util.History.getBookmarkedState("srch")||'';
	YAHOO.util.History.register("srch", searchbookmark, function (state) {
		if (state) showSearchResults(state);
	});

	try {		
		// Initialize browser history management library.
		YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");

		var searchbookmark = parseBookmark();
		if (searchbookmark) showSearchResults(searchbookmark);

	} catch (e) {
		// The only exception that gets thrown is when the browser is not supported (Opera, or not A-grade). Back button won't work.
		console.log ('Failed to show search results: '+e);
		//warn('Failed to show search results: '+ e);
	}
});

