/************************************
SEARCH
Written by Ethan Gruber, ewg4x@virginia.edu
Library: jQuery
Description: Portions of this originally authored by Matt Mitchell.
Modified heavily to handle the search form functionality
and piecing together the search query.
************************************/

$(function () {
	
	// display error if server doesn't respond
	$("#search") .ajaxError(function (request, settings) {
		$(this) .html('<div id="error">Error requesting page/service unavailable.</div>');
	});
	
	// 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 select') .change(function () {
		$(this) .siblings('.search_text') .focus();
	})
	// copy the base template
	
	
	function gateTypeBtnClick(btn) {
		// increment - this is really just used to created unique ids for new dom elements
		total_options++;
		
		var tpl = $('#searchItemTemplate') .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);
		$(tpl) .children('div') .attr('id', 'container_' + 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();
		});
		
		// assign the handler for all gateTypeBtn elements within the new item/template
		$(tpl) .children('.gateTypeBtn') .click(function () {
			gateTypeBtnClick($(this));
		});
		
		// 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');
		});
		toggle_options();
	}
	
	// assign the gate/boolean button click handler
	$('.gateTypeBtn') .click(function () {
		gateTypeBtnClick($(this));
	})
	
	// activates the advanced search action
	$('#and_button') .click(function () {
		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('.category_list') .attr('value');
			
			if (val != 'year' && val != 'weight' && val != 'dimensions') {
				query += sep + val;
				query += ':' + $(this) .children('.option_container') .children('#search_text') .attr('value');
				sep = ' ';
			} else if (val == 'weight') {
				query += sep + '(' + val;
				var weight = $(this) .children('.option_container') .children('.weight_int') .attr('value');
				var range_value = $(this) .children('.option_container') .children('.weight_range') .attr('value');
				if (range_value == 'lessequal') {
					query += ':[* TO ' + weight + ']';
				} else if (range_value == 'greaterequal') {
					query += ':[' + weight + ' TO *]';
				}
				else if (range_value == 'equal'){
					query += ':' + weight;
				}
				query += ')';
				sep = ' ';
			} else if (val == 'dimensions') {
				query += sep + '(' + val;
				var dimensions = $(this) .children('.option_container') .children('.dimensions_int') .attr('value');
				var range_value = $(this) .children('.option_container') .children('.dimensions_range') .attr('value');
				if (range_value == 'lessequal') {
					query += ':[* TO ' + dimensions + ']';
				} else if (range_value == 'greaterequal') {
					query += ':[' + dimensions + ' TO *]';
				}
				else if (range_value == 'equal') {
					query += ':' + dimensions;
				}
				query += ')';
				sep = ' ';
			} else if (val == 'year') {
				query += sep + '(' + val;
				var year = $(this) .children('.option_container') .children('.year_int') .attr('value');
				var era = $(this) .children('.option_container') .children('.year_era') .attr('value');
				if (era == 'minus') {
					era = '\\-';
				} else {
					era = '';
				}
				var range_value = $(this) .children('.option_container') .children('.year_range') .attr('value');
				if (range_value == 'less') {
					query += ':[* TO ' + era + year + '] AND NOT year:' + era + year;
				} else if (range_value == 'lessequal') {
					query += ':[* TO ' + era + year + ']';
				} else if (range_value == 'equal') {
					query += ':' + era + year;
				} else if (range_value == 'greaterequal') {
					query += ':[' + era + year + ' TO *]';
				} else if (range_value == 'greater') {
					query += ':[' + era + year + ' TO *] AND NOT year:' + era + year;
				}
				query += ')';
				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 + 'AND';
				delete tmp_gate_items[i];
				break;
			}
		});
		// pass the query to the search_results url passing the needed url params:
		$.get('search_results', {
			q : query, start:0, rows:10, ajax: true
		},
		function (data) {
			//$('#error').html('');
			// push the result into the document
			$('#search') .html(data);
			// hide the load indicator
		});
		
		// cancel the default action of the submit buttton (don't want to re-direct)
		
		return false;
	});
	$('#or_button') .click(function () {
		
		var query = '';
		var sep = '';
		var position = 1;
		
		// 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('.category_list') .attr('value');
			
			if (val != 'year' && val != 'weight' && val != 'dimensions') {
				query += sep + val;
				query += ':' + $(this) .children('.option_container') .children('#search_text') .attr('value');
				sep = ' ';
			} else if (val == 'weight') {
				query += sep + '(' + val;
				var weight = $(this) .children('.option_container') .children('.weight_int') .attr('value');
				var range_value = $(this) .children('.option_container') .children('.weight_range') .attr('value');
				if (range_value == 'lessequal') {
					query += ':[* TO ' + weight + ']';
				} else if (range_value == 'greaterequal') {
					query += ':[' + weight + ' TO *]';
				}
				else if (range_value == 'equal'){
					query += ':' + weight;
				}
				query += ')';
				sep = ' ';
			} else if (val == 'dimensions') {
				query += sep + '(' + val;
				var dimensions = $(this) .children('.option_container') .children('.dimensions_int') .attr('value');
				var range_value = $(this) .children('.option_container') .children('.dimensions_range') .attr('value');
				if (range_value == 'lessequal') {
					query += ':[* TO ' + dimensions + ']';
				} else if (range_value == 'greaterequal') {
					query += ':[' + dimensions + ' TO *]';
				}
				else if (range_value == 'equal') {
					query += ':' + dimensions;
				}
				query += ')';
				sep = ' ';
			} else if (val == 'year') {
				query += sep + '(' + val;
				var year = $(this) .children('.option_container') .children('.year_int') .attr('value');
				var era = $(this) .children('.option_container') .children('.year_era') .attr('value');
				if (era == null) {
					era = '';
				} else {
					era = '\\-';
				}
				var range_value = $(this) .children('.option_container') .children('.year_range') .attr('value');
				if (range_value == 'less') {
					query += ':[* TO ' + era + year + '] AND NOT year:' + era + year;
				} else if (range_value == 'lessequal') {
					query += ':[* TO ' + era + year + ']';
				} else if (range_value == 'equal') {
					query += ':' + era + year;
				} else if (range_value == 'greaterequal') {
					query += ':[' + era + year + ' TO *]';
				} else if (range_value == 'greater') {
					query += ':[' + era + year + ' TO *] AND NOT year:' + era + year;
				}
				query += ')';
				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 + 'OR';
				delete tmp_gate_items[i];
				break;
			}
			position++;
		});
		// pass the query to the search_results url passing the needed url params:
		$.get('search_results', {
			q : query, start:0, rows:10, ajax: true
		},
		function (data) {
			//$('#error').html('');
			// push the result into the document
			$('#search') .html(data);
			// hide the load indicator
		});
		
		// cancel the default action of the submit buttton (don't want to re-direct)
		$('#advanced_search_text') .html(query);
		return false;
	});
	
	$('#advanced_search_button') .click(function () {
		var query = $('#advanced_search_text') .attr('value');
		$.get('search_results', {
			q : query, start:0, rows:10, ajax: true
		},
		function (data) {
			$('#search') .html(data);
		});
		return false;
	});
});