/* form-elements.js
 * John Hughes, 04/10/2007
 */
 
CountryControl = Class.create();
CountryControl.prototype = {
  initialize: function(name, phoneName, interPhoneName) {
    this.name = name;
    this.countrySelect = $(name + '-country-select');
    this.provinceSelect = $(name + '-province-select');
    
    this.phoneFormElement = $(phoneName + '-form-element');
    this.interPhoneFormElement = $(interPhoneName + '-form-element');
    
    Element.observe(this.countrySelect, 'change', this.onCountryChange.bindAsEventListener(this));
  },
  setCountries: function(countries) { this.countries = countries; },
  onCountryChange: function(event) { this.countryChange(this.countrySelect.value); },
  countryChange: function(value, selected_province) {
    animate = (selected_province==null); // Only highlight when the user changes countries, not on page load

    // Repopulate the provinces dropdown.
    this.countries.each(function(country) {
      if(country.ABBR == value) {
        this.provinceSelect.options.length = 0; // Clear the select
        country.PROVINCES.each(function(value) {
          option = new Element('option');
          option.value = value.ABBR;
          option.text = value.NAME;
          if(value.ABBR == selected_province)
            option.selected = true;
            
          try {
            this.provinceSelect.add(option, null); // Standards compliant add
          } catch(e) {
            this.provinceSelect.add(option); // IE-only add
          }
        }.bind(this));
      }
    }.bind(this));
    
    if(animate)
      new Effect.Highlight(this.provinceSelect, {queue: {position: 'end', scope: 'global', limit: 1}});
      
    if(value != 'CA' && value != 'US') { // Other country
      if(this.phoneFormElement.visible()) {
        this.phoneFormElement.hide();
        
        if(animate)
          new Effect.SlideDown(this.interPhoneFormElement, {duration: 0.5});
        else
          this.interPhoneFormElement.show();
      }
    } else if(Element.visible(this.interPhoneFormElement)) {
      this.interPhoneFormElement.hide();
      
      if(animate)
        new Effect.SlideDown(this.phoneFormElement, {duration: 0.5});
      else
        this.phoneFormElement.show();
    }
  }
};

AffiliateChecker = Class.create();
AffiliateChecker.prototype = {
  initialize: function(name) {
    this.name = name;
    this.input = $(name + '-field');
    this.spinner = $(name + '-spinner');
    this.undertext = $(name + '-undertext');
    this.button = $(name + '-checkbutton');
    
    this.errorcolor = "#ffcccc";
    this.okcolor = "#ccffcc";
    this.methodurl = '/components/controller/MappingController.cfc';
    this.methodname = 'checkAffiliateCode';
    this.duration = 0.2;
    
    Element.observe(this.button, 'click', this.onButtonCheck.bindAsEventListener(this));
    Element.observe(this.input, 'click', this.reset.bindAsEventListener(this));
  },
  onButtonCheck: function(event) {
    this.button.disable();
    this.spinner.show();
    this.checkAffiliate(this.input.value);
  },
  reset: function() {
    Effect.BlindUp(this.undertext, {duration: this.duration});
    this.input.setStyle({backgroundColor: "#ffffff"});
    this.button.enable();
  },
  startCheck: function() {
  },
  doneCheck: function(response) {
    resp = dpWDDX("deserialize", response.strip().replace(/\r|\n/g, ''));
    
    if(resp['NOTFOUND']) {
      new Effect.Highlight(this.input, {startcolor: "#ffffff", endcolor: this.errorcolor, restorecolor: this.errorcolor, duration: this.duration});
      this.undertext.update("Affiliate code not found!");
      Effect.BlindDown(this.undertext, {duration: this.duration});
    } else {
      new Effect.Highlight(this.input, {startcolor: "#ffffff", endcolor: this.okcolor, restorecolor: this.okcolor, duration: this.duration});
      this.undertext.update("Affiliate found: " + resp['NAME']);
      if(resp['LOGO'] && resp['LOGO'] != "") {
        banner = new Element('img', {src: resp['LOGO'], title: resp['NAME'], alt: "Banner"});
        banner.setStyle({'float': 'left', marginTop: '10px'});
        this.undertext.insert(banner);
      }
      Effect.BlindDown(this.undertext, {duration: this.duration});
    }
    this.spinner.hide();
    this.input.enable();
  },
  checkAffiliate: function(affiliate_code) {
    new Ajax.Request(
      this.methodurl, {
        method: 'get',
        parameters: { method: this.methodname, code: affiliate_code },
        onLoading: function() { this.startCheck(); }.bind(this),
        onSuccess: function(transport) { this.doneCheck(transport.responseText); }.bind(this)
      });
  }
};

