/**
 *Author: FTDeBUGGeR
 **/

$.fn.position = function(position)
{
  return function(absolute)
  {
    if(absolute === true)
    {
      var p, e = this[0];
      if(e)
      {
        p = position.call(this);
        while(e = e.offsetParent)
        {
          try
          {
            with(position.call($(e)))
            {
              p.left += left;
              p.top += top;
            }
          }
          catch(e){}
        }
      }
    }
    else
    {
      var p = position.apply(this, arguments);
    }

    if(p)
    {
      p.x = p.left;
      p.y = p.top;
    };

    return p
  }
}($.fn.position);


var cDropBox = function(select, change)
{
  var Object = {
    select: select, 
    change: change
  };
  Object.options = {};

  Object.setActive = function(id)
  {
    this.box.text( this.options[id] );
    this.hidden.val( id );

    if ( typeof this.change == "function" )
    {
      this.change();
    }
  }

  Object.toggle = function(toggle)
  {
    if (toggle)
    {
      this.popup.toggle();
    }
    
    this.wrapper.removeClass('disable');

    if( this.popup.css("display") == "none" )
    {
      this.wrapper.addClass('disable');
    }
  }

  Object.init = function()
  {
    var me = this;

    this.name = $(this.select).attr('name');
    this.value = $(this.select).val();

    this.wrapper = $('<div class="selectbox-wrapper disable"></div>');
    this.box = $('<a href="#"></a>');
    this.boxWrapper = $('<div class="selectbox-box"></div>').append(this.box);
    this.popup = $('<ul class="selectbox-popup"></ul>').hide();
    this.hidden = $('<input type="hidden" />').attr("name", this.name).val(this.value);

    $("option", this.select).each(function(){
      var value = $(this).attr("value");
      var text = $(this).text();

      var link = $('<a href="#"></a>').html('<span>' + text + '</span>').click(function(e){
        this.object.setActive(this.value);
        this.object.popup.hide();
        this.object.toggle(false);
        
        return false;
      });

      link.get(0).value = value;
      link.get(0).object = me;

      me.popup.append( $('<li></li>').append(link) );
      me.options[value] = text;
    });

    this.box.text( this.options[ this.value ] );

    this.wrapper.append(this.boxWrapper).append(this.popup).append(this.hidden);

    this.select.after(this.wrapper);

    this.select.hide();

    this.box.click(function()
    {
      me.toggle(true);
      $(this).blur();
      return false;
    });

    $().click(function(){
      me.popup.hide();
      me.toggle(false);
    });
  };

  return Object;
};

function DropBox(select)
{
  var Box = new cDropBox(select);
  Box.init();
}


