(function($){
  $.fn.switcher = function(options){

    var opts = $.extend({}, $.fn.switcher.defaults, options);

    return this.each(function(){
      var $this = $(this), self = this;
      this.allUsers = $('.all', $this.prev('.b-members-count')).find('span');
      this.friendUsers = $('.friend', $this.prev('.b-members-count')).find('span');
      this.state = 0;
      this.opts = opts;
      this.inputs = $('input', this);
      this.bg = $('.bg', this);
      this.leftItem = $('.bg .l', this);
      this.rightItem = $('.bg .r', this);
      this.knob = initKnob();
      if(opts.type == 'event') {
        this.objId = $this.attr('name').replace('event_', '');
        this.count = $this.prev();
      }
      $.fn.switcher.setWidth(this);
      $.fn.switcher.getState(this);
      $.fn.switcher.setState(this);


      this.knob.bind('dragstop', function(e, ui){
        if(opts.enabled) {
          $.fn.switcher.stopSwitch(self, e, ui);
        }
      });
      this.knob.bind('drag', function(e, ui){
        if(opts.enabled) {
          $.fn.switcher.dragSwitch(self, e, ui);
        }
      });
      this.knob.bind('click', function(){
        if(opts.enabled) {
          (self.state) ? $.fn.switcher.toRight(self) : $.fn.switcher.toLeft(self);
          $.fn.switcher.sendAjax(self);
        }
        return false;
      });


      if(opts.disabled) {
        disable();
      }

      function enable(){
        opts.enabled = true;
        $this.removeClass('b-switcher-disabled');
        initKnob();
      }

      function disable(){
        opts.enabled = false;
        $this.addClass('b-switcher-disabled');
        destroyKnob();
      }

      function initKnob() {
        return $('.knob', self).draggable({ containment: 'parent',
                            axis:'x',
                            cursor: 'move' });
      }

      function destroyKnob() {
        return self.knob.draggable( "destroy" );
      }

      $.fn.switcher.enable = enable;
      $.fn.switcher.disable = disable;

    });
  }
  $.fn.switcher.setWidth = function(obj){
    obj.maxW = Math.max(obj.leftItem.width(), obj.rightItem.width());
    obj.w = obj.maxW + 46;
    obj.r = obj.w - 24;
    obj.offset = obj.maxW + 22;
    obj.leftItem.css('width', obj.maxW);
    obj.rightItem.css('width', obj.maxW);
    $(obj).css({'width': obj.w, 'visibility': 'visible' });
    obj.bg.css('width', (obj.maxW + 34)*2);
  }
  $.fn.switcher.setState = function(obj){
    if(obj.state) {
      obj.knob.css('left', '0');
      $.fn.switcher.moveBg(obj, -obj.offset);

    } else {
      obj.knob.css('left', obj.r);
      $.fn.switcher.moveBg(obj, 0);

    }
  }
  $.fn.switcher.getState = function(obj){
    obj.inputs.eq(0).attr('checked') ? obj.state = 0 : obj.state = 1;
  }
  $.fn.switcher.moveBg = function(obj, offset) {
    obj.bg.css({'left': offset});
  }
  $.fn.switcher.dragSwitch = function(obj, e, ui) {
    $.fn.switcher.moveBg(obj, ui.position.left - obj.offset);
  }
  $.fn.switcher.sendAjax = function(obj) {
    if(obj.opts.type == 'event') {
      $.post('/events/' + obj.objId + '/visit.json', {'_method': 'put'}, function(data){ $.fn.switcher.ajaxSuccess(obj, data); })
      obj.count.append($.fn.switcher.tplLoading);
    }
    $.fn.switcher.refreshInputs(obj);
  }
  $.fn.switcher.refreshInputs = function(obj) {
    if(obj.state) {
      obj.inputs[1].click();
    } else {
      obj.inputs[0].click();
    }
    if((obj.opts.type == 'event') && (window._gaq != undefined)) {
      var type = (obj.state) ? 'Check-out' : 'Check-in',
          pageType = (obj.opts.pageType) ? 'Page' : 'Badge';
      _gaq.push(['_trackEvent', 'Events', type, pageType]);
    }
    if(obj.opts.onChange && (typeof(obj.opts.onChange) == 'function')) {
      obj.opts.onChange(obj.inputs.eq(obj.state).val());
    }
  }
  $.fn.switcher.ajaxSuccess = function(obj, data) {
    $('.g-count-load', obj.count).remove();
    var elems = LAM.Events.get('event_' + obj.objId);

    if(elems.length > 0) {
      $.each(elems, function(index, elem){
        if(obj != elem.get(0)) {
          $.fn.switcher.changeState(elem.get(0));
        }
        obj.allUsers.text(data.rating);
        obj.friendUsers.text(data.friends_num);
      });
    }
  }
  $.fn.switcher.toRight = function(obj) {
    obj.knob.animate({'left': obj.r}, 100);
    obj.bg.animate({'left':0}, 100);
    obj.state = 0;
  }
  $.fn.switcher.toLeft = function(obj) {
    obj.knob.animate({'left': 0}, 100);
    obj.bg.animate({'left': -obj.offset}, 100);
    obj.state = 1;
  }
  $.fn.switcher.stopSwitch = function(obj, e, ui) {
    (ui.position.left >= (obj.w/2 - 15)) ? $.fn.switcher.toRight(obj) : $.fn.switcher.toLeft(obj);
    $.fn.switcher.sendAjax(obj);
  }
  $.fn.switcher.changeState = function(obj) {
    obj.state = !obj.state;
    $.fn.switcher.refreshInputs(obj);
    $.fn.switcher.setState(obj);
  }

  $.fn.switcher.tplLoading = '<div class="g-count-load"></div>';
  $.fn.switcher.defaults = {
    enabled: true
  }
})(jQuery);

