$(function(){
	
	// on load, hide the loadIndicator element
	$('#loadIndicator').hide();
	
	// display error if server doesn't respond
	$("#search").ajaxError(function(request, settings){
		$('#loadIndicator').hide();
		$(this).html('<div id="error">Error requesting page/service unavailable.</div>');
	});
	
 	// for the "browse index" page - when the select element changes value
	$('#browse_options').change(function(){
		$('#loadIndicator').fadeIn('fast');
		var field = $(this).attr('value');
		if( ! field ){ return false;}
		var search_text = '[*+TO+*];';// + field + '+asc';
		// call the browse_index_results url and pass in the needed params:
		$.getIfModified( 'browse_index_results', {q : search_text, start:0, rows:10000, field: field}, function(data){
			//$('#error').html('');
			// load the received html into the "search" div
			$('#search').html(data);
			// hide the load indicator
			$('#loadIndicator').fadeOut('fast');
		});
	})
	
	// for the quick search button
	$('#searchBtn').click(function(){
		$('#loadIndicator').fadeIn('fast');
		var search_text = $('#searchText').attr('value');
		$.getIfModified( 'search_results', {q : search_text, start:0, rows:10}, function(data){
			//$('#error').html('');
			$('#search').html(data);
			$('#loadIndicator').fadeOut('fast');
		});
		return false;
	})
	
	// total options for advanced search - used for unique id's on dynamically created elements
	var total_options = 1;
	
	// the boolean (and/or) items. these are set when a new search criteria option is created
	var gate_items = {};
	
	// focus the text field after selecting the field to search on
	$('#searchItemTemplate_1 select').change(function(){
		$(this).siblings('input').focus();
	})
	
	function gateTypeBtnClick(btn){
		// increment - this is really just used to created unique ids for new dom elements
		total_options++;
		
		// copy the base template
		var tpl = $('#searchItemTemplate_1').clone();
		
		// reset the id
		tpl.attr('id', 'searchItemTemplate_' + total_options);
		// reset the copied item's select element id
		$(tpl).children('select').attr('id', 'search_option_' + total_options);
		// reset the copied item's remove button id
		$(tpl).children('#removeBtn_1').attr('id', 'removeBtn_' + total_options);
		
		// focus the text field after select
		$(tpl).children('select').change(function(){
			$(this).siblings('input').focus();
		});
		
		// set up the text input
		$(tpl).children('input').each(function(){
			$(this).attr('value', '');
			$(this).attr('id', 'search_text_' + total_options);
		});
		
		// assign the handler for all gateTypeBtn elements within the new item/template
		$(tpl).children('.gateTypeBtn').click(function(){ gateTypeBtnClick($(this)); });
		
		// add a visual for describing the gate/boolean type
		tpl.prepend('<div class="gateTypeLabel">' + btn.text() + '</div>')
		
		// store in a "lookup" object
		gate_items[total_options] = btn.text();
		
		// add the new template to the dom
		$(btn).parent().after(tpl);
		
		// display the entire new template
		tpl.fadeIn('slow');
		
		// re-adjust the footer (footer is absolutely positioned)
		$('#footer').css('top', $('#advancedSearchForm').height() + 'px');
		
		// text style the remove part of the new template
		$('#removeBtn_' + total_options).before(' |&nbsp;');
		
		// make the remove button visible
		$('#removeBtn_' + total_options).css('visibility', 'visible');
		// assign the remove button click handler
		$('#removeBtn_' + total_options).click(function(){
			var id = $(this).attr('id');
			var num = id.substring(id.indexOf('_') + 1);
			// remove the gate/boolean item so the query is still valid
			delete gate_items[num];
			// fade out the entire template
			$(this).parent().fadeOut('slow', function(){ $(this).remove(); });
			// move the footer back up
			$('#footer').css('top', $('#advancedSearchForm').height() + 'px');
		});
	}
	
	// assign the gate/boolean button click handler
	$('.gateTypeBtn').click(function(){
		gateTypeBtnClick($(this));
	})
	
	// activates the advanced search action
	$('#advancedSearchSubmitBtn').click(function(){
		
		$('#loadIndicator').fadeIn('fast');
		
		var query = '';
		var sep = '';
		
		// clone the "gate_items" object
		// we want a fresh copy everytime the search button is pressed
		// just incase an item has been removed or more have been added
		var tmp_gate_items = {};
		for(i in gate_items){
			tmp_gate_items[i] = gate_items[i];
		}
		
		// loop through each ".searchItemTemplate" and build the query
		$('#advancedSearchForm .searchItemTemplate').each(function(){
			var val = $(this).children('select').attr('value');
			query += sep + val;
			query += ':' + $(this).children('input').attr('value');
			sep = ' ';
			
			// object "popping/shifting" - working with object not indexed array!
			for(i in tmp_gate_items){
				// get the first, delete it, and STOP
				query += sep + tmp_gate_items[i].toUpperCase();
				delete tmp_gate_items[i];
				break;
			}
		});
		
		// pass the query to the search_results url passing the needed url params:
		$.getIfModified( 'search_results', {q : query, start:0, rows:10}, function(data){
			//$('#error').html('');
			// push the result into the document
			$('#search').html(data);
			// hide the load indicator
			$('#loadIndicator').fadeOut('fast');
		});
		
		// cancel the default action of the submit buttton (don't want to re-direct)
		return false;
	});
	
})
