/**
 * $Id: jquery.singleDatePickerPopup.js 2412 2009-05-19 09:24:16Z Bjoern.Moenikes $
 **/

(function($){

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

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

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

          if (!this._ppId) {
            this._ppId = $.event.guid++;
            $.event._ppCache[this._ppId] = new Popup2(this);
            alreadyExists = false;
          }

          var controller = $.event._ppCache[this._ppId];

          controller.init(options, content);
        }
        )
    },

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



    ppGetTravelDate : function()
    {
      var c = _getController(this[0]);
      if (c) {
        return c.getTravelDate();
      }
      return null;
    },
    ppSetTravelDate : function(dateString)
    {
      return _w.call(this, 'setTravelDate', dateString);
    },
    ppUpdateGUI : function()
    {
      return _w.call(this, 'updateGUI');
    },

    ppGetAge : function()
    {
      var c = _getController(this[0]);
      if (c) {
        return c.getAge();
      }
      return null;
    },

    ppValidDate : function()
    {
      var c = _getController(this[0]);
      if (c) {
        return c.validateDate();
      }
      return null;
    },

    ppUpdateView : function(dateString)
    {
      return _w.call(this, 'updateView', dateString);
    },

    ppGetData : function()
    {
      var c = _getController(this[0]);
      if (c) {
        return c.getData();
      }
      return null;
    },


    _ppDestroy : 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 Popup2(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.dataController = undefined;
    this.$selectedItem = undefined;
    this.popupId = this.id+"Popup";
    this.travelDate = undefined;
    this.addYears = undefined;
    this.popupButtonId = this.id+"PopupButton";

  };
  $.extend(
    Popup2.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.input.attr("readonly", "readonly");
        this.bindMethodsToObj("show", "hide", "selectItem");
        this.$selectedItem = Array();
        this.cfg = {};
        if (s)
        {
          this.cfg = s;
        }

        this.addYears =  isNaN(this.cfg.addYears) ?  0 : this.cfg.addYears;
        this.myId = this.cfg.id+"";
        this.myId = this.myId.replace(/#/,"");
        this.travelDate = this.cfg.travelDate;
        this.dataController = this.cfg.dataController;
        this.build(this.ele);
        this.selectItem();
        this.hide();
      },

      updateView : function(dateStr)
      {
        if (dateStr == undefined)
          {
            C.log("ppUpdateView, no dateStr: "+dateStr);
            return;
          }
        var dates = dateStr.split(".");
        dates[1] = parseInt(dates[1], 10);
        dates[1] = ((dates[1] < 10) ? "0" : "") + dates[1];


        var $popC = $("#"+this.popupId);
        var $day = $("table.dayTable td[data='"+dates[0]+"'] a", $popC);
        var $month = $("table.monthTable td[data='"+dates[1]+"'] a", $popC);
        var $year = $("table.yearTable td[data='"+dates[2]+"'] a", $popC);

//        C.log(dates);
//        C.log($popC);
//        C.log($day);
//        C.log($month);
//        C.log($year);

        this.selectItem($day);
        this.selectItem($month);
        this.selectItem($year);
      },

      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 id="'+this.myId+'Popup" 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);
        }


        this.$popupButtonContext = $("#"+this.popupButtonId);
        this.$popupContext = $("#"+this.popupId);
        this.input.blur(this.bindToObj(function(ev){
          this.input.ppHide();
        }));
        //        this.$popupButtonContext.blur(this.bindToObj(function(ev){
        //          this.input.ppHide();
        //        }));



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


        $(el).bind("updateGUI", this.updateGUI);   // WORK AROUND TO TRIGGER SELECT



        var year = this.getSysdate().getFullYear();
        var mA = parseInt( this.cfg.maxAge, 10 );

        if (this.cfg.maxAge)
          this.rebuildYearTable(year-mA,  mA);


        if (!this.cfg.noLinks)
        {
          $("a", this.popupContent).click(this.bindToObj(function(event) {
            this.selectItem($(event.target));
            if (!this.cfg.noHide)
              if (this.$selectedItem["dayTable"]
                && this.$selectedItem["monthTable"]
                && this.$selectedItem["yearTable"])
                {
                if (this.validateDate())
                  this.hide();
                else
                {
                  var back = function()
                  {
                    getSlideManager().slideShow("#modifySearch");
                  }
                  $("#errorMessageBox").emcShow(getText('txt.singleDatePickerPopup.invalidDate.head'),
                    getText('txt.singleDatePickerPopup.invalidDate.text'), undefined, back);
                  this.input.val("");
                  this.input.attr("data","");
                }
              }
            return false;

          }));
        }
      },

      validateDate : function()
      {
        var erg = false;
        var date = this.input.attr("data");
        var items = date.split(".");
        items[1] = items[1] -1; // month are indexed by 0.11
        var check = new Date(items[2],items[1],items[0]);
        if (check.getDate() == parseInt(items[0],10)
          && check.getMonth() == parseInt(items[1],10)
          && check.getFullYear() == parseInt(items[2],10)
          && this.getAgeInYears(this.getTravelDate()) >= 0 )
          erg = true;
        return erg;
      },

      getTravelDate : function()
      {
        return(this.travelDate);
      },
      setTravelDate : function(dateString)
      {
        this.travelDate = dateString;
      },

      getAgeInYears : function()
      {
        var bdate = this.input.attr("data");
        var birthDate = parseDate(bdate);
        var travelDate = parseDate(this.getTravelDate());
        if (bdate != null && birthDate != null)
          return diffInYears(travelDate, birthDate);
        return -1;
      },

      getSysdate : function ()
      {
        return(this.getDate(sysDate));
      },

      getDate : function(dateString)
      {
        if (dateString == undefined || dateString == null)
        {
          C.log("error in singleDatePickerPopup");
          return;
        }
        var items = dateString.split(".");
        return new Date(items[2],items[1]-1,items[0]);
      },

      getData : function()
      {
        return $(this.id).attr("data");
      },


      rebuildYearTable : function(startYear, span)
      {
        startYear++; //span++;
        var numRows = Math.ceil( span / 4.0 );
        var name = this.popupId;
        var $table = $("#"+name + " .yearTable tbody");
        var delta = startYear-this.addYears;
        span = span + this.addYears;
        var count = 0;
        var $tbody = $("<tbody/>");

        //        C.log("rebuildYearTable");
        //        C.log(startYear);
        //        C.log(span);
        //        C.log($table);
        //        C.log(name);

        for (var j = 0; j < numRows; j++)
        {
          var $row = $("<tr/>");

          for (var i = 0 ; i < 4; i++)
          {
            if (count < span)
              $row.append("<td data='"+delta+"'><a href='#'>"+delta+"</a></td>");
            delta++;
            count++;
          }

          $tbody.append($row);
        }
        $table.replaceWith($tbody);
      },


      selectItem: function($item) {
//        C.log("ÜÜÜÜ");
        var hideMe = false;
        var parentName = $item ? $item.parent().parent().parent().parent().attr("class") : null;

        var val = '';
        if (!this.cfg.noLinks)
        {
          if (parentName && this.$selectedItem[parentName])
          {
            this.$selectedItem[parentName].toggleClass('selected');
            this.$selectedItem[parentName] = null;
          }

          if ($item)
          {
            this.$selectedItem[parentName] = $item;
            this.$selectedItem[parentName].toggleClass('selected');
            this.updateGUI();
            $(this.input).trigger("customChange"); // SEND CUSTOM CHANGE MESSAGE
          }
        }/*
        else
        {
          var data = this.input.attr ('data');
          if (data)
          {
            var fnSelectItem = this.selectItem;
            $("a", this.popupContent).each (function (index, domElement) {
              var $el = $(this);
              if (data == $el.attr('data'))
              {

                fnSelectItem ($el);
              }
            });
          }
        }*/

        if (this.cfg.onSelect)
        {
          this.cfg.onSelect.apply (this.input, $item);
        }
        if (!this.cfg.noHide)
        {
          if (this.$selectedItem["dayTable"]
            && this.$selectedItem["monthTable"]
            && this.$selectedItem["yearTable"])
            {
            this.hide();
            this.updateGUI();
          }

        }
      },

      updateGUI : function()
      {
        if (this.$selectedItem
          && this.$selectedItem["dayTable"]
          && this.$selectedItem["monthTable"]
          && this.$selectedItem["yearTable"])
          {
          var day = this.$selectedItem["dayTable"].parent().attr("data");
          var month = this.$selectedItem["monthTable"].parent().attr("data");
          var year = this.$selectedItem["yearTable"].parent().attr("data");
          var travelDate = this.getDate(this.getTravelDate());

          var dateString  = day+"."+month+"."+year;
          var current_date = this.getDate(dateString);

          var delta = travelDate.getTime() - current_date.getTime();
          var txt = this.getAgeInYears(this.getTravelDate()) == 1 ? 'txt.common.year' :'txt.common.years';
          this.input.val(getText(txt,this.getAgeInYears(this.getTravelDate())));
          this.input.attr("data",dateString);
        }
      },

      show: function() {
        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) {
//        C.log("hideIfClickOutside");
//        C.log(event);
//        C.log(this);
//        C.log(this.input);
        if (    this.input == undefined
          || ( 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.popupPanel.outerHeight() - 4,
          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._ppId) return $.event._ppCache[ele._ppId];
    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._ppCache || [];
    for (var i in els) {
      $(els[i].ele)._ppDestroy();
    }
  });


})(jQuery);

