/*
// automate common address stuff.
*/

/*
// get zones based on country id
*/
ZoneLookup = Class.create();
ZoneLookup.cache = {};
ZoneLookup.loading = {};
ZoneLookup.objects = new Array();
ZoneLookup.prototype = {
  initialize: function(country,zoneInput,zoneSelect,options) {
    this.options = {
      preload: false,
      selectedZone: false,
      debugOutput: false,
      zoneId: 'zone_id'
    };
    this.useCountries = new Array(38,223,'USA','CAN');
    this.lastSelected = {};
    Object.extend(this.options, options || {});

    this.country    = $(country);
    this.zoneInput  = $(zoneInput);
    this.zoneSelect = $(zoneSelect);
    if (!(this.country && this.zoneInput && this.zoneSelect)) {
      alert('could not get some of the elements!');
    }
    this.request    = false;
    this.waiting    = false;
    this.id         = ZoneLookup.objects.length;
    ZoneLookup.objects[this.id] = this;

    Event.observe(this.country,'change',this.onCountryChange.bind(this));
    Event.observe(this.zoneSelect,'change',this.onZoneChange.bind(this));

    /* if zone box is empty, force a preload */
    if (this.zoneSelect.options.length == 0) {
      this.options.preload = true;
    }

    /* if we should look up zones right away */
    if (this.options.preload) {
      this.onCountryChange();
    }
    /* show the right input */
    this.country_id = $F(this.country);
    this.showInput(true);
  },
  onZoneChange: function() {
    this.lastSelected[this.country.value] = this.zoneSelect.options[this.zoneSelect.selectedIndex].value;
    this.zoneInput.value = this.zoneSelect.options[this.zoneSelect.selectedIndex].name;
  },
  onCountryChange: function() {
    var cid = $F(this.country);
    this.country_id = cid;
    // first, disable the zone form elements
    var zsel = this.zoneSelect;
    var zinp = this.zoneInput;
    zsel.disabled = 1;
    zinp.disabled = 1;
    
    if (this.useCountries.include(cid)) {
      zsel.options.length = 1;
      //zsel.options[0] = new Option('Loading...',0);
      this.showInput(true);
      this.waiting = true;
      if (ZoneLookup.loading[cid]) {
        this.debug("country "+cid+" is loading; zones will be filled in when request completes");
        // it will be filled in when the request completes
        return;
      }
      if (ZoneLookup.cache[cid]) {
        this.debug("populating from cache");
        this.populate(ZoneLookup.cache[cid]);
        return;
      }
      this.lookupZone(cid);
    } else {
      this.showInput(true);
      this.debug("Using text field for country "+cid);
      // this one just uses the text field method
    }
  },
  showInput: function(enable) {
    var cid = this.country_id;
    var good;
    var bad;
    if (this.useCountries.include(cid)) {
      good = this.zoneSelect;
      bad  = this.zoneInput;
    } else {
      good = this.zoneInput;
      bad  = this.zoneSelect;
    }
    Element.show(good);
    Element.hide(bad);
    bad.disabled = 1;
    if (enable) {
      good.disabled = '';
    }
  },
  lookupZone: function(cid) {
    ZoneLookup.loading[cid] = 1;
    this.debug("looking up country "+cid);
    var opt = {
      method: 'GET',
      onSuccess: this.responseHandler.bind(this),
      onFailure: function(t) {
        alert("Some Error Looking up Zones for Country ["+cid+"]");
      }
    };
    this.request = new Ajax.Request('/xml/index.php?action=zone&country='+cid,opt);
  },
  populate: function(json) {
    var zsel = this.zoneSelect;
    var zinp = this.zoneInput;
    var selZone = this.options.selectedZone;
    zinp.value = '';
    this.debug("populating options");
    this.waiting = 0;
    zsel.options.length = 1;
    //zsel.options[0] = new Option('-- choose --','0');
    for (var i = 0; i < json.length; i++) {
      var j = zsel.options.length;
      zsel.options[j] = new Option(json[i].zone_name,json[i].zone_id);
      if (selZone && (selZone == json[i].zone_code || selZone == json[i].zone_id)) {
        zsel.selectedIndex = j;
        this.options.selectedZone = false;
        selZone = false;
      }
    }
    zsel.disabled = false;
  },
  responseHandler: function(t,json) {
    var cid = json[0].req_country;
    this.debug("response handler called. country="+cid);
    ZoneLookup.cache[cid] = json;
    ZoneLookup.loading[cid] = 0;
    var objs = ZoneLookup.objects;
    var found = 0;
    for (var i = 0; i < objs.length; i++) {
      var zl = objs[i];
      if (zl.waiting && (zl.country_id == cid)) {
        zl.populate(json);
        zl.showInput(true);
        found++;
      }
    }
    this.request = false;
  },
  debug: function(str) {
    var o = this.options.debugOutput;
    if (!o) return;
    o.innerHTML += "<br><b>"+this.id+"</b>: "+str;
  }
};

ZipLookup = Class.create();
ZipLookup.prototype = {
  initialize: function(zip,city,state) {
    this.zip = $(zip);
    this.city = $(city);
    this.state = $(state);
    this.busy = 0;
    Event.observe(this.zip,'change',this.lookup.bind(this));
  },
  lookup: function() {
    var z = this.zip.value;
    if (z.length >= 5) {
      z = z.substring(0,5);
    }
    var opt = {
      method: 'get',
      onSuccess: this.responseHandler.bind(this),
      onFailure: this.fail.bind(this)
    };
    this.req = new Ajax.Request('/xml/index.php?action=zip&zip='+z,opt);
  },
  fail: function() {
    this.busy = 0;
  },
  responseHandler: function(t,json) {
    if (json.zip) {
      this.city.value = json.city;
      var st = json.zone_id;
      var stab = json.zone_code;
      var valstr = '';
      for (var i = 0; i < this.state.options.length; i++) {
        var o = this.state.options[i];
        valstr += o.value + ', ';
        if ((i % 10) == 0) valstr += '\n';
        if (o.value == st || o.value == stab) {
          this.state.selectedIndex = i;
          break;
        }
      }
    }
  }
};
