/* 
 * This is a legacy compatability file, one should call the plain js file instead.
 * Or better use gogoJavascript::js()->augment_form_localities(); 
 */

gogoLocality = {
  feed_url: '/__classpath/gogo/gogoLocalities/views/localities.js-php?Planet=Earth&Continent=*'
};

//:mode=javascript:
if(typeof gogoLocality == 'undefined')
{
  gogoLocality = {
    feed_url: '/__classpath/gogo/gogoLocalities/views/localities.js-php'
  }
}

gogoLocality.populate_select = function(Select, Country, Region, Province, alternateFirstOption)
{
  var data = {
    Planet: 'Earth',
    Continent: '*'
    
  }
    
  if(Country != null)
  {   
    data.Country = Country;
    if(Region != null)
    {
      data.Region = Region;   
      if(Province != null)
      {
        data.Province = Province;   
      }
    }
  }
    
  
  var isCountrySelect  = Country == null && Region == null && Province == null;
  
  var theSelect = Select;
  var selectedValue = theSelect.selectedIndex >= 0 ? theSelect.options[theSelect.selectedIndex].value : '';
  
  Gogo.postback(this.feed_url, data, function(jsToEval) 
    {      
      Gogo.emptySelect(theSelect);
      var  places = eval(jsToEval);
      var beenChanged = true;
      var setTo = -1;
            
      for(var x = 0; x < places.length; x++)
      {
        if(theSelect.localityFilter && !theSelect.localityFilter(places[x])) continue;
        
        if((theSelect.options.length == 0))// && isCountrySelect)  
        {          
          theSelect.options[theSelect.options.length] = alternateFirstOption ? alternateFirstOption : new Option('Please Select', '');
        }
        
        theSelect.options[theSelect.options.length] 
          = new Option(places[x], places[x], selectedValue == places[x], selectedValue == places[x]);
        if(selectedValue == places[x])
        {
          beenChanged = false;
          setTo = theSelect.options.length - 1;
        }
      }
      
      if(setTo > 0)
      {
        theSelect.selectedIndex = setTo;
      }
      
      if(typeof theSelect.beenRefilled == 'function')
      {
        theSelect.beenRefilled();  
      }
      if( (1 || beenChanged) && typeof theSelect.onchange == 'function') theSelect.onchange();

    }
  );
}


