$(document).ready
(
	function()
	{
		$('#select2').attr('disabled', 'disabled');
		$('#select1').change
		(
			function processChange()
			{
				function removeOptions()
				{
					this.options.length = 1;
				}
			
				function beforePost()
				{
					this.options[0].text = 'Loading...';
					$(this).attr('disabled', 'disabled');
				}
			
				function processResponse(data, textStatus)
				{
					for (i = 0; i < data.length; i++)
					{
						$('#select2').get(0).options[$('#select2').get(0).options.length] = new Option(data[i].market_name, data[i].market_id);
					}

					$('#select2').each(afterPost)
				}
			
				function afterPost()
				{
					this.options[0].text = 'Choose One';
					$(this).attr('disabled','');
				}
			
				if (!this.selectedIndex && $.cookie('state')) {
				    this.selectedIndex = $.cookie('state');
				}
				
				if (this.selectedIndex != 0)
				{
				    $.cookie('state', this.selectedIndex, { path: '/', expires: 10 });
					$('#select2').each(removeOptions);
					$('#select2').each(beforePost);
					//$.getJSON('/index/markets/state/' + $('#select1').val(), {} , processResponse);
					$.ajax
					({
						type:"GET",
						url:"/data/markets.xml",
						dataType:"xml",
						success:function(xml)
						{
							$(xml).find('Markets').each
							(
							 	function()
								{
									if ($(this).find('state').text() == $('#select1').val())
									{
										$('#select2').get(0).options[$('#select2').get(0).options.length] = new Option($(this).find('market_name').text(), $(this).find('subdomain').text());
									}
								}
							);
							
							$('#select2').each(afterPost);
						}
					});
				}
				else
				{
					$('#select2').each(removeOptions)
				}
			}
		);
	
		$('#search_form').submit
		(
			function()
			{
				if($('#select2').get(0).selectedIndex > 0)
				{
					locationRegex = /(www\.)?(.*)/
					document.location = "http://" + $('#select2').get(0).options[$('#select2').get(0).selectedIndex].value+ "." + document.location.host.replace(locationRegex, '$2');
					return false;
				}
				else return false;
		}
	)
	
	 $('#select1').change();
	
 });

