/** 
 *  jquery.columnview-1.1.1.js
 *  
 *  Created by Chris Yates on 2009-02-26.
 *  http://christianyates.com
 *  Copyright 2009 Christian Yates and ASU Mars Space Flight Facility. All rights reserved.
 *  
 *  Requires jQuery 1.3.x
 *  Also available with jQuery 1.2.6 support (with Live Query plugin) - see
 *  http://christianyates.com/blog/jquery/finder-column-view-hierarchical-lists-jquery
 *  
 *  Tested with Firefox 3.x, Safari 3.x,4.x, Internet Explorer 6.x,7.x
 *  Dual licensed under MIT and GPL.
 *
 */
 
(function($){
  $.fn.columnview = function(){
    // Hide original list
    $(this).hide();
    
    // Create new top container from top-level LI tags
    var top = $(this).children('li');
    var container = $('<div/>').addClass('containerobj').attr('id','cv'+Math.floor(Math.random()*10e10)).insertAfter(this);
    var topdiv = $('<div class="top"></div>').appendTo(container);
    if($.browser.msie) { $('.top').width('200px'); } // Cuz IE don't support auto width
    $.each(top,function(i,item){
      var topitem = $(':eq(0)',item).clone().data('sub',$(item).children('ul')).appendTo(topdiv);
      if($(topitem).data('sub').length) {
        $(topitem).addClass('hasChildMenu');
        if($.browser.safari){
          $(topitem).css({'margin-right':'15px'});    
        }
        addWidget(topitem);
      }
      // Automatically select GET variable category
      if($(topitem).attr("id") == $.url.param("cat")) {
      	$(topitem).addClass('active');
      	if($(topitem).data('sub').children('li').length) {
	      // Menu has children, so add another submenu
	      submenu(container,topitem);
	    }
      }
    });
    
    // Event handling functions
    $('a',container).live("click",function(event){
      var container = $(this).parents('.containerobj');
      
      // Hide getting started message
      $('#getting-started').fadeOut();
      
      // activate loader
      if($(this).parent().hasClass('feature')) {
      	//event.preventDefault();
      	loadContent(this,event);
      }
      
      // Handle clicks
      var level = $('div',container).index($(this).parents('div'));
      // Remove blocks to the right in the tree, and 'deactivate' other links within the same level
      $('div:gt('+level+')',container).remove();
      $('div:eq('+level+') a',container).removeClass('active').removeClass('inpath');
      $('.active',container).addClass('inpath');
      $(this).addClass('active');
      if($(this).data('sub').children('li').length) {
        // Menu has children, so add another submenu
        submenu(container,this);
      } else {
        // No children, show title instead (if it exists, or a link)
        var title = $('<a/>').attr({href:$(this).attr('href')}).text($(this).attr('title') ? $(this).attr('title') : $(this).text());
        var featurebox = $('<div/>').html(title).addClass('feature').appendTo(container);
        // Set the width
        var remainingspace = 0;
        $.each($(container).children('div').slice(0,-1),function(i,item){
          remainingspace += $(item).width() + 15;
        });
        var fillwidth = $(container).width() - remainingspace;
        $(featurebox).css({'top':0,'left':remainingspace}).width(fillwidth).show();
      }
      return false;
    });

    // Keyboard navigation
    $('a',container).live('keydown',function(key){
      switch(key.which){
        case(37): //left
          $(this).parent().prev().children('.active').focus().click();
          break;
        case(38): //up
          $(this).prev().focus().click();
          break;
        case(39): //right
          if($(this).hasClass('hasChildMenu')){
            $(this).parent().next().children('a:first').focus().click();            
          }
          break;
        case(40): //down        
          $(this).next().focus().click();
          break;
        case(13): //enter
          $(this).dblclick();
          break;
      }
    });

  }; 
  
  // Generate deeper level menus
  function submenu(container,item){
    var leftPos = 0;
    $.each($(container).children('div'),function(i,mydiv){
      leftPos += $(mydiv).width() + 15;
    });
    var submenu = $('<div/>').css({'top':0,'left':leftPos}).appendTo(container);
    if($.browser.msie) { $(submenu).width('200px'); } // Cuz IE don't support auto width
    var subitems = $(item).data('sub').children('li');
    $.each(subitems,function(i,subitem){
      var subsubitem = $(':eq(0)',subitem).clone().data('sub',$(subitem).children('ul')).appendTo(submenu);
      if($(subsubitem).data('sub').length) {
        $(subsubitem).addClass('hasChildMenu');
        if($.browser.safari){
          $(subsubitem).css({'margin-right':'15px'});    
        }
        addWidget(subsubitem);
      }
    });
  }
  
  // Uses canvas, if available, to draw a triangle to denote that item is a parent
  function addWidget(item, color){
    var triheight = $(item).height();
    var canvas = $("<canvas></canvas>").attr({height:triheight,width:10}).addClass('widget').prependTo(item);    if(!color){ color = $(canvas).css('color'); }
    canvas = $(canvas).get(0);
    if(canvas.getContext){
      var context = canvas.getContext('2d');
      context.fillStyle = color;
      context.beginPath();
      context.moveTo(3,(triheight/2 - 3));
      context.lineTo(10,(triheight/2));
      context.lineTo(3,(triheight/2 + 3));
      context.fill();
    } else {
      /**
       * Canvas not supported - put something in there anyway that can be 
       * suppressed later if desired. We're using a decimal character here
       * representing a "black right-pointing pointer" in Windows since IE
       * is the likely case that doesn't support canvas.
       */
      $("<span>&#9658;</span>").addClass('widget').css({'height':triheight,'width':10}).prependTo(item);
    }
  }
  
  // Load Dynamic content
  function loadContent(item,event) {
	
	var loading = $("#loading");
	var container = $("#products");
	var link = $(item).attr("href");
	
	event.preventDefault();
	
	//show the loading bar
	showLoading();
	container.fadeOut();
	
	//define the target and get content then load it to container
	if((link == "#") || (link == "http://www.stewartsequip.ca/products.php#") || (link == "http://www.stewartsequip.com/products.php#")) { link = "/products/default.html";}
	container.load(link, hideLoading() );
	container.fadeIn();
  };
	
  //show loading bar
  function showLoading(){
	$("#loading")
	.css({opacity:"1"});
	$("loading").show();
  }
  
  //hide loading bar
  function hideLoading(){
	$("#loading").fadeTo(1000, 0);
	$("#loading").hide();
  }; 
  
})(jQuery);

$(document).ready(function() { $('#columnized').columnview(); });