function submitQueryFormByAutoCompleter()
{
	clearHiddenFormFields();
//	getExpandedCollection();
	return true;
}

function submitQueryForm()
{
	clearHiddenFormFields();
	submitForm('queryform');
}

function clearHiddenFormFields()
{
	changeFormFieldValue('collectionBasic', '');
	changeFormFieldValue('dateFromBasic', '');
	changeFormFieldValue('fileFormatBasic', '');
	changeFormFieldValue('pageBasic', '');
	changeFormFieldValue('similarId', '');
	changeFormFieldValue('filter', '');
	changeFormFieldValue('crn', '');
}

function submitAdvQueryForm()
{
	changeFormFieldValue('pageAdvanced', '');
	changeFormFieldValue('similarId', '');
	submitForm('advqueryform');
}

function submitAllNovellChange(allNovell)
{
	changeFormFieldValue('allNovell', allNovell);
	changeFormFieldValue('pageBasic', '');
	getExpandedCollection();
	submitForm('queryform');
}

function submitCollectionChange(collection)
{
	changeFormFieldValue('collectionBasic', collection);
	changeFormFieldValue('pageBasic', '');
	getExpandedCollection();
	submitForm('queryform');
}

function submitDateChange(date)
{
	changeFormFieldValue('dateFromBasic', date);
	changeFormFieldValue('pageBasic', '');
	getExpandedCollection();
	submitForm('queryform');
}

function submitFileFormatChange(format)
{
	changeFormFieldValue('fileFormatBasic', format);
	changeFormFieldValue('pageBasic', '');
	getExpandedCollection();
	submitForm('queryform');
}

function changeFormFieldValue(id, value)
{
	var field = document.getElementById(id);
	if (field != null)
	{
		field.value = value;
	}
}

// Submit form without calling onsubmit event
function submitForm(id)
{
	var form = document.getElementById(id);
	if (form != null)
	{
//		getExpandedCollection();
		form.submit();
	}
}

function gotoPage(page)
{
	var queryForm;
	if ($('#queryform').size() > 0) {
		queryForm = 'queryform';
		changeFormFieldValue('pageBasic', page);
	}
	else {
		queryForm = 'advqueryform';
		changeFormFieldValue('pageAdvanced', page);
	}
	getExpandedCollection();
	submitForm(queryForm);
}

function clearTextFields()
{
	changeFormFieldValue('allWords', '');
	changeFormFieldValue('exactWords', '');
	changeFormFieldValue('anyWords', '');
	changeFormFieldValue('noneWords', '');
}

function onSaveQueryDialogSaveButtonClick() 
{
	$('#saveQueryDialog').dialog('close');
	var queryName = $('#saveQueryDialog input[name=queryName]');
	var queryForm = $('#queryform').is(":visible") ? $('#queryform') : $('#advqueryform');
	var queryFormInput = $('#queryform').is(":visible") ? $('#queryform input[name=queryName]') : $('#advqueryform input[name=queryName]');
	$(queryFormInput).val(queryName.val());
	getExpandedCollection();
	queryForm.submit();
}

function onEditQueryDialogSaveButtonClick() 
{
	$('#editQueryDialog').dialog('close');
	
	var dataArray = new Array();
	
	$('#editQueryDialog ul li a.title').each(function() 
	{
		var obj = 
		{
	        id: $(this).parent()[0].id,
    	    name: $(this).text(),
        	visible: ($(this).parent().css('display')=='none'?0:1)
    	};
    	
    	dataArray.push(obj);
	});
	
	$.ajax({ type: 'post', 
	         url: 'editsavedqueries', 
	         dataType: 'json',
	         data: {data: $.toJSON(dataArray)}, 
	         async: false, 
	         success: function(response) 
	         { 
	         	if (response.message != null && response.message.length > 0)
	         	{
		         	$('#messagesDialog').html(response.message);
		         	$('#messagesDialog').dialog('open')
		        }
	         	$.publish('EditQueryCompleteTopic'); 
	         }
	});
}

function onSelectSavedQueries(obj)
{
	$.ajax({ type: 'post', 
	         url: 'retrievequery', 
	         dataType: 'json',
	         data: {id: $(obj).val()}, 
	         async: false, 
	         success: function(response) 
	         { 
	         	if (response.message != null && response.message.length > 0)
	         	{
		         	$('#messagesDialog').html(response.message);
		         	$('#messagesDialog').dialog('open')
		        }
		        else
		        {
		        	window.location.href = 'query?' + (response.url == null ? '' : response.url);
		        }
	         }
	});
}

/* ************************************
 * The following should all the form to
 * submit when enter is pressed.
 * ************************************/

function submitenter(inputfield, e)
{
	var keycode;
	if (window.event)
		keycode = window.event.keyCode;
	else if (e)
		keycode = e.which;
	else
		return true;

	if (keycode == 10 || keycode == 13)
	{
		$('#queryform').is(":visible") ? submitQueryForm() : submitAdvQueryForm();
		return false;
	}
	else
		return true;
	
}

/*******
* Dev Search JS doc
* for use by Brent Leavitt
* Updated: 25 Feb 2011
**********/


//CREDIT: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});