UsernameChecker = Class.create();
UsernameChecker.prototype = {
  initialize: function(name) {
    this.name = name;
    this.input = $(name + '-field');
    this.button = $(name + '-checkbutton');
    this.spinner = $(name + '-spinner');
    this.undertext = $(name + '-undertext');

    this.errorcolor = "#ffcccc";
    this.okcolor = "#ccffcc";
    this.methodurl = '/components/ddbBridge.cfc';
    this.methodname = 'checkUsername';
    this.duration = 0.2;
    
    Element.observe(this.button, 'click', this.checkUsername.bindAsEventListener(this));
    Element.observe(this.input, 'click', this.reset.bindAsEventListener(this));
  },
  reset: function() {
    Effect.BlindUp(this.undertext, {duration: this.duration});
    this.input.setStyle({backgroundColor: "#ffffff"});
    this.button.enable();
  },
  startCheck: function() {
    this.spinner.show();
    this.button.disable();
    this.input.disable();
  },
  doneCheck: function(response) {
    this.spinner.hide();
    //if(response.strip().replace(/\r|\n/g, '').substr(0,5).match(/true/)) {
    if(response.strip().replace(/\r|\n/g, '').match(/true/)) {
      new Effect.Highlight(this.input, {startcolor: "#ffffff", endcolor: this.okcolor, restorecolor: this.okcolor, duration: this.duration});
      this.undertext.innerHTML = "Username ok!";
      Effect.BlindDown(this.undertext, {duration: this.duration});
    } else {
      new Effect.Highlight(this.input, {startcolor: "#ffffff", endcolor: this.errorcolor, restorecolor: this.errorcolor, duration: this.duration});
      this.undertext.innerHTML = "Username taken or invalid!";
      Effect.BlindDown(this.undertext, {duration: this.duration});
    }
    this.input.enable();
  },
  checkUsername: function() {
    new Ajax.Request(
      this.methodurl, {
        method: 'get',
        parameters: { method: this.methodname, username: this.input.value },
        onLoading: function() { this.startCheck(); }.bind(this),
        onSuccess: function(transport) { this.doneCheck(transport.responseText); }.bind(this)
      });
  }
};

CompoundPhone = Class.create();
CompoundPhone.prototype = {
  initialize: function(name) {
    this.name = name;
    this.areacode = $(name + '-areacode');
    this.number = $(name + '-number');
    this.extension = $(name + '-extension');
    
    Event.observe(this.areacode, 'keypress', this.onAreacodeKeyPress.bindAsEventListener(this));
    Event.observe(this.number, 'keypress', this.onNumberKeyPress.bindAsEventListener(this));
    Event.observe(this.extension, 'keypress', this.onExtensionKeyPress.bindAsEventListener(this));
  },
  onAreacodeKeyPress: function(event) {
    chars = event.element().value.length;
    if(event.keyCode != Event.KEY_BACKSPACE &&
       event.keyCode != Event.KEY_DELETE &&
       event.element().value.length >= 3)
      this.number.focus();
  },
  onNumberKeyPress: function(event) {
    chars = event.element().value.length;
    if(event.keyCode == Event.KEY_BACKSPACE) {
      if(chars==0) {
        this.areacode.focus();
        this.setCursorToEnd(this.areacode); // For IE
      }
    } else if( event.keyCode != Event.KEY_DELETE && chars >= 7)
      this.extension.focus();
  },
  onExtensionKeyPress: function(event) {
    chars = event.element().value.length;
    if(event.keyCode == Event.KEY_BACKSPACE) {
      if(chars==0) {
        this.number.focus();
        this.setCursorToEnd(this.number);
      }
    }
  },
  setCursorToEnd: function(element) { // Move carat to the end position for IE
    try {
      t = element.createTextRange();
      t.move('character',element.value.length), t.moveEnd('character', element.value.length), t.select();
    } catch(e) {}
  }
};

TextFieldWithExample = Class.create();
TextFieldWithExample.prototype = {
  initialize: function(inputElementId, defaultText, options) {
    this.setOptions(options);
    this.input = $(inputElementId);
    this.name = this.input.name;
    this.defaultText = defaultText;
    this.createHiddenInput();
    this.checkAndShowExample();

    Event.observe(this.input, "blur", this.onBlur.bindAsEventListener(this));
    Event.observe(this.input, "focus", this.onFocus.bindAsEventListener(this));
    Event.observe(this.input, "select", this.onFocus.bindAsEventListener(this));
    Event.observe(this.input, "keydown", this.onKeyPress.bindAsEventListener(this));
    Event.observe(this.input, "click", this.onClick.bindAsEventListener(this));
  },

  createHiddenInput: function() {
    this.hiddenInput = document.createElement("input");
    this.hiddenInput.type = "hidden";
    this.hiddenInput.value = "";
    this.input.parentNode.appendChild(this.hiddenInput);
  },

  setOptions: function(options) {
    this.options = { exampleClassName: 'example' };
    Object.extend(this.options, options || {});
  },

  onKeyPress: function(event) {
    if (!event) var event = window.event;
    var code = (event.which) ? event.which : event.keyCode
    if (this.isAlphanumeric(code)) {
      this.removeExample();
    }
  },

  onBlur: function(event) { this.checkAndShowExample(); },
  onFocus: function(event) {
    if (this.exampleShown())
      this.removeExample();
  },

  onClick: function(event) { this.removeExample(); },

  isAlphanumeric: function(keyCode) { return keyCode >= 40 && keyCode <= 90; },

  checkAndShowExample: function() {
    if (this.input.value == '') {
      this.input.value = this.defaultText;
      this.input.name = '';
      this.hiddenInput.name = this.name;
      Element.addClassName(this.input, this.options.exampleClassName);
    }
  },

  removeExample: function() {
    if (this.exampleShown()) {
      this.input.value = '';
      this.input.name = this.name;
      this.hiddenInput.name = null;
      Element.removeClassName(this.input, this.options.exampleClassName);
    }
  },

  exampleShown: function() {
    return Element.hasClassName(this.input, this.options.exampleClassName);
  }
}