gogoLocality.implant_selects = function(countryInputName,regionInputName,provinceInputName,alternateFirstOptions)
{
  function nsy(inp)
  {
    if(inp.value) return inp.value;
    return 'None Selected Yet';
  }

  function make_select(countryInput, regionInput, provinceInput)
  { 
    // Already done?
    if(typeof countryInput.redrawLocalities != 'undefined') return;
    
    var countrySelect = document.createElement('select');
    var regionSelect = regionInput ? document.createElement('select') : null; 
    var provinceSelect = provinceInput ? document.createElement('select') : null;
    
    /* ************************************************************** */
    // =================== COUNTRY SELECT =============================
    
    // Hookup the localityFilter method of the input if it exixts
    //  this should accept a string and return true/false as to wether
    //  to include in the selector or not
    if(countryInput.localityFilter) countrySelect.localityFilter = countryInput.localityFilter;   
    
    // this method (of the original input field) takes the value presently
    // in the input field and draws the locality selectors, and updates
    // the subordinate locality selectors as well (ie change country, and districts change)
    countryInput.redrawLocalities = function()
    {
      for(var i = countrySelect.options.length -1; i >= 0; i--)
        countrySelect.options[i] = null;
      countrySelect.options[0] = new Option(countryInput.value, countryInput.value, true, true);
      gogoLocality.populate_select(countrySelect, null, null, null, alternateFirstOptions ? alternateFirstOptions.Country : null );
     
      //regionInput.redrawLocalities();
    }

    // update the original input when the selector gets changed, will
    // also cascade to subordinates through thier redrawLocalities() method
    countrySelect.onchange = function() 
      { 
        if(countrySelect.options.length)
        {
          var oldval = countryInput.value;
          countryInput.value = countrySelect.selectedIndex >= 0 ? countrySelect.options[countrySelect.selectedIndex].value : countrySelect.options[0].value; 
          if(countryInput.onchange && oldval != countryInput.value)
          {
            countryInput.onchange();
          }
        }
        
        if(regionInput) regionInput.redrawLocalities();                      
      }
    
    // tell the selector it has been filled, this will either hide or show
    // the original input, and itself, depending on if there are options
    // to be chosen from
    countrySelect.beenRefilled = function()
    {
      if(!this.options.length) 
      {
        this.style.display = 'none';
        countryInput.style.display = '';
        if(countryInput.type == 'hidden')
        {
          // If the field is hidden, they may only select a valid
          // value from the list, and there are none, so remove
          // any existing value
          countryInput.value = ''; 
        }
      }
      else
      {
        this.style.display = '';
        countryInput.style.display = 'none';
      }
    }
      
    countrySelect.style.display = (countryInput.type == 'hidden' ) ? '' : 'none';
    if(countryInput.value)
    {
      countrySelect.options[0] = new Option(countryInput.value, '');
    }
    else if(alternateFirstOptions)
    {
      countrySelect.options[0] = alternateFirstOptions.Country;
    }
    else
    {
      countrySelect.options[0] = new Option('Loading Countries', '');
    }
    countryInput.parentNode.insertBefore(countrySelect,countryInput);
    
    
    /* ************************************************************** */    
    // ===================== REGION SELECT =============================
    if(!regionInput) return;
    
    regionSelect.focused = regionInput.focused = false;
    regionSelect.onfocus = regionInput.onfocus = function() { this.focused = true; }
    regionSelect.onblur  = regionInput.onblur  = function() { this.focused = false; }
    
    
    
    // Hookup the localityFilter method of the input if it exixts
    //  this should accept a string and return true/false as to wether
    //  to include in the selector or not
    if(regionInput.localityFilter) regionSelect.localityFilter = regionInput.localityFilter;
       
    // this method (of the original input field) takes the value presently
    // in the input field and draws the locality selectors, and updates
    // the subordinate locality selectors as well (ie change country, and districts change)
    regionInput.redrawLocalities = function()
    {
      for(var i = regionSelect.options.length -1; i >= 0; i--)
        regionSelect.options[i] = null;
      regionSelect.options[0] = new Option(regionInput.value, regionInput.value, true, true);
      gogoLocality.populate_select(regionSelect, nsy(countryInput), null, null, alternateFirstOptions ? alternateFirstOptions.Region : null );
     
      //provinceInput.redrawLocalities();
    }
    
    // tell the selector it has been filled, this will either hide or show
    // the original input, and itself, depending on if there are options
    // to be chosen from
    regionSelect.beenRefilled = function()
    {
      if(!this.options.length) 
      {
        regionInput.style.display = '';
        if(regionInput.type == 'hidden')
        {
          // If the field is hidden, they may only select a valid
          // value from the list, and there are none, so remove
          // any existing value
          regionInput.value = '';
          
          if(alternateFirstOptions)
          {
            this.options[0] = alternateFirstOptions.Region;
            this.style.display = '';            
          }
          else
          {
            this.style.display = 'none';
          }          
        }
        else
        {
          this.style.display = 'none';          
        }
      }
      else
      {
        this.style.display = '';
        
        if(regionInput.focused) 
        { 
          regionInput.blur();
          regionSelect.focus();
        }
        
        regionInput.style.display = 'none';
      }
    }
        
    // update the original input when the selector gets changed, will
    // also cascade to subordinates through thier redrawLocalities() method
    regionSelect.onchange = function() 
    { 
      if(regionSelect.options.length)
      {
        if(!regionSelect.options.length) return;
        var oldval = regionInput.value;
        regionInput.value = regionSelect.selectedIndex >= 0 ? regionSelect.options[regionSelect.selectedIndex].value : regionSelect.options[0].value;
        if(regionInput.onchange && regionInput.value != oldval)
        {
          regionInput.onchange();
        }
      }
      
      if(provinceInput) provinceInput.redrawLocalities();        
    }
    
    regionSelect.style.display = (regionInput.type == 'hidden' ) ? '' : 'none';
    if(regionInput.value)
    {
      regionSelect.options[0] = new Option(regionInput.value, '');
    }
    else if(alternateFirstOptions)
    {
      regionSelect.options[0] = alternateFirstOptions.Region;
    }
    else
    {
      regionSelect.options[0] = new Option('Loading Regions', '');
    }
    regionInput.parentNode.insertBefore(regionSelect,regionInput);
    
    
    
    /* ************************************************************** */    
    // ===================== PROVINCE SELECT =============================
    if(!provinceInput) return;
    provinceSelect.focused = provinceInput.focused = false;
    provinceSelect.onfocus = provinceInput.onfocus = function() { this.focused = true; }
    provinceSelect.onblur  = provinceInput.onblur  = function() { this.focused = false; }
    
    
    // Hookup the localityFilter method of the input if it exixts
    //  this should accept a string and return true/false as to wether
    //  to include in the selector or not
    if(provinceInput.localityFilter) provinceSelect.localityFilter = provinceInput.localityFilter;
    
    // tell the selector it has been filled, this will either hide or show
    // the original input, and itself, depending on if there are options
    // to be chosen from
    provinceSelect.beenRefilled = function()
    {
      if(!this.options.length) 
      {
        provinceInput.style.display = '';
        if(provinceInput.type == 'hidden')
        {
          // If the field is hidden, they may only select a valid
          // value from the list, and there are none, so remove
          // any existing value
          provinceInput.value = '';
          
          if(alternateFirstOptions)
          {
            this.options[0] = alternateFirstOptions.Province;
            this.style.display = '';            
          }
          else
          {
            this.style.display = 'none';
          }          
        }
        else
        {
          this.style.display = 'none';          
        }
      }
      else
      {
        this.style.display = '';
        if(provinceInput.focused) 
        { 
          provinceInput.blur();
          provinceSelect.focus();
        }
        provinceInput.style.display = 'none';
      }
    }
    
    // this method (of the original input field) takes the value presently
    // in the input field and draws the locality selectors, and updates
    // the subordinate locality selectors as well (ie change country, and districts change)
    provinceInput.redrawLocalities = function()
    {
      for(var i = provinceSelect.options.length -1; i >= 0; i--)
        provinceSelect.options[i] = null;
      provinceSelect.options[0] = new Option(provinceInput.value, provinceInput.value, true, true);
      gogoLocality.populate_select(provinceSelect, nsy(countryInput), nsy(regionInput), null, alternateFirstOptions ? alternateFirstOptions.Province : null );
           
    }
    
    // update the original input when the selector gets changed, will
    // also cascade to subordinates through thier redrawLocalities() method
    provinceSelect.onchange = function() 
      { 
        if(!provinceSelect.options.length) return;
        var oldval = provinceInput.value;
        provinceInput.value = provinceSelect.selectedIndex >= 0 ? provinceSelect.options[provinceSelect.selectedIndex].value : ''; 
        if(provinceInput.onchange && oldval != provinceInput.value)
        {
          provinceInput.onchange();
        }
      }
    
    provinceSelect.style.display = (provinceInput.type == 'hidden' ) ? '' : 'none';
    if(provinceInput.value)
    {
      provinceSelect.options[0] = new Option(provinceInput.value, '');
    }
    else if(alternateFirstOptions)
    {
      provinceSelect.options[0] = alternateFirstOptions.Province;
    }
    else
    {
      provinceSelect.options[0] = new Option('Loading Provinces', '');
    }
    provinceInput.parentNode.insertBefore(provinceSelect,provinceInput);

    
    
    
    //countryInput.redrawLocalities();
  }
  
  
  make_select
  (
    typeof countryInputName == 'string' ? document.getElementsByName(countryInputName)[0] : countryInputName,
    regionInputName ? ( typeof regionInputName == 'string' ? document.getElementsByName(regionInputName)[0] : regionInputName) : null ,
    provinceInputName ? ( typeof provinceInputName == 'string' ? document.getElementsByName(provinceInputName)[0] : provinceInputName) : null 
  );  
  
  (typeof countryInputName == 'string' ? document.getElementsByName(countryInputName)[0] : countryInputName).redrawLocalities();
}   