/**
 * $Id: jquery.singleDatePickerPopup.js 2412 2009-05-19 09:24:16Z Bjoern.Moenikes $
 **/

//   _sdpCache    _sdpId   sdp  SingleDatePickerPopup   singleDatePickerPopup    müssen für neues Plugin ersetzt werden

(function($){

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

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

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

          if (!this._sdpId) {
            this._sdpId = $.event.guid++;
            $.event._sdpCache[this._sdpId] = new SingleDatePickerPopup(this);
            alreadyExists = false;
          }

          var controller = $.event._sdpCache[this._sdpId];

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

    sdpGetMaxAge : function()
    {
      var c = _getController(this[0]);
      if (c) {
        return c.getMaxAge();
      }
      return null;
    },

    /*
sdpSetJSONAction : function(action)
    {
      return _w.call(this, 'setJSONAction', action);
    },
    sdpGetRenderDirective : function()
    {
      var c = _getController(this[0]);
      if (c) {
        return c.getRenderDirective();
      }
      return null;
    },
    */
   
    _sdpDestroy : 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 SingleDatePickerPopup(ele)
  {
    this.ele = ele;

    // initial values...
    this.id				=	undefined;
    this.$context			=	undefined;
    this.directive = undefined;
    this.popupId = "noID";
    this.popupHeadline = "no headline";
    this.onChangeCallback = undefined;
    this.$controll = undefined;
    this.maxAge = undefined;
    this.travelDate = undefined;
  };
  $.extend(
    SingleDatePickerPopup.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.onChangeCallback = s.onChangeCallback;
        this.maxAge = s.maxAge;
        this.travelDate = s.travelDate;

        if (this.onChangeCallback != undefined)
          this.$context.bind("customChange", this.onChangeCallback);

        this.sdpBuildPopup();
      },


      getMaxAge : function()
      {
        return this.maxAge;
      },


      sdpBuildPopup : function()
      {
        var $data = this.sdpRenderObjFromTemplate (
          '#templates div.singleDatePicker', this.directive, this.data,
          'compiledSingleDatePicker');
        var $popupData = $('<div class="col1"/>').append($data);
        var $con = $('<div class="'+ this.popupId +'"/>').append(
          $("<h3>"+this.popupHeadline+"</h3>")).append($popupData);

        $(this.popupId).popup2($con, {
          "additionalClassName" : "singleDatePickerPopup",
          "maxAge" : (this.getMaxAge()+1),
          "addYears" : 0, // 3 additional years
          "travelDate" : this.travelDate,
          "id" : this.id,
          "multiSelect" : "dayTable monthTable yearTable"
        });
      },


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


      sdpRenderObjFromTemplate  : 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._sdpId) return $.event._sdpCache[ele._sdpId];
    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._sdpCache || [];
    for (var i in els) {
      $(els[i].ele)._sdpDestroy();
    }
  });


})(jQuery);