$(document).ready(function(){

	$.subscribe('autoCompleteSelectTopic', function(event, data) {
		var ui = event.originalEvent.ui;
		$('#term').val(ui.item.value);
		if($('#term').val().length > 0) {
			setTimeout(submitQueryForm, 100);
		}
	});

	var advancedQuery = false; 
	
	//$('div.module>ul.pseudo_checkboxlist').addClass('jq');
	if($.getUrlVar('queryType')=='advanced'){
		advancedQuery = true; 
	}
	
	if($.getUrlVar('crn')){
		
		var byName = $.getUrlVar('crn');
		var collNum = new Array();
		collNum = byName.split('-');
		//
		//alert(collNum);
		
		if(advancedQuery){
			for(var j=0; j<collNum.length; j++)
			{
			
				var collId = "collection_"+collNum[j];
				$('ul.checkboxlist li input#'+collId).siblings('a.checkboxtoggle').addClass('checkboxtoggle_open').siblings('ul.checkboxlist').show();		
			}
		}else{
		//assume basic query
			for(var j=0; j<collNum.length; j++)
			{
			
				var collId = "coll_"+collNum[j];
				$('ul.pseudo_checkboxlist li ul#'+collId).siblings('a.checkboxtoggle').addClass('checkboxtoggle_open').end().show();					

			}
		}
	}

	//set clear btn at page load. 
	$('#form_advanced_col2 ul.checkboxlist li input:checked').each(function(){
		$('#form_advanced_col2 p.clear_filter').show();
	});
	
	//toggles clear btn visibility based on whether any labels have selected classes or not. 
	$('#form_advanced_col2 ul.checkboxlist li').click(function(){
		var selectBox = false;
		$('#form_advanced_col2 ul.checkboxlist li label.selected').each(function(){
			selectBox = true;
		});
		
		if(selectBox !== true){
			$('#form_advanced_col2 p.clear_filter').hide('fast');
		}else{
			$('#form_advanced_col2 p.clear_filter').show('slow');
		}
		selectBox = false;
	});
	
	//clear btn functionality. Strips all selections out of both the labels and respective input fields. 
	$('#form_advanced_col2 p.clear_filter').click(function(){
		$('#form_advanced_col2 ul.checkboxlist li label').removeClass('selected partial').siblings('input').attr('checked','');
		$('#form_advanced_col2 ul.checkboxlist ul').hide();
		$('#form_advanced_col2 ul.checkboxlist li a.checkboxtoggle_open').removeClass('checkboxtoggle_open');
		$(this).hide('fast');
	});

	var dateFrom = $('input#dateFrom').val();
	var dateTo = $('input#dateTo').val();
	
	if((dateTo !== '')||(dateFrom !== '')){
		$('#form_wrap .form_advanced_dates #adv_date_clr').show();
	}

	$('input#dateFrom').change(function(){
		engageDateClear();
	})

	$('input#dateTo').change(function(){
		engageDateClear();
	})
	
	$('#form_wrap .form_advanced_dates #adv_date_clr a').click(function(){
		$('input#dateTo').val('');
		$('input#dateFrom').val('');
		$(this).parent().hide('fast');
	
	});

	$('input#crn').val('');//Clear value of  INPUT #crn. 
	$('div.module>ul.pseudo_checkboxlist').show();//This is the last thing to happen  so that jquery has time to build the rest... 
	$('#form_advanced_col2 > ul.checkboxlist').show(); 
});

 //this method is called on form submit, it records to the "CRN" (Collections Right Navigation) hidden input field  the unique ID's of each collection which has been expanded. 
function getExpandedCollection(){

	var advancedQuery = false; 
	
	//$('div.module>ul.pseudo_checkboxlist').addClass('jq');
	if($.getUrlVar('queryType')=='advanced'){
		advancedQuery = true; 
	}
	
	var collString = '';
	
	if(advancedQuery){
		$('ul.checkboxlist li a.checkboxtoggle_open').each(function(){
			var expandedId = $(this).siblings('input').attr('id');
			var numId = expandedId.substr(11);//get only the number from the ID
			collString += numId+'-';
		}); //Find the expanded collections	
		
	}else{
		$('ul.pseudo_checkboxlist li a.checkboxtoggle_open').each(function(){
			var expandedId = $(this).siblings('ul').attr('id');
			var numId = expandedId.substr(5);//get only the number from the ID
			collString += numId+'-';
		}); //Find the expanded collections	
	}

	var newCollString = collString.substr(0,collString.length-1);//Strip last character from string...
	$('input#crn').val(newCollString);
}

	//find the rows within the div.modules ul.pseudo_checkboxlist that are expanded.  
		//Find a way to index and record each instance. Even just a numerical list of values, then pass those to a hidden input field that get passed on submit. 
		
	//For each LI with a child anchor tag that has the class of "checkboxtoggle_open", select the sibling anchor tag's content. That becomes your unique ID. 
	//Assemble each one into an arrray. and then stuff this into the value of the hidden input field. 
	
	//On the flip side, when the page is loaded, look for this hidden input field. if it exists process the values contained therein. 
		//loop  through each li in the main  ul.pseudo_checkboxlist and find if in the second anchor tag there is a match with any one of the arrayed items sent. If a match, apply a "checkboxtoggle_open" class to the previous sibling of the anchor tag class. 
		
		//Also to avoid too much gitteriness. hide collections until classes are set and ready to display. 

function engageDateClear(){
	$('#form_wrap .form_advanced_dates #adv_date_clr').show('slow');
	
 }
