(function($) {
  // Private Variables and Methods
  var subMenu = {
    opt: {},

    // Parse the json script into html.
    // The li's will be limited so that it lists evenly across the columns (default:6)
    parseJSON: function(json) {
      var parts = [];
      var total = 0;
      var count = 0;
      var countcat = 0;
      var titlec = "";
      // Get the total number of items for the whole section
      $.each(json, function() { 
        total += this.items.length 
      });
      
      // Set the number of items per column so we roughly get the same amount of items per column
      count = Math.round(total/subMenu.opt.columns);
        
      // Create the submenu
     
      parts.push('<div class="sub_menu_O">');
      parts.push('<div class="sub_menu_I">');
      
      $.each(json, function() {        
        var li = [];
         
        if(this.title.toLowerCase()=="categories")
        { 
          titlec = "categories";
        }  
               
        parts.push('<div class="'+ this.title.toLowerCase() +'">');
        parts.push('<h4>'+ this.title +'</h4>');
                
        $.each(this.items, function() {
          li.push('<li><a href="'+ this.url +'">'+ this.title +'</a></li>');
          if( titlec == "categories")
            countcat++;
        });
      
         if(countcat<count && titlec == "categories")
          { 
            for(var i=0;i<=(count-countcat);i++)
                li.push('<li><a href="#">test</a></li>');
          }
                     
        var columns = subMenu.arrayChunk(li, count);
                
        $.each(columns, function() {
          parts.push('<ul>'+ this.join('') +'</ul>');
        });
                
        parts.push('</div>');        
      });
      
      parts.push('<br style="clear:both;" />');
      parts.push('</div>');
      parts.push('</div>');
     

      return parts.join('');
    },

    arrayChunk: function(input, size) {
      // Split array into chunks 
      // discuss at: http://phpjs.org/functions/arrayChunk
      // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
      // *     example 1: arrayChunk(['Kevin', 'van', 'Zonneveld'], 2);
      // *     returns 1: {0 : {0: 'Kevin', 1: 'van'} , 1 : {0: 'Zonneveld'}}
      for(var x, i = 0, c = -1, l = input.length, n = []; i < l; i++){
        (x = i % size) ? n[c][x] = input[i] : n[++c] = [input[i]];
      }
      
      return n;
    },
    
    debug: function(msg) {
      if (window.console && window.console.log) {
        window.console.log(msg);
      }
    }
  };

  // Public Variables and Methods
  $.subMenu = {
    defaults: {
      url:     '',
      json:    {},
      columns: 6,
      append:  'li'
    }
  };

  // Prototype Methods
  $.fn.extend({
    // Loads json script and renders the submenu
    addSubMenu: function(options) {
      subMenu.opt = $.extend($.subMenu.defaults, options);

      var menus = this;

      $.getJSON(subMenu.opt.url, function(data) {
        return menus.each( function() {
          $(this).children(subMenu.opt.append)
            .append(subMenu.parseJSON(data[$(this).attr('id')]))
              .observeSubMenu();

          $('.sub_menu_I > :first-child').each( function() {
            $(this).addClass('first');
          });          
        });        
      });
    },
    
    // Observe hover events
    observeSubMenu: function() {
      var menu   = $(this).find(".sub_menu_O");
      var parent = this.parent();
      
      
      // Fix so that the animation works first time
      $(':hover .sub_menu_O').css('display', 'none');
      
      // Use hoverIntent to tweak the hover events
      return $(this).hoverIntent({    
        interval: 300,
        over: function() {
          menu.fadeIn('fast', function() {
            parent.css('z-index', 50);  
           // $('.sub_menu_O').css('z-index', -100);
            
             
          });
          
         
           $('select').hide(); // stops the selects from sitting above the menu
          
           if(parent.find("span").html()=="Women")
           {
                //$(".sub_menu_O").attr("onclick","/index/all-categories&gender=woman");
                $(".sub_menu_O").css("cursor","pointer");
                 $(".sub_menu_O").bind("click", function(e){
                 window.location.href =  "/index/all-categories&gender=woman";
                 });

           }
            if(parent.find("span").html()=="Men")
           {
                  $(".sub_menu_O").css("cursor","pointer");
                 $(".sub_menu_O").bind("click", function(e){
                 window.location.href =  "/index/all-categories&gender=man";
                 });
           }
             if(parent.find("span").html()=="Sale")
           {
                  $(".sub_menu_O").css("cursor","pointer");
                 $(".sub_menu_O").bind("click", function(e){
                 window.location.href =  "/index/all-categories&gender=sale";
                 });
           }
           
         // $('select').hide(); // stops the selects from sitting above the menu
        },
        out: function() {
        
          menu.fadeOut('normal', function() {
          
            parent.css('z-index', 100);  
            $('select').show();
          });
        }
      });
    }
  });
})(jQuery);
