//_______________________________________________________________________
//   |       |
//   | knipp |           Knipp Medien und Kommunikation GmbH
//    -------
//
//
//    Project: Pöppelmann Relaunch 2010
//
//    Copyright (C) 2009 by Knipp Medien und Kommunikation GmbH
//
//    initial autor:   Björn Mönikes
//    version:         $Revision: 1578 $
//                     $Date: 2012-01-19 17:57:32 +0100 (Do, 19 Jan 2012) $
//                     $Author: igor.lubimov $
//

var infoboxItems = [];

//var infoboxItem = {
//  'area'                 :  "kapsto, ktech, famac, teku", // one of
//  'productImage'         :  undefined,
//  'productName'          :  undefined,
//  'productDescription'   :  undefined,
//  'productDetailsLink'   :  undefined,
//  'uid'                  :  undefined  // unique identifier for object
//};


var infoboxItem = {
  'area'                 :  "famac", // one of
  'productImage'         :  '/fileadmin/images/company/notepad/dummypic.png',
  'productName'          :  'VCD 10,5',
  'productDescription'   :  'TEKU Premium',
  'productGroup'         :  'Rundtop/Container 5"',
  'productDetailsLink'   :  undefined,
  'uid'                  :  undefined  // unique identifier for object
};


(function($){

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

      // set defaults for event timeout, animation duration and padding
      options = $.extend(
      {
        eventTimeout : 1500,
        animationDuration : 1000,
        padding : 5,
        artikel : " Artikel"
      }
      , options
      );

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

          if (!this._ibId) {
            this._ibId = $.event.guid++;
            $.event._ibCache[this._ibId] = new Infobox(this);
            alreadyExists = false;
          }

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


    ibShowBox : function()
    {
      return _w.call(this, 'start_animating');
    },

    ibAddItem : function(item)
    {
      return _w.call(this, 'addItem', item);
    },

    ibClearItems : function()
    {
      return _w.call(this, 'clearItems');
    },

    ibShowNotFoundDialog : function()
    {
      return _w.call(this, 'showNotFoundDialog');
    },

    _ibDestroy : function()
    {
      return _w.call(this, 'cleanup');
    }
  });

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


  function Infobox(ele)
  {
    // constants indicating the current state of this Infobox instance
    this.ANIM_SHOW = 1;
    this.VISIBLE = 2;
    this.ANIM_HIDE = 3;
    this.HIDDEN = 4;

    // current state of this Infobox instance
    this.state = this.HIDDEN;

    // basic setup
    this.ele = ele;
    this.$ele = $(this.ele);
    this.$anchor = $("#wishList a");
    this.targetHeight = 200;
  };

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

      showNotFoundDialog : function() {
        var $nfd  = $("<div class=\"knippnotfounddialog\"><br/><br/> &nbsp;"+getText('notFoundMessage')+"</div>");

      $nfd.dialog({
        modal: true,
        resizable: false,
        close: this.bindToObj(this.hideNotFoundDialog),
        width: 300,
        height: 200
      });
      this.$nfd = $('div.knippnotfounddialog:last');
      },

    hideNotFoundDialog : function() {
      this.$nfd.remove();
    },



      init : function(s)
      {
        // get some setup paramter
        this.eventTimeout = s.eventTimeout;
        this.animationDuration = s.animationDuration;
        this.padding = s.padding;
        this.artikel = s.artikel;
        this.artikelCount = 0;
        this.itemsToAdd = [];
        this.addTimeout;


//        C.log(notepadCaption);

        // get prepare container for content
        this.$container = $("<div class=\"ib_container\" />");
        var $mz = "<div class=\"close\"></div>"
          + "<div class=\"image\"><img width=\"36p\" height=\"36p\" src=\"\" /></div>"
          + "<div class=\"header\"><b>"+notepadCaption+"</b></div>"
          + "<div class=\"divider\"></div>"
          + "<div class=\"title\"></div>"
          + "<div class=\"subtitle\"></div>"
          + "<div class=\"group\"></div>";
        this.$content = $("<div  id=\"merkzettel\"  class=\"ib_content\">"+$mz+"</div>");
        this.$container.append(this.$content);

        this.$anchor.before(this.$container);

        if (this.$number) {
        } else {
          $('a', this.$ele).append(" <span class=\"number\" style=\"display: none;\"></span>");
          this.$number = $("span.number", this.$ele);
        }

        this.state = this.ANIM_HIDE ;//HIDDEN;

        // bind scroll event to scrollOccured function and start the game
//        this.$ele.bind("click", this.bindToObj(this.start_animating));
        $("div.close",this.$content).bind("click", this.bindToObj(this.animate_hide));

        $.ajax({
          url: "?eID=json&a=MZcount",
          type: "POST",
          data: JSON.stringify({"data" : {"area":area}}),
          dataType: "json",
          //async:false,
          success: this.bindToObj(function(msg){
//                        C.log(msg);
		      if (msg && msg.data && msg.data.count) {
                        this.artikelCount = msg.data.count;
                        this.setNumberArtikel();
                      }
                   }),
          error : this.bindToObj(function(jqXHR, textStatus, errorThrown) {
                      C.log("ajax error!");
                      C.log(jqXHR);
                      C.log(textStatus);
                      C.log(errorThrown);
                      //throw textStatus;
                      //throw errorThrown;
                   })
        });
      },

      clearItems : function() {
       $.ajax({
            url: "?eID=json&a=clearMZ",
            type: "POST",
            data: JSON.stringify({"data" : {"area":area}}),
            dataType: "json",
            //async:false,
            success: this.bindToObj(function(msg){
//                        C.log(msg);
                        this.artikelCount = 0;
                        this.setNumberArtikel();
                        window.location = window.location; // reload page
                     }),
            error : function(jqXHR, textStatus, errorThrown) {
                        C.log("ajax error!");
                        C.log(jqXHR);
                        C.log(textStatus);
                        C.log(errorThrown);
                        throw textStatus;
                        throw errorThrown;
                     }
          });
      },

      setNumberArtikel : function()
      {
        this.$number.text(" "+this.artikelCount+" "+this.artikel);
        if (this.artikelCount > 0) {
          this.$number.show();
          $("#wishList").parent().addClass("active");
        } else
          this.$number.hide();

      },


      cleanup : function()
      {
        $(window).unbind("click", this.bindToObj(this.startAnim));
      },



      addItem : function(item) {

          clearTimeout (this.addTimeout);
          this.item = item;
          this.itemsToAdd.push (item);
          $("div.title",this.$container).text(item.productName);
          $("div.group",this.$container).text(item.productGroup);
          $("div.subtitle",this.$container).text(item.productDescription);
          $("div.image img",this.$container).attr("src", item.productImage);

          var self = this;
          var submitAdding = function () {
            $.ajax({
              url: "?eID=json&a=addToMZ",
              type: "POST",
              data: JSON.stringify({data:self.itemsToAdd}),
              dataType: "json",
              //async:false,
              success: self.bindToObj(function(msg){
                          C.log(msg);
                          self.start_animating();
                          self.artikelCount = msg.data.count;
                          self.setNumberArtikel();
                       }),
              error : function(jqXHR, textStatus, errorThrown) {
                          C.log("ajax error!");
                          C.log(jqXHR);
                          C.log(textStatus);
                          C.log(errorThrown);
                          throw textStatus;
                          throw errorThrown;
                       }
            });
            self.itemsToAdd = [];
          };

          this.addTimeout = setTimeout (submitAdding, 1000);

//        C.enable();
//        C.log("item");
//        C.log(item);
//        C.log(this.$ele);
      },

      start_animating : function () {
       //   this.addItem(infoboxItem);

        if (this.state == this.HIDDEN)
          this.animate_show();
        else if (this.state == this.VISIBLE)
          this.completly_visible();
        else if (this.state == this.ANIM_HIDE)
          this.animate_show();
      },

      stopTimer : function () {
        this.$ele.stopTime("IB_ANIMATE_SHOW");
        this.$ele.stopTime("IB_COMPLETELY_VISIBLE");
        this.$ele.stopTime("IB_ANIMATE_HIDE");
        this.$content.stop(); // stop "animation-in-progress"
      },

      animate_show : function ()
      {
        this.$container.show();
        this.state = this.ANIM_SHOW;
        this.stopTimer();
        this.$ele.oneTime(this.animationDuration, "IB_ANIMATE_SHOW", this.bindToObj( this.completly_visible ));
        this.$content.animate({top: 0},this.animationDuration);
      },

      completly_visible : function ()
      {
        this.state = this.VISIBLE;
        this.stopTimer();
        this.$ele.oneTime(this.eventTimeout, "IB_ANIMATE_SHOW", this.bindToObj( this.animate_hide ));
      },

      animate_hide : function ()
      {
        this.state = this.ANIM_HIDE;
        this.stopTimer();
        this.$ele.oneTime(this.animationDuration, "IB_ANIMATE_HIDE", this.bindToObj( this.hidden ));
        this.$content.animate({top: this.targetHeight},this.animationDuration);
      },

      hidden : function ()
      {
        this.state = this.HIDDEN;
        this.$container.hide();
      },


      setAlignMode : function (newMode) {
        var oldMode = this.alignMode;
        this.alignMode = 'top';
        if ( /* newMode == 'top' || */ newMode == 'bottom' || newMode == 'center' || newMode == 'anchor')
          this.alignMode = newMode;

        if (this.alignMode != oldMode) // mode has changed
          this.scrollOccured(); // scroll into new position
      },


      getPageScroll : function () {
        var xScroll, yScroll;
        if (self.pageYOffset) {
          yScroll = self.pageYOffset;
          xScroll = self.pageXOffset;
        }
        else if (document.documentElement && document.documentElement.scrollTop) {
          yScroll = document.documentElement.scrollTop;
          xScroll = document.documentElement.scrollLeft;
        }
        else if (document.body) {// all other Explorers
          yScroll = document.body.scrollTop;
          xScroll = document.body.scrollLeft;
        }
        return new Array(xScroll,yScroll)
      }
    }
    );


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

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


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

/**
 * automatically initialize selectboxes
 */
$(function(){
   var $eles = $("div.selectbox.autoinit");
   if ($eles.length && $.isFunction ($.fn.selectbox)) {
     $eles.selectbox({});
   }
   var value ="";
 });

