/**
 *	Utility functions for d3mls search
 *	@version MarkF Redesign
 */
var d3mls_search =
{
	buttonClass : "button",
	divId : "d3mls_search",
	loadingIcon : "/images/ajax-loader.gif",

	init : function(divId, buttonClass, loadingIcon)
	{
		if (divId != '')
			this.divId = divId;
		if (buttonClass != '')
			this.buttonClass = buttonClass;
		if (loadingIcon != '')
			this.loadingIcon = loadingIcon;

		this.setupSearchForm();
	},
	
	setupSearchForm : function()
	{
		$("#"+this.divId+" a."+this.buttonClass).bind("click", function(e){
			
			e.preventDefault();
			d3mls_search.activateLoadingIcon();
			$("form[name=search_form]").append("<input type='text' class='hidden' name='scrolltops' value='"+d3mls_search.selectScrollTops.join(",")+"' />");
			$("form[name=search_form]").submit();
		});

		this.setupLoadingIcon();
		this.setupLocationsSelectInputs();
	},

	setupSearchTabs : function()
	{
		$("#"+this.divId).tabs();
	},

	getSuggest : function(input)
	{
		$input = $(input);
		if (( $input.val().length > 2 && parseInt($input.val()) ) || $input.val().length > 5){
			$.post('/app/modules/d3mls/ninja_code/search_simple.php', {'loc' : $input.val()},
				function(data){
					if (data.length > 1)
						$input.next().html(data).show();
					else
						$input.next().hide();
				}
			);
		}
	},

	locationSuggestFill : function(value, suggestResult)
	{
		$(suggestResult).parent().prev().val(value);
		$("#suggestBox").hide();
	},

	/**
	 *	Functions for dimming the screen and spinning the progress wheel
	 */
	$loadingBlanket : null,
	$loadingIcon : null,

	activateLoadingIcon : function()
	{
		this.$blanket.css({
				height: $("#"+this.divId).height()
			}).show();
		this.$loadingIcon.css({
				"top"		: ($("#"+this.divId).height() / 2),
				"left"		: ($("#"+this.divId).width() / 2)
			}).show();
	},

	setupLoadingIcon : function()
	{
		this.$blanket = $("<div class='loadingBlanket'></div>").prependTo("#"+this.divId);
		this.$loadingIcon = $("<img class='loadingIcon' src='"+this.loadingIcon+"' />").prependTo("#"+this.divId);
	},

	/**
	 *	2D Array to hold a list of geographic divisions (currently regions, counties, areas, cities and sub_divisions)
	 */
	selectedLocations : [[],[],[],[],[]],
	/**
	 *	Array of scrollTops, one per select box, for remembering where in the box a location input was checked
	 */
	selectScrollTops : [0,0,0,0,0],
	/**
	 *	Set up checkboxes to respond to location selects
	 */
	setupLocationsSelectInputs : function()
	{
		$("#"+this.divId+" > #generalSearchDiv >#locationsSection > #locationsSelectsContainer div.locations input[type=checkbox]").each(
			function()
			{
				$(this).bind("click",function(event){
					d3mls_search.selectInputs($(this),parseInt($(this).attr("index")),event);
				});
			}
		);
	},
	/**
	 *	Get a new set of locations select boxes for the container (#locationsSelectsContainer)
	 *	@param $input The clicked input
	 *	@param index The index of the locations select box
	 *	@param $event The click event
	 */
	selectInputs : function($input, index, $event)
	{
		this._dim($(".locationsSelects:eq("+(index)+")"), true);
		this.selectScrollTops[index] = $input.parents(".locationsSelects").scrollTop();
		var locations = $input.val().split("|");
		if ($input.is(":checked") && $.inArray(locations[index],this.selectedLocations[index])<0)
			this.selectedLocations[index].push(locations[index]);
		else
			this.selectedLocations[index] = this._removeElements([locations[index]], this.selectedLocations[index]);

		if (index < 4)//sub_division inputs don't have children
		{
			$.post("/app/modules/d3mls/xml/getLocations.php",
				{
					'locations' : this.selectedLocations,
					'index' : index
				},
				function(data, status)
				{
					$("#locationsSelectsContainer").replaceWith(data);
					$(".locationsSelects").each(function(i){
						var scrollTopValue = d3mls_search.selectScrollTops[i+1];
						$(this).scrollTop(scrollTopValue);
					});
				}
			);
		}
	},

	/**
	 * Update locations select boxes scroll tops from posted array
	 * @param scrolltopsAr Array
	 */
	updateScrolltops : function(scrolltopsAr)
	{
		this.selectScrollTops = scrolltopsAr;
		$(".locationsSelects").each(function(i){
			var scrollTopValue = d3mls_search.selectScrollTops[i+1];
			$(this).scrollTop(scrollTopValue);
		});
	},

	/**
	 * Dim/undim a div's content
	 * @param $div jQuery Div to dim
	 * @param dim Boolean True to dim, false to undim
	 */
	_dim : function($div, dim)
	{
		$div.css({
			"color" :"black",
			"-ms-filter" : "progid:DXImageTransform.Microsoft.Alpha(Opacity=40)",
			"filter" : "alpha(opacity="+((dim)?40:100)+")",
			"-moz-opacity" : ((dim)?.40:1),
			"opacity" : ((dim)?.40:1)
			});
	},

	/**
	 *	Remove an array of elements from an array
	 *	@param theseElements Array of strings to remove
	 *	@param fromThisArray Array to remove from
	 *	@return	fromThisArray
	 */
	_removeElements : function(theseElements, fromThisArray)
	{
		$.unique(theseElements);
		$.unique(fromThisArray);

		for (var i=0; i<theseElements.length;i++)
			fromThisArray = $.grep(fromThisArray, function(value) {
				return value != theseElements[i];
			});
		return fromThisArray;
	},

	/**
	 *	Group all locations under location parent (i.e. parent county > child city) and collapse the group
	 *	@param divId String The id of the node containing location parent/child group
	 */
	locationsAccordion : function(divId)
	{
		//set each group to open and collapse
		$('#'+divId+' .locationsSelectSection .locationsHeader').click(function() {
			var $locationsHeaderIcon = $(this).find("div.locationsHeaderIcon");
			if ($locationsHeaderIcon.hasClass('locationsHeaderIconClicked'))
				$locationsHeaderIcon.removeClass("locationsHeaderIconClicked");
			else
				$locationsHeaderIcon.addClass("locationsHeaderIconClicked");
			$(this).next().toggle('slow');
		}).next().hide();
		//if location select contains only one group (contains title div and div of inputs), open that group
		if ($('#'+divId+' > .locationsSelectSection').children().size()<4)
		{
			$('#'+divId).find(">:first-child .locationsHeader .locationsHeaderIcon")
				.addClass("locationsHeaderIconClicked").end()
				.find(".locationsContent").show();
		}
		else
		{	//search each group for checked inputs and open if any found
			$('#'+divId+' .locationsSelectSection .locationsContent input:checked').each(
				function(){
					$(this).parent().parent().parent().prev().find(".locationsHeaderIcon").addClass("locationsHeaderIconClicked").end().next().show();
				}
			);
		}
	},

	/**
	 *	Make an accordion. Assumes div.accordionPanel and then the div to collapse/show
	 */
	accordion : function(divId)
	{

		var $panels = $('#'+divId+' .accordionPanel');

		$panels.click(function() {
			$(this).next().toggle('slow');
		}).next().hide();

		if ($panels.length == 1)
			$panels.next().show();
	}
};

