

/**
 * $Id: jquery.popup.js 2404 2009-05-18 09:57:15Z Bjoern.Moenikes $
 **/

//   _pCache    _pId   p  Popup   popup    müssen für neues Plugin ersetzt werden

(function($){

  $.fn.extend({
    popup : function(content, options)
    {
      if (!$.event._pCache) $.event._pCache = [];

      // initialise the date picker controller with the relevant settings...
      options = $.extend(
      {
        id : '',
        $context : '',
        overrideWidth : undefined,
        overrideHeight : undefined,
        noLinks : undefined
      }
      , options
      );

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

          if (!this._pId) {
            this._pId = $.event.guid++;
            $.event._pCache[this._pId] = new Popup(this);
            alreadyExists = false;
          }
          var controller = $.event._pCache[this._pId];
          controller.init(options, content);
        }
        )
    },

    pShow : function()
    {
      return _w.call(this, 'show');
    },
    pHide : function()
    {
      return _w.call(this, 'hide');
    },

    pResetEvents : function()
    {
      return _w.call(this, 'resetEvents');
    },
    pUpdateItem : function()
    {
      return _w.call(this, 'updateItem');
    },
    _pDestroy : 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 Popup(ele)
  {
    this.ele = ele;
    // initial values...
    this.$context			=	$(ele);
    this.id				=	this.$context.attr("id");


    this.input = undefined;
    this.popupContent  = undefined;
    this.cfg = undefined;
    this.$selectedItem = undefined;
    this.popupId = undefined;
    this.$close = undefined;
    this.$button = undefined;
    this.overrideWidth = undefined;
    this.overrideHeight = undefined;
    this.overrideStyle = undefined;
  };
  
  $.extend(
    Popup.prototype,
    {
      init : function(s,content)
      {
        //        this.id = s.id;
        //        this.$context = $(s.id);

        this.input = $(this.ele);
        this.popupContent = content;
        this.popupId = this.id+"Popup";
        this.$popupContext = undefined;
        this.popupButtonId = this.id+"PopupButton";
        this.$popupButtonContext = undefined;
        this.overrideWidth = s.overrideWidth;
        this.overrideHeight = s.overrideHeight;
        this.overrideStyle = undefined;

        var st = "";
        if (this.overrideWidth != undefined)
          st += "width: "+this.overrideWidth+";";
        if (this.overrideHeight)
          st += (st.length != 0) ? " " : "" + "height: "+this.overrideWidth+";";
        if (st.length > 0)
          st = 'style="'+st+'"';
        this.overrideStyle = st;


//        C.log("jquery.popup.js: init()");
//        C.log(this.overrideHeight);
//        C.log(this.overrideStyle);
//        C.log("!!");


        this.input.attr("readonly", "readonly");

        this.bindMethodsToObj("show", "hide", "hideIfClickOutside", "selectItem");
        this.bindMethodsToObj("show", "hide", "selectItem");
        this.$selectedItem = null;
        this.cfg = {};
        if (s)
        {
          this.cfg = s;
        }
//        C.log("BUILD");
//        C.log(this.cfg);
//        C.log(s);

        this.build(this.ele);
        this.selectItem();
        this.hide();


      },
      build: function(el) {
        this.$close = $('<a class="close" href="#" onfocus="blur();">close</a>').click(this.bindToObj(function(event) {
          this.hide();
          return false;
        }));

        this.$button = $('<a id="'+this.popupButtonId+'" class="popupButton" href="#">toggle</a>').click(this.bindToObj(function(event) {
          this.toggle();
          return false;
        }));

        this.input.after (this.$button);

        this.popupController = $('<div class="popupController"></div>').append(this.$close);
        this.popupContent = $('<div class="popupContent"></div>').append(this.popupContent);

        var additionalClassName =
        this.cfg.additionalClassName ? this.cfg.additionalClassName : '';
        this.popupPanel = this.rootLayers = $('<div '+this.overrideStyle+' id="'+this.popupId+'" class="popupPanel ' + additionalClassName + '"></div>')
        .css({
          display: "none",
          position: "absolute",
          zIndex: 100
        })
        .append(this.popupController, this.popupContent)
        .appendTo(document.body);

        if ($.browser.msie && $.browser.version < 7) {
          this.ieframe = $('<iframe class="popupPanel_ieframe" frameborder="0"></iframe>')
          .css({
            position: "absolute",
            display: "none",
            zIndex: 99
          })
          .insertBefore(this.popupPanel);
          this.rootLayers = this.rootLayers.add(this.ieframe);
        }

        var $emptySelectItem = this.selectItem;
        //      console.log($(el));
        $(this.ele).bind("emptySelectItem", function() {
          $emptySelectItem();
        });   // WORK AROUND TO TRIGGER SELECT

        this.resetEvents();


        this.$popupButtonContext = $("#"+this.popupButtonId);
        this.$popupContext = $("#"+this.popupId);

        this.$popupButtonContext.blur(function(ev){
          return;
//          C.log("button");
//          C.log(this);
//          C.log(ev);
//          C.log(ev.target);
          if ($(ev.target).length && !$(ev.target).attr("id").length)
            this.input.pHide();
        });


//        this.$popupButtonContext.blur(this.bindToObj(function(ev){
//          C.log("button");
//          C.log(this);
//          C.log(ev);
//          C.log(ev.target);
//          return;
//          if ($(ev.target).length && !$(ev.target).attr("id").length)
//            this.input.pHide();
//        }));
        this.input.blur(this.bindToObj(function(ev){
          this.input.pHide();
        }));
        //        this.input.bind("keypress",this.bindToObj(function(ev){
        //          C.log("KEYPRESS"); C.log(ev);
        //        }));


        this.input.change(this.bindToObj(function() {
          this.selectItem();
        }));
      },

      resetEvents : function()
      {
//        C.log("noLinks");
//        C.log(this.cfg.noLinks);
        if (!this.cfg.noLinks)
        {
          /*
          if (!this.el)
            return;
          C.log("$(this)");
          C.log((this.el));
          C.log($(this.el));
          $(this.el).bind("click",function(ev){
            ev.preventDefault();
            var $tar = $(ev.target);
            C.log("ÜÜ");
            C.log($tar);
            if ($tar.attr("id") != "")
            {
              return;
              this.selectItem($tar);
              if (!this.cfg.noHide)
                this.hide();
              return false;
            }
          })
        */
          $("a", this.popupContent).click(this.bindToObj(function(event) {
            this.selectItem($(event.target));
            if (!this.cfg.noHide)
              this.hide();
            return false;
          }));

        }
      },

      updateItem: function() {
        var data = this.input.attr ('data');
        var pc = this;
        if (data)
        {
          var fnSelectItem = this.selectItem;
          $("a", this.popupContent).each (function (index, domElement) {
            var $el = $(domElement);
            var $this = pc;
            if (data == $el.attr('data'))
            {
              /*             C.log("***updateItem");
        C.log(pc);
        C.log($this);
        C.log($el);
        C.log($this.$selectedItem);
        C.log("---");
*/
              if (pc.$selectedItem == $el)
              {
                //                C.log("selecting nothing new!");
                return;
              }
              if (pc.$selectedItem)
              {
                pc.$selectedItem.removeClass('selected');
                pc.$selectedItem = null;
              }
              pc.$selectedItem = $el;
              pc.$selectedItem.addClass('selected');
            }
          });
        }
      },

      selectItem: function($item) {
        //        C.log("selectItem");
        //        C.log(this);
        //        C.log($item);
        //        C.log(this.$selectedItem);
        //        C.log("---");

        var val = '';
        if (!this.cfg.noLinks)
        {
          if (this.$selectedItem)
          {
            this.$selectedItem.removeClass('selected');
            this.$selectedItem = null;
          }

          if ($item)
          {
            this.$selectedItem = $item;
            this.$selectedItem.addClass('selected');
            this.input.attr("data", this.$selectedItem.attr('data'));

            $(this.input).trigger("customChange"); // SEND CUSTOM CHANGE MESSAGE

            val = this.$selectedItem.html();
            this.input.val(val);
          }
          else
          {
            var data = this.input.attr ('data');
            if (data)
            {
              var fnSelectItem = this.selectItem;
              $("a", this.popupContent).each (function (index, domElement) {
                var $el = $(domElement);
                if (data == $el.attr('data'))
                {
                  fnSelectItem ($el);
                }
              });
            }
          }
        }
        if (this.cfg.onSelect)
        {
          this.cfg.onSelect.apply (this.input, $item);
        }
        if (!this.cfg.noHide)
          this.hide();
      },

      show: function() {
        if (!this.input.attr('disabled'))
        {
          this.setPosition();
          this.rootLayers.css("display", "block");
          this.$button.addClass ('popupButton_minus');
          this.input.unbind("focus", this.show);
          $(document.body).bind ('mousedown', this.hideIfClickOutside);
        }
      },

      hide: function() {
        this.$button.removeClass ('popupButton_minus');
        this.rootLayers.css("display", "none");
        $(document.body).unbind("mousedown", this.hideIfClickOutside);
        this.input.focus(this.show);
      },

      toggle: function() {
        var shown = this.rootLayers.css("display");
        shown == 'none'? this.show () : this.hide ();
      },

      hideIfClickOutside: function(event) {
        if (event.target != this.input[0] && event.target != this.$button[0] && !this.insideSelector(event)) {
          this.hide();
        };
      },

      setPosition: function() {
        var offset = this.input.offset();
        this.rootLayers.css({
          top: offset.top + this.input.outerHeight(),
          left: offset.left
        });

        if (this.ieframe) {
          this.ieframe.css({
            width: this.popupPanel.outerWidth(),
            height: this.popupPanel.outerHeight()
          });
        };
      },

      insideSelector: function(event) {
        var offset = this.popupPanel.offset();
        offset.right = offset.left + this.popupPanel.outerWidth();
        offset.bottom = offset.top + this.popupPanel.outerHeight();

        return event.pageY < offset.bottom &&
        event.pageY > offset.top &&
        event.pageX < offset.right &&
        event.pageX > offset.left;
      },

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

      bindMethodsToObj: function() {
        for (var i = 0; i < arguments.length; i++) {
          this[arguments[i]] = this.bindToObj(this[arguments[i]]);
        };
      }


    }
    );


  function _getController(ele)
  {
    if (ele._pId) return $.event._pCache[ele._pId];
    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._pCache || [];
    for (var i in els) {
      $(els[i].ele)._pDestroy();
    }
  });


})(jQuery);

