/* Search box collection selector
 * -----------------
 * Note: Multiple functions spliced together.
 * Need to go through the code and remove redundancy/cleanup/optimise.
 */

$(document).ready(function() {
	//Prepare the search collection selector styles/HTML
	$('#searchButton', $('#searchSite')).before('<div id="searchCollectionButton" class="hover active"/>');
	$('#searchSite', $('#tools')).addClass('js').append('<ul id="selector"/><div id="searchInfo"/>');
	$('#tools', $('#header')).addClass('js');
	
	//Set variables for core elements
	iSelector = $('#selector', $('#searchSite'));
	iQuery = $('#searchQuery', $('#searchSite'));
	iInfo = $('#searchInfo', $('#searchSite'));
	
	//Hide the default select dropdown, labels and search information
	$('#searchInfo, #selector', $('#searchSite')).hide();
	$('#searchCollection, label', $('#searchSite')).addClass('hidden');
	hideCollection();
	
	//Disable the Query input's browser autocomplete
	$(iQuery).attr('autocomplete','off');
	
	//Populate array and drop down with search collection options
	var n = $('#searchCollection option').length;
	choices = new Array (n);
	var i=0;
	for (i=0;i<n;i++) {
		choices[i] = $('#searchCollection option:nth-child(' + (i+1) + ')').text();
		$(iSelector).append("<li>Search " + choices[i] + "</li>");
	}
	
	//Set the initial input text
	chooseCollection();
	
	//Draw search information prompt
	var widthInput = $(iQuery).innerWidth();
	var widthSelector = $('#searchCollectionButton', $('#searchSite')).innerWidth();
	var widthNewSelector = widthInput + widthSelector - 1;
	var widthNewsearchInfo = widthInput + widthSelector - 8;
		//get correct widths for IE6
		if (($.browser.msie) && ($.browser.version.substr(0,1) < 7)) {
			widthInput = $(iQuery).innerWidth();
			widthSelector = $('#searchCollectionButton', $('#searchSite')).innerWidth();
			widthNewSelector = widthInput + widthSelector + 1;
			widthNewsearchInfo = widthInput + widthSelector + 2;
		}
	$(iInfo).width(widthNewsearchInfo);
	$(iSelector).width(widthNewSelector);

	//Syncs up the text input box with the hidden select input
	$('#searchCollection', $('#searchSite')).change(function() {
		chooseCollection();
	});
	
	//Select the search input, ready for typing
	$(iQuery).focus(function() {
		$(this).addClass('focus');
		$('#searchCollectionButton, #searchSite.js div.wrap').addClass('focus');
		
		if (checkValues()) {
			var text = $(this).val();
			$(iInfo).fadeIn('fast');
			$(this).val('').css('color','#000');
		} else {
			$(iInfo).fadeIn('fast');
			$(this).select();
		}
	}).blur(function() {
		$(this).removeClass('focus');
		 $('#searchCollectionButton, #searchSite.js div.wrap').removeClass('focus');
		
		 if ($(this).val() == "") {
			$(iInfo).fadeOut('fast');
			chooseCollection();
		}
	});
	
	//Hide the dropdown menu when clicking outside
	$(document).click(function(){
		hideCollection();
	});
	
	//Show the dropdown menu
	$('#searchCollectionButton').click(function(e){
		e.stopPropagation();
		if ($('#searchCollectionButton').hasClass('active')) {
			hideCollection();
		} else {
			$('#searchCollectionButton').addClass('active');
			$(iInfo).fadeOut('fast');
			$(iSelector).fadeIn(function(){if(jQuery.browser.msie)this.style.removeAttribute('filter');});
		}
	});
	
	//hover over option (to work in conjunction with keyboard selection)
	$('li', iSelector).hover(function() {
		$('li', iSelector).removeClass('selected');
		$(this).addClass('selected');
	});
	
	//Select an option from the dropdown
	$('li', iSelector).click(function() {
		selectItem();
	});
	
	//Add :active state to search button click
	$('#searchButton', $('#searchSite.js')).mousedown(function() {
			$(this).addClass('active');
		}).mouseup(function() {
		 	$(this).removeClass('active');
	});
	
	//Give collection selector :hover in IE6
	if (($.browser.msie) && ($.browser.version.substr(0,1) < 7)) {
		$('#searchCollectionButton, #searchButton', $('#searchSite.js')).hover(function() {
			$(this).addClass('hover');
		}, function() { 
			$(this).removeClass('hover');
		});
	}
	
	//Detect arrow key press in query input (keydown() needed for Chrome/Safari)
	$(iQuery).keydown(function(e) {
    switch (e.keyCode) {
        case 40:
			//down arrow press
			showSelector(1);
			break;
		case 38:
            //up arrow press
			showSelector(-1);
			break;
        default:
			break;
        }      
	});
	
	//Detect enter key press in query input/dropdown (keypress() needed for Opera)
	$(iQuery).keypress(function(e) {
    switch (e.keyCode) {
		case 13:
            //enter press
			if (($('#searchCollectionButton').hasClass('active')) && ($('li', iSelector).hasClass('selected'))) {
				selectItem();
				return false;
			}
			break;
        default:
			break;
        }      
	});
	
});

/* ---------------------------------------------------------------
 * Functions
 */

//Show collection selector via keyboard
//This function needs to be simplified to reduce duplicate code
function showSelector(action) {
	var collection = $('#searchCollection :selected').text();
	var items = $('li', iSelector).length;
	var itemSelected = $('li', iSelector).index($('li.selected', iSelector));
	
	if ($('#searchCollectionButton').hasClass('active')) {
		if ((itemSelected <= (items - 1)) && (itemSelected > -1)) {
			 if (action == -1) {
				 if (itemSelected > 0) {
					itemSelected = itemSelected + action;
				 } else {
					 itemSelected = items - 1; 
				 }
			 } else {
				if (itemSelected < (items - 1)) {
					itemSelected = itemSelected + action;
				 } else {
					 itemSelected = 0; 
				 }
			 }
		} else {
			itemSelected = 0;
		}
	} else {
			$('#searchCollectionButton').addClass('active');
			itemSelected = $('li', iSelector).index($('li:contains('+ collection + ')', iSelector));
			$(iInfo).fadeOut('fast');
			$(iSelector).fadeIn(function(){if(jQuery.browser.msie)this.style.removeAttribute('filter');});
	}
	
	$('li', iSelector).removeClass('selected').eq(itemSelected).addClass('selected');
}

//Select item from dropdown
function selectItem() {
	var index = $('li', iSelector).index($('li.selected', iSelector));
	$('#searchCollection option').eq(index).attr('selected', 'selected');
	hideCollection();
	chooseCollection();
	$(iQuery).focus();	
}

//Adds the currently selected collection to the default input text
function chooseCollection() {
	var collection = $('#searchCollection :selected').text();
	var caption = 'Searching ' + collection;
	if (checkValues()) {
		$(iQuery).val(collection).css('color','#999').attr('title',caption);
		$(iInfo).html(caption);
	} else {
		$(iQuery).attr('title',caption).select();
		$(iInfo).html(caption).fadeIn('fast');
	}
}

//Checks to see if the current text input matches an item in the array or is blank
function checkValues() {
	var found = false;
	var toolsquery = $(iQuery).val();
	var i=0;
	for (i=0;i<choices.length;i++) {
		if ((toolsquery == "") || (toolsquery == choices[i])) {
			found = true;
			break;
		}
	}
	return found;
}

function hideCollection() {
	$(iSelector).fadeOut();
	$('#searchCollectionButton').removeClass('active').removeClass('hover');
}