//_______________________________________________________________________
//   |       |
//   | 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: 892 $
//                     $Date: 2011-10-27 22:22:51 +0200 (Do, 27 Okt 2011) $
//                     $Author: Bjoern.Moenikes $
//

// mainMenuMouseOver Plugins - displays these nice main menu mouse over effects
// 
// requires: jquery.timers

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

      options = $.extend( {
          mouseoverTimeout : 1500,   // time span that has to pass until popup appears
          showSubmenu : false   // show submenu?
        },
        options );

      return this.each (function () {
        if (!this._mmoController) {
          this._mmoController = new MmoPlugin (this, options);
          $.event._mmoCleanup[$.event.guid] = this._mmoController;
          $.event._mmoCleanup[$.event.guid++].init (options);
        }
      });
    },


    _mmoDestroy : function () {
      return _eachCall.call (this, 'cleanup');
    }
  });


  var _eachCall = function (f, a1, a2, a3) {
    return this.each (function () {
      if (this._mmoController)
        this._mmoController[f](a1, a2, a3);
    });
  };


  $(window).bind('unload', function() {
    var els = $.event._mmoCleanup || [];
    for (var i in els) {
      $(els[i].ele)._mmoDestroy();
    }
  });


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

    init : function(s) {
        // get init parameters
        this.mouseoverTimeout = s.mouseoverTimeout;
        this.showSubmenu = s.showSubmenu;
        
        // set internal parameters
        this.timerRunning = false;
        this.popupVisible = false;
        
        this.$activePage = $("div.mainMenuContainer li.active");  // active paging tab
        
      // do not show mouse over for active menu items
//      if (!this.$ele.hasClass("current") && !this.$ele.hasClass("active")) {
        if (true){
        var str = $("a", this.$ele).attr("href");
        if (str == undefined)
           return;
        str = str.split("/");
        var tgt = str[0];
        var url ="/MouseOverPopups/"+tgt+"/?type=9";
        
        this.submenu = null;
        switch(tgt) {
            case 'kapsto':
            case 'kapstor':
                this.submenu = "kapsto";
                break;
            case 'k-tech':
            case 'k-techr':
                this.submenu = "ktech";
                break;
            case 'famac':
            case 'famacr':
                this.submenu = "famac";
                break;
            case 'teku':
            case 'tekur':
                this.submenu = "teku";
                break;
            default:
                this.submenu = "default";
        }

        this.$popup = $("<div class=\"mmocontainer\"> </div");
        this.$ele.bind("mouseenter", this.bindToObj(this.showWrapper));
        this.$ele.bind("mouseleave", this.bindToObj(this.hideWrapper));
        var $targetContainer = this.options.targetContainer ?
        $(this.options.targetContainer) : this.$ele;
//        var $sub = $("div.mainMenu_secondLevel_"+this.submenu).clone();
//        $sub.show(); //.css("margin-left","-8px");
//        console.log(this.submenu);
//        console.log($sub);
//        this.$spacer = $('.mainMenu_secondLevel', $targetContainer);
//        this.$spacer = $('<div style=\"display: none;\" class="mmo-spacer">');
//        this.$spacer.append($sub);
//        $targetContainer.append(this.$spacer);
        this.$popup.append($("<div class=\"mmoloading mmo-container\" style=\"width: 685px; height: 273px;display: none; margin-left: 0px;\"><div class=\"mmoloadingmsg\">Loading data</div></div>"));
        $targetContainer.append(this.$popup);

        

        // load html data according to mapping
        //$.ajax({url : "/index.php?id="+mapping[tgt]+"&type=10", context: this, success: this.ajaxSuccess, error: this.ajaxError, dataType: "html" });
        $.ajax({
          url : url,
          context: this,
          success: this.ajaxSuccess,
          error: this.bindToObj(this.ajaxError),
          dataType: "html"
        });
      }
    },

    ajaxSuccess : function(data, textStatus, XMLHttpRequest) {
      var $data = $("<div>").html(data);
      if ($data.length == 0) // do not work on real document
        return;
      this.$popup.append($data); //.context.getChildren());
      $("div.mmoloading",this.$popup).remove();
      //$("div.mmoloadingmsg",this.$popup).remove();
    },

    ajaxError : function(event, request, settings){
      $("div.mmoloading",this.$popup).remove();
      //$("div.mmoloadingmsg",this.$popup).remove();
      this.$popup.append("<p>Error loading popup "+this.$ele.attr("id")+"</p>");
    },
    
    showWrapper : function() {
      
//      C.log("showWrapper: timer"+this.timerRunning);
   
      // no mouseover effect for currently active menus
      if (this.$ele.hasClass("active"))
        return;
        
      if (this.timerRunning == false && this.popupVisible == false)
      {
//        C.log("starting timer");
        this.timerRunning = true;       
        this.$ele.oneTime(this.mouseoverTimeout, "mmoTimeout"+this.submenu, 
                          this.bindToObj( 
                          function() {
//                          C.log("timer finished");
                            this.timerRunning = false;
                            this.popupVisible = true;
//                          C.log("show");
                            this.show();
                          })); 
        }
    },
    
    hideWrapper : function() {
//        C.log("hideWrapper: timer "+this.timerRunning);
        if (this.timerRunning == true && this.popupVisible == false)
        {
            // stop timer
//            C.log("stop timer");
            this.$ele.stopTime("mmoTimeout"+this.submenu);
            this.timerRunning = false;
            return;
        }
        else if (this.popupVisible == true) {
//            C.log("hide");
            this.hide();
            this.popupVisible = false;
        }
    },

    show : function () {     
      var $temp = $("div.mmoloading",this.$popup);
      if ($temp.length > 0)
          $temp.show();
      if (this.options.overedStyleClass) {
        this.$ele.addClass(this.options.overedStyleClass);
        if (this.$ele != this.$activePage)
            this.$activePage.removeClass("active");
      }
      
      if (this.options.anchorObject) {
        var anchorOffset = $(this.options.anchorObject).offset();
        if (this.options.anchorOffset) {
          if (this.options.anchorOffset.top) {
            anchorOffset.top += this.options.anchorOffset.top;
          }
          if (this.options.anchorOffset.left) {
            anchorOffset.left += this.options.anchorOffset.left - 5;
          }
        }
        this.$popup.offset(anchorOffset);
      }

      // hide submenu?
      if (this.showSubmenu == false)
          $(".mmo-container",this.$popup).css("margin-top",-1);
    },

    hide : function () {
      if (this.options.overedStyleClass) {
        this.$ele.removeClass (this.options.overedStyleClass);
        if (this.$ele != this.$activePage)            
            this.$activePage.addClass("active");
      }

      //this.$popup.hide();
      //this.$spacer.hide();
      //$("#mainMenu_secondLevel").css("visibility",""); // show old menu
    },


    cleanup : function() {
    }
  });
})(jQuery);

