/**
 * $Id: jquery.ul_popup.js 2334 2009-04-28 13:24:57Z Bjoern.Moenikes $
 **/

(function($){

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

      // initialise the date picker controller with the relevant settings...
      options = $.extend(
      {
        renderDirective : '',                  // needed for autorenderer
        emptyRow : ' ',
        popupId : undefined,
        popupHeadline : undefined,
        onChangeCallback : undefined,
        $data : undefined
      }
      , options
      );

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

          if (!this._upId) {
            this._upId = $.event.guid++;
            $.event._upCache[this._upId] = new UlPopup(this);
            alreadyExists = false;
          }

          var controller = $.event._upCache[this._upId];

          controller.init(options);
        }
        )
    },
    ulpSelectItem: function($item) {
      return _w.call(this, 'XselectItem', $item);
    },

    ulpGenerateContent: function(data, target) {
      return _w.call(this, 'generateContent', data, target);
    },
   
    _upDestroy : 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 UlPopup(ele)
  {
    this.ele = ele;

    // initial values...
    this.$context			=	$(ele);
    this.id				=	this.$context.attr("id");
    this.directive = undefined;
    this.popupId = "noID";
    this.popupHeadline = "no headline";
    this.onChangeCallback = undefined;
    this.$controll = undefined;
  };
  $.extend(
    UlPopup.prototype,
    {
      init : function(s)
      {

        this.directive = {
          '[class]' : 'className',
          'li' : 'item <- items',
          'li a' : 'item.txtValue',
          'li[class]' : 'item.styleClass',
          'li a[class]' : 'item.styleClass',
          'li a[data]' : function (arg) {
            return arg.item.data;
          }
        };
        
        //this.id = s.popupId;
        //this.$context = $(s.popupId);
        this.popupId = s.popupId;
        this.popupHeadline = s.popupHeadline;
        this.data = s.data;
        this.$data = s.$data;
        this.onChangeCallback = s.onChangeCallback;
        if (this.onChangeCallback != undefined)
          this.$context.bind("customChange", this.onChangeCallback);

        this.buildPopup();
      },

      generateContent : function(data, target)
      {
        if (data)
          this.data = data;

//        C.log("generateContent");
//        C.log(target);
//        C.log(this.data);

        var $data = Array();
        var len = undefined;
        if (this.data){
          len = this.data.length;
          var i;
          for (i = 0; i < len; i++)
            $data[i] = renderObjFromTemplate ('#templates ul.selectorList', this.directive,
              this.data[i], 'compiledSelectorList');
        }
        else if (this.$data)
          $data[0] = this.$data;

        len = $data.length;

        var $popupData = $('<div class="col1"/>');
        for (i = 0; i < len; i++)
          $popupData.append($data[i]);

        $(this.popupId).pResetEvents();

        if (target)
          $(target).replaceWith($popupData);

        return $popupData;
      },

      buildPopup : function()
      {
        
        var $popupData = this.generateContent();

        var $con = $('<div class="'+ this.popupId.replace(/#/,"") +'"/>').append(
          $("<h3>"+this.popupHeadline+"</h3>")).append($popupData);
        $(this.popupId).popup($con);
      },


      XselectItem: function($item) {
//        C.log("XselectItem");
//        C.log(this.popupId);
        $(this.popupId).trigger("emptySelectItem");
      },


      renderObjFromTemplate  : function(templateSelector, directive, context, compiledFunction)
      {
        var $obj = null;
        if (templateSelector)
        {
          var $template = $(templateSelector);
          if ($template)
          {
            if (compiledFunction)
            {
              if (!$p.compiledFunctions[compiledFunction])
              {
                $template.clone().compile (compiledFunction, directive);
              }
              $obj = $('<div/>').render (context, compiledFunction, $template);
            }
            else
            {
              $obj = $('<div/>').render (context, directive, $template);
            }
          }
        }

        return $obj;
      }
    });



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


})(jQuery);