(function($, window, document) {

  var methods = {

    init : function(options) {
      _self = this;
                         
/*
      var ulMenu = $("<ul></ul>").attr({ 
        "class": ["left_menu"].join(' ')            
      }).appendTo(this);
*/
      return this.each(function() {
      });    
    }
  };

  $.fn.menu = function( method ) {
    
    this.selectCategory = function(idCategory) {
      this.idCategorySelected = idCategory;
    }
    
    //animate the opening of the branch (span.grower jQueryElement)
    function openBranch(jQueryElement, noAnimation) {
    		jQueryElement.addClass('OPEN').removeClass('CLOSE');
    		if(noAnimation)
    			jQueryElement.parent().find('ul:first').show();
    		else
    			jQueryElement.parent().find('ul:first').slideDown('slow', 'swing');
    }
    //animate the closing of the branch (span.grower jQueryElement)
    function closeBranch(jQueryElement, noAnimation) {
    	jQueryElement.addClass('CLOSE').removeClass('OPEN');
    	if(noAnimation)
    		jQueryElement.parent().find('ul:first').hide();
    	else
    			jQueryElement.parent().find('ul:first').slideUp('slow', 'swing');
    }
    
    //animate the closing or opening of the branch (ul jQueryElement)
    function toggleBranch(jQueryElement, noAnimation) {
    	if(jQueryElement.hasClass('OPEN')) {
      	closeBranch(jQueryElement, noAnimation);
    	} else
    		openBranch(jQueryElement, noAnimation);
    }

    function addMenuButton(parent, param) {
      var li = $("<li></li>").attr("id", "cat" + param.id).appendTo(parent);
      var ahref = $("<a>" + param.name + "</a>").appendTo(li);
      ahref.click(function(e) {
        e.preventDefault(); 
        window.location.href = "category.php?idcat=" + param.id;
        return false;
      });   
      return li;   
    }
    
    // Přidání kostičky s produktem
    this.addRow = function(parent, param, level) {  
      _self = this;
      var idCategorySelected = this.idCategorySelected;

      if (param.level_last == "1") {
        var liMenu = addMenuButton(parent, param);
        if (idCategorySelected == param.id) liMenu.find("a").css ({ color: "orange" }); 
      }
      if (param.level_last == "0") {
        var liMenu = addMenuButton(parent, param);
        if (idCategorySelected == param.id) liMenu.find("a").css ({ color: "orange" }); 
        var ulMenu = $("<ul></ul>").attr({"loaded" : "false"}).appendTo(liMenu);
        grower = $("<span class='grower OPEN'> </span>").prependTo(liMenu);
        grower.addClass('CLOSE').removeClass('OPEN').parent().find('ul:first').hide();
    		grower.click(function(){
    			toggleBranch($(this));
    		});
        
        liMenu.mouseover(function() {
          if (ulMenu.attr("loaded") == "false") {
            ulMenu.attr("loaded", "true");
            $.ajax({ 
              async: false,
              url: "ajax/category_op.php", 
              data: "op=preloadCategory&idCategory=" + param.id,
              type: "post", 
              dataType: 'json',
              success: function(data) {
                if (data !== null && typeof data.records !== 'undefined') {
                  $.each(data.records, function() {
                    var oData = jQuery.parseJSON(this.toString());
                    liMenu = _self.addRow(ulMenu, { "id" : oData.id, "id_parent" : oData.id_parent, "name" : oData.name, "level_last" : oData.level_last, "id_distributor" : oData.id_distributor }, level + 1);
                  });
                }                                                                                                                                                  		
              }
            });
          }
        });
      }
      return liMenu;
/*
      $.ajax({ 
        async: false,
        url: "ajax/category_op.php", 
        data: "op=preloadMenuCategory&idp=" + param.mega_id,
        type: "post", 
        dataType: 'json',
        success: function(data) {
          alert(data.records);

          if (data !== null && typeof data.records !== 'undefined') {
            if ((data.records.length < 2) || (level == 2)) {      
              var liMenu = addMenuButton(obj, "<a href=\"index.php?cat=" + param.id + "\">" + param.category + "</a>", "submenu");
              ulMenu = liMenu;
            } else {
              var liMenu = addMenuButton(obj, "<a>" + param.category + "</a>", "odd");
              var ulMenu = $("<ul></ul>").attr({ 
                "class": ["left_menu"].join(' ')            
              }).appendTo(liMenu);
            }
            $.each(data.records, function() {
              var oData = jQuery.parseJSON(this.toString());
              _self.addRow(ulMenu, { "id" : oData.id, "mega_id" : oData.mega_id, "mega_idp" : oData.mega_idp, "category" : oData.category }, level + 1);
            });
          } else {
            var liMenu = addMenuButton(obj, "<a href=\"index.php?cat=" + param.id + "\">" + param.category + param.mega_id + "</a>", "submenu");
            return;
          }

         }
      });
*/      
/*
      if (hasSubmenu) {
        var liMenu = addMenuButton(this, "<a>" + param.category + "</a>", "odd");

        liMenu.click(function() {
          $('.submenu').remove();
          $.each(submenu, function() {
            var oData = jQuery.parseJSON(this.toString());
            addMenuButton(liMenu, "<a href=\"index.php?cat=" + oData.id + "\">" + oData.category + "</a>", "submenu");
          });
        });
         
      } else {
        addMenuButton(this, "<a href=\"index.php?cat=" + param.id + "\">" + param.category + "</a>", "odd");
      }

      $.each(submenu, function() {
        var oData = jQuery.parseJSON(this.toString());
        
        if (hasSubmenu && (oData.id == param.selectedMenu)) liMenu.click();
      });
*/      
      return true;
    }  

//    this.setAjaxSource = function(f) {
//      this.ajaxSource = f;
//    }

/*
    findInputObjects = function(oThis) {
      var tmp = new Array();
      $(oThis).find('input').each(function(i) {
        if (this.type == 'text' || this.type == 'hidden' || this.type == 'checkbox') {
          var obj = new Object();
          obj.name = this.name;
          obj.type = this.type;
          tmp.push(obj);
        } 
      });
      $(oThis).find('select').each(function(i) {
        if (this.type == 'select-one') {
          var obj = new Object();
          obj.name = this.name;
          obj.type = this.type;
          tmp.push(obj);
        } 
      });
      $(oThis).find('textarea').each(function(i) {
        if (this.type == 'textarea') {
          var obj = new Object();
          obj.name = this.name;
          obj.type = this.type;
          tmp.push(obj);
        } 
      });
      oThis.formFields = JSON.stringify(tmp);
    }

    disableEscapeButton = function(oThis) {
      $(oThis).find('input').keydown(function (event) {
        if (event.keyCode == 27) {
          $(this).val("");
          return false;
        }
      });
    }
    
    this.jGetInputSelect = function(sObj) {
      var aCheckboxs = new Array();
      $(sObj, this).find('option[selected]').each(function(i) {aCheckboxs.push(this.value); });
      var jStr = JSON.stringify(aCheckboxs);      
      return jStr;
    }

    loadInputObjects = function(oThis, oColumns, jData) {
      var jFormFields = jQuery.parseJSON(oThis.formFields);
      $.each(jFormFields, function() {
        if (this.type == "text") $("input[name$=" + this.name + "]", oThis).val(jData[this.name]);  
        if (this.type == "hidden") $("input[name$=" + this.name + "]", oThis).val(jData[this.name]);  
        if (this.type == "checkbox") $("input[name$=" + this.name + "]", oThis).attr('checked', ((jData[this.name]==1)?true:false));
        if (this.type == "select-one") $("select[name$=" + this.name + "]", oThis).val(jData[this.name]);
        if (this.type == "textarea") $("textarea[name$=" + this.name + "]", oThis).html(jData[this.name]);
      });  
      return true;
    }
*/

    // Zpracování metod
    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    
        
  };

})(jQuery, window, document);

