YAHOO.namespace('lister');

if ('function' != typeof YAHOO.lister.proof)
{
  YAHOO.lister.proof = function (text)
  {
    var proof       = document.createElement("h1");
    proof.innerHTML = text;

    document.body.appendChild(proof);
  };
}

YAHOO.lister = function ()
{
  /*
  ** ******************************************************************
  ** private variables available only to methods of the module.
  */

  /*
  ** private shorthand variables to comon YUI parts/utilities
  */
  var Yue   = YAHOO.util.Event,
      Elem  = YAHOO.util.Element,
      Dom   = YAHOO.util.Dom;
  /*
  ** private shorthand variable for built YUI objects. set in init(), or
  ** elsewhere.
  */
  var proof  = YAHOO.lister.proof; // YAHOO.lister.proof();

  /*
  ** module state:
  */
  var listerVariables = false,
      initialLoad     = true,
      category	      = '',
      state	      = '',
      county	      = '',
      township	      = '',
      agent	      = '',
      list	      = [];

  /*
  ** these are Dom refrences that won't change, they are set by direct
  ** calls when needed, and then used freely after that.
  */
  var form	  = '',
      save	  = '',
      categories  = '',
      states	  = '',
      counties	  = '',
      townships	  = '',
      agents	  = '';
  /*
  ** private method setListerVariables to be run once.  Access is
  **    protected by private variable listerVariables, but for more
  **    speed, test variable directly with if -- although it will only
  **    save you one function call:
  **
  **    if (!listerVariables)
  **    {
  **      setListerVariables();
  **    }
  */
  var setListerVariables = function ()
  {
    if (!listerVariables)
    {
      if (!(form = Dom.get('form')))
      {
	alert('Form Element not found.');
      }
      if (!(save = Dom.get('but_save')))
      {
	alert('Save Button not found.');
      }
      if (!(categories = Dom.get('sel_category')))
      {
	alert('Category Select not found.');
      }
      if (!(states = Dom.get('state_sel')))
      {
	alert('Region Select not found.');
      }
      if (!(counties = Dom.get('county_sel')))
      {
	alert('Town Select not found.');
      }
      if (!(townships = Dom.get('js_town')))
      {
	alert('Hidden Township Select not found.');
      }
      if (!(agents = Dom.get('realator_sel')))
      {
	alert('Agent Select not found.');
      }
      listerVariables = true;
    }
  };

  /*
  ** private method trim() trims an element's innerHTML to nothing.
  */
  var trim = function (id)
  {
    proof('trim');
    var elem = Dom.get(id);

    if (elem)
    {
      if ('SCRIPT' == elem.tagName)
      {
	/*
	** evil IE6 balks at deleting innerHTML from script tags.
	** so we just insert a new tag with same id in place.
	*/
	var parent = new Elem(elem.parentNode.id);
	var script = document.createElement('SCRIPT');

	parent.replaceChild(script, elem);

	script.id = id;
      }
      else
      {
	elem.innerHTML = '';
      }
    }
  };

  /*
  ** private method match() finds a select element's option that matches the
  **			    passed value
  */
  var match = function (which, val)
  {
    proof('match :: matching [' + which.id + '] on val [' + val + ']');
    var opt = 0;

    while (opt < which.options.length)
    {
      proof('match :: opt is [' + opt + '] val is [' +
	    which.options[opt].value + ']');

      if (val == which.options[opt].value)
      {
	proof('match :: val found!');

	which.selectedIndex = opt;
	break;
      }
      ++opt;
    }
  };

  /*
  ** private method fillLocations builds Region Town Dropdowns and sets up
  ** the event listeners for the lister dropdowns..
  */
  var fillLocations = function ()
  {
    proof('fillLocations');
    fillStates();

    initialLoad = true; // true means don't reset county by state selection

    match(categories, category);
    match(states,     state);
    changeState();
    
    initialLoad = false;
  };

  /*
  ** private method fillStates builds Region Dropdown.
  */
  var fillStates = function ()
  {
    proof('fillStates');
    trim(states);

    if (list)
    {
      var opt = null;

      for (opt in list)
      {
	var option	  = document.createElement('OPTION');
	option.value	  = list[opt][1];
	option.innerHTML  =
	  option.label	  = list[opt][0];

	if (state == list[opt][1])
	{
	  option.selected = 'selected';
	}
	states.appendChild(option);
      }
    }
  };

  /*
  ** private method fillCounties  builds Town Dropdown (visible but acutally
  **				  the county).
  */
  var fillCounties = function (countyList)
  {
    proof('fillCounties :: list = [' + countyList + ']');
    trim(counties);

    if (countyList)
    {
      var opt = null;

      for (opt in countyList)
      {
	var option			= document.createElement('OPTION');
	option.value			= countyList[opt][1];
	option.innerHTML = option.label = countyList[opt][0];

	if (county == countyList[opt][1])
	{
	  option.selected = 'selected';
	}
	counties.appendChild(option);
      }
    }
  };

  /*
  ** private method fillTownships builds Township Dropdown (invisible but
  **				  used in database searches).
  */
  var fillTownships = function (townList)
  {
    proof('fillTownships :: list = [' + townList + ']');
    trim(townships);

    if (townList)
    {
      var opt = null;

      for (opt in townList)
      {
	var option			= document.createElement('OPTION');
	option.value			= townList[opt][1];
	option.innerHTML = option.label = townList[opt][0];

	if (county == townList[opt][1])
	{
	  option.selected = 'selected';
	}
	townships.appendChild(option);
      }
    }
  };

  /*
  ** private method changeState	Event (select-states-changed) callback that
  **				populates counties and townships.
  */
  var changeState = function ()
  {
    proof('changeState');
    state = states.options[states.selectedIndex].value;

    trim(counties);
    fillCounties(list[states.selectedIndex][2]);

    if (initialLoad)
    {
      match(counties, county);
    }
    changeCounty();
  };

  /*
  ** private method changeCounty  Event (select-counties-changed) callback 
  **				  that populates townships.
  */
  var changeCounty = function ()
  {
    proof('changeCounty');
    county = counties.options[counties.selectedIndex].value;

    trim(townships);
    fillTownships(list[states.selectedIndex][2][counties.selectedIndex][2]);

    if (townships.options.length)
    {
      township = townships.options[townships.selectedIndex].value;
    }
    counties.disabled = false;

    if ((!state) || (0 == state))
    {
      counties.disabled = true;
    }
  };

  var check = function ()
  {
    proof('check');
    var val_agent   = agents.options[agents.selectedIndex].value,
	val_state   = states.options[states.selectedIndex].value,
	val_county  = counties.options[counties.selectedIndex].value;

    if ((!val_agent) || (0 == val_agent))
    {
      proof('check :: no agent');
      alert('You must Choose an agent for the property.');
    }
    else if ((!val_state) || (0 == val_state))
    {
      proof('check :: no state');
      alert('You must Choose a region for this property.'); // never?
    }
    else if ((!val_county) || (0 == val_county))
    {
      proof('check :: no county');
      alert('You must Choose a town for this property.');
    }
    else
    {
      form.submit();
      return true;
    }
    return false;
  };


  var that =
    {
      dataList: [],

      init: function (e, unknown, args)
      {
	list	  = YAHOO.lister.dataList;
	category  = args['category'] || 0;
	state	  = args['state']    || 0;
	county	  = args['county']   || 0;
	township  = args['township'] || 0;

	proof('init');
	setListerVariables();
	fillLocations();
	Yue.on(states.id,   'change', changeState);
	Yue.on(counties.id, 'change', changeCounty);
	Yue.on(save.id,	    'click',  check);
      }
    };

  return that;
}();
