/// <reference name="MicrosoftAjax.debug.js" />

var Cyberhomes = 
{
	initialize : function ()
	{
		this._setupElements();
		this._initializeSearchConfig();
		this._addEventHandlers();
		
		// enable the search textbox
		$get(this._elements.searchQuery).disabled = false;
		$get(this._elements.searchType).disabled = false;
		
		if (Sys.Browser.agent === Sys.Browser.Firefox)
			$get(this._elements.searchType).style.height = "23px";
	},
	
	dispose : function ()
	{
		this._clearEventHandlers();
	},
	
	
	// Private Methods ----------------------------------------------------------------------------------------------
	
	_setupElements : function ()
	{
		this._elements = 
		{
			searchType		: "search_type",
			searchQuery		: "search_query",
			searchButton	: "search_submitButton"
		};
	},
	
	_addEventHandlers : function ()
	{
		var e = this._elements;
		
		$addHandlers($get(e.searchType), { change : function (evt) { this._selectSearchType(this.get_searchType()); } }, this);
		
		$addHandlers($get(e.searchQuery),
		{
			focus	: function (evt) { this._searchQueryHasFocus = true; this._updateHintText(); },
			blur	: function (evt) { this._searchQueryHasFocus = false; this._updateHintText(); },
			keydown : function (evt) { var key = this._getEventKey(evt); if (key === Sys.UI.Key.enter) { this._submitSearch(); this._freezeEvent(evt.rawEvent); } }
		}, this);
		
		$addHandlers($get(e.searchButton), { click : function (evt) { this._submitSearch(); evt.stopPropagation(); } }, this);
		
		this._eventHandlersAdded = true;
	},
	
	_clearEventHandlers : function ()
	{
		if (!this._eventHandlersAdded) return;
		
		$clearHandlers($get(this._elements.searchType));
		$clearHandlers($get(this._elements.searchQuery));
		$clearHandlers($get(this._elements.searchButton));
	},

	_updateHintText : function ()
	{
		var txt = $get(this._elements.searchQuery);
		
		if (this._searchQueryHasFocus)
		{
			if (txt.value.trim().startsWith(this._searchConfig[this.get_searchType()].hintText))
				txt.value = String.empty;
		}
		else
		{
			if (String.isNullOrEmpty(txt.value.trim()) || this._isHintText(txt.value.trim()))
				txt.value = this._searchConfig[this.get_searchType()].hintText;
		}
	},
	
	_isHintText : function (text)
	{
		var c = this._searchConfig;
		for (var i = 1; i < c.length; i++)
		{
			if (c[i].hintText === text)
				return true;
		}
		return false;
	},
	
	_submitSearch : function ()
	{
		var query = $get(this._elements.searchQuery);
		location.href = "http://www.cyberhomes.com/searchredirect.aspx?query={0}&srchtype={1}".format(escape(query.value.trim()), this.get_searchType());
	},
	
	_initializeSearchConfig : function ()
	{
		this._searchConfig = [];
		
		this._searchConfig[1] = { hintText : "Type a neighborhood, county, city & state, or ZIP" };
		this._searchConfig[2] = { hintText : "Type a full address, neighborhood, county, city & state, or ZIP" };
		this._searchConfig[3] = { hintText : "Type a neighborhood, county, city & state, or ZIP" };
		this._searchConfig[4] = { hintText : "Type a neighborhood, county, city & state, or ZIP" };
		this._searchConfig[5] = { hintText : "Type a neighborhood, county, city & state, or ZIP" };
	},
	
	_selectSearchType : function (searchType)
	{
		// make sure the proper value is selected in the drop-down
		$setValue(this._elements.searchType, searchType);
		
		// update the hint-text for the search textbox
		this._updateHintText();
	},
	
	_getEvent : function (evt) { return (evt ? evt : window.event); },
	
	_getEventKey : function (evt)
	{
		evt = this._getEvent(evt);
		if (evt) return (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	},
	
	_freezeEvent : function (evt)
	{
		if (evt.preventDefault) evt.preventDefault();
		evt.returnValue = false;
		evt.cancelBubble = true;
		if (evt.stopPropagation) evt.stopPropagation();
		return false;
	},
	

	// --- Public Properties -----------------------------------------------------------------------------------------
	
	get_searchType : function () { return parseInt($getValue(this._elements.searchType), 10); }
};

Sys.Application.add_load(Function.createDelegate(Cyberhomes, Cyberhomes.initialize));
Sys.Application.add_unload(Function.createDelegate(Cyberhomes, Cyberhomes.dispose));





// String class extentions ===============================================================================================================

String.empty = "";

String.isNullOrEmpty = function (value)
{
	/// <summary>Returns true if the value is null or empty.</summary>
	/// <param name="value" type="String" optional="false" mayBeNull="true">The value to test.</param>

	return typeof(value) == "undefined" || value === null || value === String.empty || value.toString() === String.empty;
};

String.parse = function (value)
{
	/// <summary>Parses the specified value to a string.</summary>
	/// <param name="value" type="Object" optional="false" mayBeNull="true">The value to parse to a string.</param>
	
	return "{0}".format(value);
};

String.format = function (format, args)
{
	/// <summary>Overrides the ASP.NET AJAX String.format method. Our implementation of 'format' proved to be much more efficient!</summary>
    /// <param name="format" type="String">The format string.</param>
    /// <param name="args" parameterArray="true" mayBeNull="true">The arguments for formatting.</param>
    
    if (arguments.length === 2)
		return format.format(arguments[1]);
	else
		return format.format(Array.prototype.slice.call(arguments, 1));
};

String.prototype.format = function(args)
{
    /// <summary>Formats a string based on the parameters passed in.</summary>
    /// <param name="args" parameterArray="true" mayBeNull="true">The arguments for formatting.</param>
		
	var params = String.prototype.format.arguments;
    var toReturn = this;

    if ( params !== null )
    {
		if ( params.length > 0 && params[0] !== null && typeof(params[0]) == "object" )
		{
			params = params[0];	
		}
		
		for (var i = 0; i < params.length; i++)
		{
			if (params[i] === null) params[i] = String.empty;
			var regex = new RegExp("\\{" + i + "\\}", "g");
			toReturn = toReturn.replace(regex, params[i]);
		}
	}

	return toReturn;
};



// Sys.UI.DomElement class extentions ===============================================================================================================

var $getValue = Sys.UI.DomElement.getValue = function (elementId, trimValue)
{
	/// <summary>Returns the value of the element based on its type.</summary>
	/// <param name="elementId" type="String" optional="false" mayBeNull="false">The ID of the element.</param>
	/// <param name="trimValue" type="Boolean" optional="true" mayBeNull="true">Indicates whether to trim the value.</param>

	var value = String.empty;
	var inst = $get(elementId);
	if (inst)
	{		
		if (inst.tagName === "SELECT")
		{
			if (inst.options.length > 0)
				value = inst.options[inst.selectedIndex].value;
		}
		else if ((inst.tagName === "INPUT" && inst.type === "checkbox") || (inst.tagName === "INPUT" && inst.type === "radio"))
			value = inst.checked ? true : false;
		else
			value = inst.value;
	}
	if (trimValue) value = value.trim();
	return value;
};

var $setValue = Sys.UI.DomElement.setValue = function (elementId, value)
{
	/// <summary>Sets the value of the element.</summary>
	/// <param name="elementId" type="String" optional="false" mayBeNull="false">The ID of the element.</param>
	/// <param name="value" type="String" optional="false" mayBeNull="false">The value to set.</param>
	
	var inst = $get(elementId);
	if (inst && typeof(value) !== 'undefined')
	{
		if ((inst.tagName === "INPUT" && inst.type === "checkbox") || (inst.tagName === "INPUT" && inst.type === "radio"))
			inst.checked = value;
		else if (inst.tagName === "SELECT")
			Sys.UI.DomElement.selectByValue(elementId, value);
		else
			inst.value = value;
	}
};

Sys.UI.DomElement.getSelectedText = function (elementId)
{
	/// <summary>Gets the text of the selected item in the 'select' element.</summary>
	/// <param name="elementId" type="String" optional="false" mayBeNull="false">The ID of the element.</param>

	var text = String.empty;
	var inst = $get(elementId);
	if (inst)
	{
		if (inst.selectedIndex !== -1)
			text = inst.options[inst.selectedIndex].innerHTML;
	}
	return text;
};

Sys.UI.DomElement.selectByValue = function (elementId, value)
{
	/// <summary>Finds and selects a value in a 'select' element.</summary>
	/// <param name="elementId" type="String" optional="false" mayBeNull="false">The ID of the element.</param>
	/// <param name="value" type="String" optional="false" mayBeNull="false">Value to search for.</param>
	
	var inst = $get(elementId);
	if (inst)
	{
		value = String.parse(value);
		for (var i = 0; i < inst.options.length; i++) 
		{
			if (inst.options[i].value === value) { inst.options[inst.selectedIndex].selected = false; inst.options[i].selected = true; }
		}
	}
};