/**
 * Righto - this basically replaces a <select> with an unordered list and a 
 * hidden input
 **/
var SelectReplacement = new Class({
  Implements:     Log,
  initialize:     function (id)
  {
    // Useful with Symfony - if we're on the dev env, use MooTools console.log
    // wrapper for stuff
    if($defined(ENV) && ENV == 'dev')
    {
      this.enableLog();
    }
    
    this.log('Creating new replacement for '+id);
    
    // Create a new list, and wrap everything in a div for ease of styling
    this.container  = new Element('div');
    this.list       = new Element('ul',{
      'id':     id+'-replacement',
      'class': 'closed'
    });
    
    // Part of MooTools.More, this handles opening/closing the select-replacement
    this.showHide = new Fx.Reveal(this.list,{
      'heightOverride':     250
    });
    
    // A few JS events bound to the tween, basically just changing the class
    // of the trigger button on show, hide and start so we can style it
    // accordingly
    this.showHide.addEvents({
      'onShow': function ()
      {
        this.trigger.addClass('open');
      }.bind(this),
      'onHide': function ()
      {
        this.list.set('class','closed');
      }.bindWithEvent(this),
      'onStart': function ()
      {
        this.trigger.removeClass('open');
        this.list.set('class','open');
      }.bindWithEvent(this)
    });

    // Loop through each option, creating a new list item containing a link
    $(id).getElements('option').each(
      function (opt)
      {
        li = new Element('li',{ 'class': opt.get('value') }).adopt(
          new Element('a', {
            'text':   opt.get('text'),
            'href':   '#'+opt.get('value')
          })
        );
        li.addEvents({
          'mouseenter':     function ()
          {
            this.addClass('mouse-over');
          },
          'mouseleave':     function ()
          {
            this.removeClass('mouse-over');
          },
          'click':          this.changeSelection.bindWithEvent(this)
        });
        this.list.adopt(li);

        if(opt.get('selected'))
        {
          // Creat the trigger and a hidden field with the same attributes as
          // the select (since it'll replace it)
          this.trigger      = new Element('a',{ text: opt.get('text'), href: '#', 'class': 'trigger' });
          this.hiddenInput  = new Element('input', { type: 'hidden', value: opt.get('value'), id: id, name: $(id).get('name') });
          li.addClass('selected');
        }
      }.bind(this)
    );

    this.trigger.addEvent('click', this.triggered.bindWithEvent(this));

    // This is a catch-all click event on the body, so if you click anywhere
    // on the page, the select will collapse as a native select widget would
    $(document.body).addEvent('click',function ()
    {
      this.showHide.dissolve();
    }.bind(this));

    this.container.adopt(this.hiddenInput, this.trigger, this.list);
    this.container.replaces($(id));
  },
  
  /**
   * Fired when the trigger is clicked to expand the select
   **/
  triggered:        function (ev)
  {
    if(ev)
    {
      ev.preventDefault();
      ev.stop();
    }
    this.showHide.toggle();
  },
  
  /**
   * When the user clicks an item in the list, set the form value and collapse
   * the form
   **/
  changeSelection:  function (ev)
  {
    if(ev)
    {
      ev.preventDefault();
      ev.stop();
    }
    this.showHide.dissolve();
    
    fauxUri = new URI($(ev.target).get('href'));
    newCountryCode = fauxUri.get('fragment');

    this.log(newCountryCode);
    
    newCountryName = $(ev.target).get('text');

    this.hiddenInput.set('value',newCountryCode);
    this.trigger.set('text',newCountryName);
    this.log("Setting new country selection to " + newCountryName + " ("+newCountryCode+")");
  }

});

var CheckboxReplacement = new Class({
  Implements:     Log,
  checkbox:       false,
  image:          false,
  anchor:         false,
  initialize:     function (id)
  {
    // Useful with Symfony - if we're on the dev env, use MooTools console.log
    // wrapper for stuff
    if($defined(ENV) && ENV == 'dev')
    {
      this.enableLog();
    }
    
    this.log('Creating new replacement for '+id);
    
    $(id).setStyle('display','none');
    
    this.checkbox = $(id);
    
    if(this.checkbox.checked)
      this.log("Checkbox is already checked");
    else
      this.log("Checkbox is not checked");
    
    src = this.checkbox.checked ? '/images/checkbox.on.png' : '/images/checkbox.png';
    
    this.image    = new Element('img',{ src:  src});
    this.anchor   = new Element('a',{
      'href':       '#',
      'events':     {
        'click':    function (ev)
        {
          if(ev)
          {
            ev.preventDefault();
          }
          this.checkbox.checked = !this.checkbox.checked;
          newSrc = this.checkbox.checked ? '/images/checkbox.on.png' : '/images/checkbox.png';
          this.image.set('src',newSrc);
        }.bindWithEvent(this)
      }
    });
    
    $(id).getParent().adopt(this.anchor.adopt(this.image));
    
  }
});

var verifyForm = function ()
{
  // Set the body's opacity to 0 as soon as the page is ready, then we'll
  // fade it in on-load
  $('container').fade('hide');

  //countrySelect = new SelectReplacement('age_country_code');
  rememberMe    = new CheckboxReplacement('age_remember_me');
  
  pos = {
    'padding-top':  '2px'
  };
  new OverText($('age_date_of_birth_day'),{
    'element':          'span',
    'textOverride':     MooTools.lang.get('Verify','dd'),
    'positionOptions':  pos
  });
  new OverText($('age_date_of_birth_month'),{
    'element':          'span',
    'textOverride':     MooTools.lang.get('Verify','mm'),
    'positionOptions':  pos
  });
  new OverText($('age_date_of_birth_year'),{
    'element':          'span',
    'textOverride':     MooTools.lang.get('Verify','yyyy'),
    'positionOptions':  pos
  });
};

var checkFlash = function ()
{
  if( Browser.Plugins.Flash.version > 9 ) {
    return true;
  }
  else if( Browser.Plugins.Flash.version == 9 && Browser.Plugins.Flash.build > 115 ) {
    return true;
  }
  else{
    return false;
  }
};

window.addEvents({
  'domready':   function() {
    verifyForm();
    var hasFlash = checkFlash() ? 1 : 0;
    $('age_hasFlash').set('value', hasFlash);
  },
  'load':       function ()
  {
    $('container').fade('in');
  }
});

