/**
 * $Id: jquery.radiobutton.js 2416 2009-05-19 10:17:34Z Bjoern.Moenikes $
 **/

// General idea: wrapper class for a hidden radiobutton
// controller waits for click
// clicks are beeing send to corresponding target radiobutton
// jquery.radiobutton binds to onChange of target radiobutton
// jquery.radiobutton shows image depending on radiobutton state

(function($){

  $.fn.extend({
    radioButton : function(options)
    {
      if (!$.event._rbCache) $.event._rbCache = [];

      // initialise the date picker controller with the relevant settings...
      options = $.extend(
      {
        // no options
        syncFunc : undefined,
        onClickFunc : undefined
      }
      , options
      );

      return this.each(
        function()
        {
          var $this = $(this);
          var alreadyExists = true;

          if (!this._rbId) {
            this._rbId = $.event.guid++;
            $.event._rbCache[this._rbId] = new RadioButton(this);
            alreadyExists = false;
          }

          var controller = $.event._rbCache[this._rbId];
          controller.init(options);
        }
        )
    },

    rbSetOnClickFunction : function(fn)
    {
      return _w.call(this, 'setOnClickFunction',fn);
    },

    rbSyncSelectState : function(a,b)
    {
      return _w.call(this, 'syncSelectState',a,b);
    },

    rbEnable : function()
    {
      return _w.call(this, 'enable');
    },
    rbDisable : function()
    {
      return _w.call(this, 'disable');
    },

    rbSetSelected : function($target, sel)
    {
      return _w.call(this, 'setSelected', $target, sel);
    },

    _rbDestroy : function()
    {
    // TODO - implement this?
    }
  });

  // private internal function to cut down on the amount of code needed where we forward
  // dp* methods on the jQuery object on to the relevant DatePicker controllers...
  var _w = function(f, a1, a2, a3)
  {
    return this.each(
      function()
      {
        var c = _getController(this);
        if (c) {
          c[f](a1, a2, a3);
        }
      }
      );
  };

  function RadioButton(ele)
  {
    // initial values...
    this.ele = ele;
    this.id				      =	$(this.ele).attr("id");
    this.viewId         = this.id + '-rbview';
    this.$viewContext   = undefined;
    this.name           = $(this.ele).attr("name");
    this.$context		  	=	$(this.ele);
    this.syncFunc       = undefined;
    this.onClickFunc    = undefined;

    if (this.id=="" || this.name=="")
    {
      C.log("Error: RadioButton() without id and/or name inited: ");
      C.log(this.ele);
    }
  };
  $.extend(
    RadioButton.prototype,
    {
      // javascript:void(    $("#kind_flightOnly").rbDisable()        );
      // javascript:void(    $("#kind_flightOnly").rbEnable()        );

      // javascript:void(    $("#kind_flightOnly").attr("disabled", "disabled")        );


      setOnClickFunction : function(fn)
      {
        this.onClickFunc = fn;
      //        C.log("internal setOnClick");
      //        C.log(this);
      },

      enable : function()
      {
        if (this.$viewContext.hasClass("disabledrbcheck"))
          this.$viewContext.removeClass("disabledrbcheck").addClass("rbcheck");
        if (this.$viewContext.hasClass("disabledrbnocheck"))
          this.$viewContext.removeClass("disabledrbnocheck").addClass("rbnocheck");
        this.$context.removeAttr("disabled");
      },
      disable : function()
      {
        //        C.log("DIS");
        if (this.$viewContext.hasClass("rbcheck"))
          this.$viewContext.removeClass("rbcheck").addClass("disabledrbcheck");
        if (this.$viewContext.hasClass("rbnocheck"))
          this.$viewContext.removeClass("rbnocheck").addClass("disabledrbnocheck");
        this.$context.attr("disabled","disabled");
      },

      setSelected : function($target, sel)
      {
        //        C.log("SET SELECTED");
        //        C.log($target);
        //        C.log(sel);
        if (sel == true)
        {
          $target.removeClass("rbnocheck").addClass("rbcheck");
        }
        else
        {
          $target.removeClass("rbcheck").addClass("rbnocheck");
        }
      },

      bindToObj: function(fn) {
        var self = this;
        return function() {
          return fn.apply(self, arguments)
        };
      },

      init : function(s)
      {     
        this.syncFunc = s.syncFunc;
        this.onClickFunc = s.onClickFunc;
        var synFun = this.syncFunc;

        // deselect all radio buttons of corresponding button group and
        // select just the newly selected one
        
        var radioChange = function(event)
        {
          //          C.log("radioChange1");
          if ($.isFunction(synFun))
            return;
          
          //          C.log($(event.target));
          //          C.log($(event.target).is(":checked"));
          var item = $(event.target).attr("id");
          var $item = $("#"+item+"-rbview");
          var name = $item.attr("name");
          var $target1 = $("div[name='"+name+"'].rbcheck");
          var $target2 = $("div[name='"+name+"'].disabledrbcheck");
          $target1.removeClass("rbcheck").addClass("rbnocheck");
          $target2.removeClass("disabledrbcheck").addClass("disabledrbnocheck");
          $item.removeClass("rbnocheck").addClass("rbcheck");
        }
        

        // a click to graphical radio button is beeing passed to "real" radio button
        var simulateClick = function(event)
        {
          //          C.log("simulateclick");
          // deselect all radio buttons of corresponding button group and
          // select just the newly selected one
          var radioChange2 = function(item)
          {
            //            C.log(this);
            //            C.log(this.onClickFunc);
            if ($.isFunction(this.onClickFunc))
              this.onClickFunc();
            //            C.log("radioChange2");
            if (!($.isFunction(synFun)))
              return;
            //            C.log("ok");
            var $item = $("#"+item+"-rbview")
            var name = $item.attr("name");
            var $target1 = $("div[name='"+name+"'].rbcheck");
            var $target2 = $("div[name='"+name+"'].disabledrbcheck");
            $target1.removeClass("rbcheck").addClass("rbnocheck");
            $target2.removeClass("disabledrbcheck").addClass("disabledrbnocheck");
            $item.removeClass("rbnocheck").addClass("rbcheck");
            if ($.isFunction(synFun))
              synFun();
          }
          
          var item = "#"+$(event.target).attr("id").replace(/-rbview/,"");
          var $item = $(item);
          C.log($item);
          if (!$item.is(":disabled"))
          {
            //            C.log("click: " + $("#modifySearch").msGetSearchKind());
            $item.change().click();
            //            C.log("clicked: " + $("#modifySearch").msGetSearchKind());
            this.bindToObj(radioChange2)(item);
          }

        }

        this.$context.bind("click",this.bindToObj(radioChange));
        //   this.$context.bind("click",radioChange);

        //        var el = document.getElementById(this.id);
        //        if(el.addEventListener)
        //          el.addEventListener('RadioStateChange', function(ev){C.log(ev);}, false);
        //        if (navigator.userAgent.search(/MSIE/i) > 0)
        //          el.onpropertychange = radioChange;
        //        else if(el.addEventListener)
        //        C.log(this.id);
        //        C.log("EL:"); C.log(el);
        //          el.addEventListener('DOMAttrModified', function(ev){alert("hi");C.log(ev);}, false);

        var xclass="rbnocheck";
        if (this.$context.is(":checked"))
          xclass="rbcheck";
        if (this.$context.is(":disabled"))
          xclass="disabled"+xclass;
        
        ($('<div id="'+this.viewId+'" class="'+xclass+'"'+
          'name="'+this.name+'" >').bind("click", this.bindToObj(simulateClick ))).insertAfter(this.$context);

        this.$viewContext = $("#"+this.viewId);

        this.captureLabel();

        if (this.$context.is(":hidden"))
          this.$viewContext.hide();
        this.$context.hide();
      },

      // all labels for the current input element will be manipulated:
      // the "for"-target will be erased and the label is going to trigger an
      // click event to the graphical radio button when beeing clicked
      captureLabel : function()
      {
        $("label[for='"+ this.id+"']")
        .removeAttr("for")
        .click(this.bindToObj(function()
        {
          $("#"+this.viewId).click();
        }));
      },

      syncShowHideState : function()
      {
        if (this.$context.is(":hidden"))
          updateVisibility(false);
        else
          updateVisibility(true);
      },

      syncSelectState : function($target, $view)
      {
        var $tgt = this.$context;
        var $vie = this.$viewContext;

        if ($target && $target.length > 0)
        {
          $tgt = $target;
          $vie = $view
        }
       
        //        C.log("#################################");
        //        C.log("syncSelectState");
        //        C.log($target);
        //        C.log($tgt);
        //        C.log($tgt.is(":checked"));

        if ($tgt.is(":checked"))
          $vie.removeClass("rbnocheck").addClass("rbcheck");
        else
          $vie.removeClass("rbcheck").addClass("rbnocheck");
      },


      updateVisibility : function(visible)
      {
        if (visible)
          this.$viewContext.show();
        else
          this.$viewContext.hide();
      }
    }
    );

  function _getController(ele)
  {
    if (ele._rbId) return $.event._rbCache[ele._rbId];
    return false;
  };

  // make it so that no error is thrown if bgIframe plugin isn't included (allows you to use conditional
  // comments to only include bgIframe where it is needed in IE without breaking this plugin).
  if ($.fn.bgIframe == undefined) {
    $.fn.bgIframe = function() {
      return this;
    };
  };


  // clean-up
  $(window)
  .bind('unload', function() {
    var els = $.event._rbCache || [];
    for (var i in els) {
      $(els[i].ele)._rbDestroy();
    }
  });


})(jQuery);