var httpObj = getHTTPObject();
var isWorking = false;
var request = createRequestObject();
var usePropId = true;


function getHTTPObject() {

  var xmlhttp = false;

  if(window.XMLHttpRequest)
  {
  	try
	{
		xmlhttp = new XMLHttpRequest();
	}
	catch(e)
	{
		xmlhttp = false;
	}
  }
  else if(window.ActiveXObject)
  {
  	try
	{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}	
	catch(e)
	{
		try
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e)
		{
			xmlhttp = false;
		}
	}
  }
 
  return xmlhttp;

}



function handleSuiteResponse()
{
	if (httpObj.readyState == 4) 
	{

		if (httpObj.responseText.indexOf('invalid') == -1) 
		{
			list = httpObj.responseText.split("|");
			
			suiteObj = document.getElementById('suite');
			suiteField = document.getElementById('suite_field');
			suiteObj.options.length=0;
			selection = false;
			
			if(httpObj.responseText.length>0)
			{
				for(var index=0; index < list.length; index++)
				{
					suiteObj.options[index] = new Option(list[index],list[index]);
					
					if(request['suite'] && suiteObj.options[index].value == request['suite'])
					{
						suiteObj.selectedIndex = index;
						request['suite'] = null;
						selection = true;
					}
				}
//				
				
				suiteField.style.display = 'block';
			}
			else
			{
				var index = 0;
				
				suiteField.style.display = 'none';
			}
			
			suiteObj.options[index] = new Option('Any','Any');
			if(!selection)
				suiteObj.selectedIndex = index;
			
			isWorking = false;
		}
	}
}

function onPropertyChange()
{
	var prop = document.getElementById('property').value;
	suiteObj = document.getElementById('suite');
	suiteField = document.getElementById('suite_field');
	
	if(prop == '-1')//handle the any selection
	{
		
		suiteObj.selectedIndex = suiteObj.options.length-1;
		suiteField.style.display = 'none';
		return;
	}
	
	var url = "/cgi/suiteList/"+prop;
	
	httpObj.open("GET",url,true);
	httpObj.onreadystatechange = handleSuiteResponse;
	isWorking = true;
	httpObj.send(null);
	//suiteField.style.display = 'block';
}//end populate cities

function handlePropertyResponse()
{
	if (httpObj.readyState == 4) 
	{

		if (httpObj.responseText.indexOf('invalid') == -1) 
		{
			console.debug(httpObj.responseText);
			
			propComboBox = document.getElementById('property');
			propComboBox.options.length=0;
			selection = false;
			
		
			for(var index=0; getQueryVariable('id'+index,httpObj.responseText)!=null; index++)
			{
				if(usePropId)
					propComboBox.options[index] = new Option(decode(getQueryVariable('title'+index,httpObj.responseText)),getQueryVariable('id'+index,httpObj.responseText));
				else
					propComboBox.options[index] = new Option(decode(getQueryVariable('title'+index,httpObj.responseText)),decode(getQueryVariable('title'+index,httpObj.responseText)));
				
				if(request['property'] && propComboBox.options[index].value == request['property'])
				{
					propComboBox.selectedIndex = index;
					request['property'] = null;
					selection = true;
				}
			}
			if(usePropId)
				propComboBox.options[index] = new Option('Any','-1');
			else
				propComboBox.options[index] = new Option('Any','Any');
			
			if(!selection)
				propComboBox.selectedIndex = index;
			
			isWorking = false;
			
			//onPropertyChange();
		}
	}
}

function onCityChange()
{
	var city = document.getElementById('desiredCity').value;
	
	if(city == 'Any')//handle the any selection
	{
		var url = "/cgi/propertyList"
	}
	else
	{
		var url = "/cgi/propertyList/"+document.getElementById('desiredCity').value;
	}
	
	httpObj.open("GET",url,true);
	httpObj.onreadystatechange = handlePropertyResponse;
	isWorking = true;
	httpObj.send(null);
}//end populate cities

function getQueryVariable(variable,string) {
  var query = string;
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  return null;
}

function decode(str) {
     return unescape(str.replace(/\+/g, " "));
}

function createRequestObject() {
  FORM_DATA = new Object();
    // The Object ("Array") where our data will be stored.
  separator = ',';
    // The token used to separate data from multi-select inputs
  query = '' + this.location;
  qu = query
    // Get the current URL so we can parse out the data.
    // Adding a null-string '' forces an implicit type cast
    // from property to string, for NS2 compatibility.
  query = query.substring((query.indexOf('?')) + 1);
    // Keep everything after the question mark '?'.
  if (query.length < 1) { return false; }  // Perhaps we got some bad data?
  keypairs = new Object();
  numKP = 1;
    // Local vars used to store and keep track of name/value pairs
    // as we parse them back into a usable form.
  while (query.indexOf('&') > -1) {
    keypairs[numKP] = query.substring(0,query.indexOf('&'));
    query = query.substring((query.indexOf('&')) + 1);
    numKP++;
      // Split the query string at each '&', storing the left-hand side
      // of the split in a new keypairs[] holder, and chopping the query
      // so that it gets the value of the right-hand string.
  }
  keypairs[numKP] = query;
    // Store what's left in the query string as the final keypairs[] data.<
  for (i in keypairs) {
    keyName = keypairs[i].substring(0,keypairs[i].indexOf('='));
      // Left of '=' is name.
    keyValue = keypairs[i].substring((keypairs[i].indexOf('=')) + 1);
      // Right of '=' is value.
    while (keyValue.indexOf('+') > -1) {
      keyValue = keyValue.substring(0,keyValue.indexOf('+')) + ' ' + keyValue.substring(keyValue.indexOf('+') + 1);
        // Replace each '+' in data string with a space.
    }
    keyValue = unescape(keyValue);
      // Unescape non-alphanumerics
    if (FORM_DATA[keyName]) {
      FORM_DATA[keyName] = FORM_DATA[keyName] + separator + keyValue;
        // Object already exists, it is probably a multi-select input,
        // and we need to generate a separator-delimited string
        // by appending to what we already have stored.
    } else {
      FORM_DATA[keyName] = keyValue;
        // Normal case: name gets value.
    }
  }
  return FORM_DATA;
}
