var _checkbox_counter = 0;

var Checkbox = $.klass({
  
  initialize: function(checkbox, options)
    {
    this.checkbox = $(checkbox);
    this.options = $.extend({
      className:  "check_box",
      base_id: "check_box_"
      }, options);
    
    this.id = this.options.base_id + _checkbox_counter;
    
    this.checked = this.checkbox.get(0).checked;
    this.value = this.checkbox.attr("value");
    
    value = (this.checked)? this.checkbox.attr("value") : "";
    checked = (this.checked)? ' checked' : '';
    
    this.checkbox.after('<a class="'+ this.options.className + checked +'" id="'+ this.id +'_altbox" href="#"></a>');
    this.checkbox.after('<input type="hidden" name="'+ this.checkbox.attr("name") +'" value="'+ value +'" class="checkbox '+ this.id +'" />');
    
    this.checkbox.remove();
    this.altbox = $("#"+ this.id + "_altbox");
    this.input = $("input.checkbox."+ this.id + "[type=hidden]");
    
    if(this.altbox.parent("label").length > 0)
      {
      this.label = this.altbox.parent("label");
      this.label.disableSelection();
      this.apply_events(this.altbox.parent("label"));
      this.altbox.parent("label").css({ cursor: "pointer" });
      if(this.checked) this.label.addClass("checked");
      }
    else
      {
      this.apply_events(this.altbox);
      }
    
    _checkbox_counter++;
    },
  
  apply_events: function(element)
    {
    element.bind("click", this, function(e){
      e.data.toggle.apply(e.data, [e]);
      });

    element.bind("mouseenter", this, function(e){
      e.data.enter.apply(e.data, [e]);
      });

    element.bind("mouseleave", this, function(e){
      e.data.leave.apply(e.data, [e]);
      });
    },
  
  toggle: function(e)
    {
    e.preventDefault();
    
    if(this.checked) this.uncheck();
    else this.check();
    
    (this.options.onToggle || function(){}).apply(this, [e]);
    },
  
  check: function()
    {
    this.input.val(this.value);
    this.altbox.addClass("checked");
    if(this.label) this.label.addClass("checked");
    this.checked = true;
    },
  
  uncheck: function()
    {
    this.input.val("");
    this.altbox.removeClass("checked");
    if(this.label) this.label.removeClass("checked");
    this.checked = false;
    },
  
  enter: function()
    {
    this.altbox.addClass("hover");
    },
  
  leave: function()
    {
    this.altbox.removeClass("hover");
    }
  
  });