/** Seek out likely sets of country, region, province and 
 *   turn them into selectors.
 */
 
gogoLocality.auto_implant_selects = function(form, alternateFirstOptions)
{
  if(!form)
  {
    var forms = document.getElementsByTagName('form');
    for(var x = 0; x < forms.length; x++)
    {      
      gogoLocality.auto_implant_selects(forms[x]);
    }      
    return;
  }
  
  // Find input elements
  var inputs = form.getElementsByTagName('input');
  
  // Look for countries
  for(var x = 0; x < inputs.length; x++)
  {
    if(inputs[x].name.match(/^(.*)Country(.*)$/))
    {
      var flds   = { country: inputs[x], region: null, province:null };
      var prefix = RegExp.$1;
      var suffix = RegExp.$2;
      // Found one, look for the matching region
      for(var i = x+1; i < inputs.length; i++)
      {
        if(inputs[i].name == (prefix + 'Region' + suffix))
        {
          flds.region = inputs[i];
          
          // Found, look for matching province
          for(var j = i+1; j < inputs.length; j++)
          {
            if(inputs[j].name == (prefix + 'Province' + suffix))
            {
              flds.province = inputs[j];
              // Found all three
              break;
              //gogoLocality.implant_selects(inputs[x].name, inputs[i].name, inputs[j].name, alternateFirstOptions);         
            }
          }
          break;
        }
      }
      
      // No matching region
      gogoLocality.implant_selects(flds.country, flds.region, flds.province, alternateFirstOptions);
    }
  }
  
}