(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

address_skip_load = false;

function header_menu_start(){
  parse_menu_activate_parent($('#navmenu li.selected'));

  var menu_data = parse_menu($('ul#navmenu'));
  var $menu = $('#menu-wrapper');
  var force_menu_refresh = false;
  var passed_first_external = false;

  $.address.externalChange(function(event) {
    var hash = window.location.hash.slice(2);
    var path = window.location.pathname.slice(1);

    // If no hash, but there's a path, load that path
    if (!hash && path){
       window.location.href = 'http://' + window.location.host + '/#' + window.location.pathname;
       return false;
    }else if(hash){
      passed_first_external = true;
    }

    if (passed_first_external) {
      force_menu_refresh = true;
      load_content(event.value);
    }else{
      //console.log('First External Load Skipped:', event.value);
      passed_first_external = true;
    }
  });

  $.address.internalChange(function(event) {
    if (!address_skip_load){load_content(event.value);}else{
      //console.log('Load Skipped:', event.value);
      address_skip_load = false;
    }
  });

  // Bind clicks for extra login/register
  $('#login a.login, #login a.register').click(function(){
    $('#nav-tabs li a.login').click();
    if ($(this).is('.register')){$.address.value('/member/register');}
    return false;
  });

  // Manage top nav tabs bindings
  $('#nav-tabs li a').click(function(){
    var tab = $(this).attr('class');

    // If the tab isn't already selected, switch tabs
    if (!$('#header .wrap.selected').is('.'+tab)){
      // Fade out old content
      $('#header .wrap.selected').fadeOut('slow', function(){$(this).hide();}).removeClass('selected');

      // Fade in new content
      $('#header .wrap.'+tab).fadeIn('slow').addClass('selected');

      // Set new text
      $('#nav-tabs .current').text($(this).text());

      // Set button selected
      $('#nav-tabs li').removeClass('selected');
      $(this).parent().addClass('selected');
    }
    
    if (!$(this).is('.login')){ // Don't activate the login link
      $.address.value($(this).attr('href'));
    }
    return false;
  });

  setup_menu();

  function setup_menu(){
    $menu.html('');
    // Setup ul horizontal depth of 5 levels
    $.each([0,1,2,3,4], function(i){
      $menu.append('<ul/>');
      $('ul:last', $menu).addClass('menu-level level-'+ i).data('level', i);
    });

    $('ul', $menu).hoverIntent({
      over: menu_flydown,
      out: menu_flyup,
      timeout: 200
    });

    // render the root and follow active links [init only]
    render_children(0, menu_data, '/', true);
  }

  // Hover slide out for large menus..
  function menu_flydown(){
    var base_height = $menu.height();
    if ($(this).is('.active')){
      $(this).stop().height('auto');
        var menu_height = $(this).height();
      $(this).height('');

      //console.log('IN menu_height:', menu_height, ' base_height:', base_height);
      if (menu_height > base_height){
        $(this).height(base_height);
        $(this).stop(true, true).animate({height: menu_height}, 500);
        $('li', this).stop(true, true).animate({top: 0}, 500);
        $('span', this).stop(true, true).fadeOut(500);
      }
    }
  }

  // Hover slide up in for large menus...
  function menu_flyup(){
    var base_height = $menu.height();
    var arrow_height = 0;
    var active = $('a.active', this).parent();

    var link_offset = 0;

    if (active.length){
      link_offset = active.position().top + active.height()
      //console.log('sel_item_bottom:', link_offset);
      if (link_offset > (base_height - arrow_height)){
        link_offset = base_height - (active.position().top+active.height()) - arrow_height;
      }else{
        link_offset = 0;
      }
    }

    if ($(this).is('.active') && $(this).height() != base_height){
      $(this).stop(true, true).animate({height: base_height}, 500, function(){$(this).height('');});

      if (link_offset){
        $('li', this).stop(true, true).animate({top: link_offset}, 500);
      }

      $('span',this).stop(true, true).fadeIn(500);

    }else{
      if (link_offset && !$(this).is('.active_sel')){
        $('li', this).stop(true, true).animate({top: link_offset}, 500);
      }
    }
  }

  function render_children(level, items, base_path, init_build){
    // If we're building out anything past the first menu level, hide the welcome
    if (level > 0) {
      if (init_build){$('#header-welcome').hide();}else{$('#header-welcome').fadeOut('slow');}
    }

    // Reference UL
    $ul = $('ul.level-'+level);
    clear_menus(level);
    $ul.addClass('active');

    var render_queue_item = null;

    if (items.length >= 6){
      $ul.append('<span class="more more_bottom"/>');
    }

    // Add menu items (and bind click for next level)
    $.each(items, function(i, item){
      $ul.append('<li><a href="' + item.p + '" ' + (item.active ? 'class="active"' : '') + '>' + item.t + '</a></li>');

      // If active and menu is being initialized, build out the next level
      // (once we're done build the list, of course)
      if (init_build && item.active && item.children != undefined){
        render_queue_item = item;
      }

      $('li:last a', $ul).click(function(){

        if (item.children != undefined){
          render_children(level+1, item.children, item.p + '/');
          if ($(this).attr('href') != '/nolink'){$.address.value($(this).attr('href'));}
        }else{
          clear_menus(level+1);

          if ($(this).attr('href') != '/nolink'){$.address.value($(this).attr('href'));}
          //return true; // Activate end link
        }

        $('ul.level-'+level+' a.active').removeClass('active');
        $(this).addClass('active');

        return false;
      });
    });

    if(render_queue_item){
      render_children(level+1, render_queue_item.children, render_queue_item.p + '/', init_build);
    }

    // If showing the menu forcefully, don't screw around with the animation
    if (init_build){$ul.each(menu_flyup);}else{
      $ul.hide().fadeIn('slow', menu_flyup);
    }

  }

  function clear_menus(level){
    // Clear all ULs this level and above
    $('ul.menu-level').each(function(){
      if ($(this).data('level') >= level){
        $(this).html('');
        $(this).removeClass('active');
        $('span', this).remove();
      }
    });
  }

  // Parse Ul/li menu into JSON
  function parse_menu(dom_root){
    var data_root = [];
    dom_root.children('li').each(function(){
      var menu_item = {t: $('a:first', this).text(), p: $('a:first', this).attr('href')};
      if ($(this).is('.selected')){
        menu_item.active = true;
      }

      if ($(this).children('ul').length){
        menu_item.children = parse_menu($(this).children('ul'));
      }
      data_root.push(menu_item);
    });
    return data_root;
  }

  function parse_menu_activate_parent(node){
    var parent = node.parent().parent();
    if (parent[0]){
      if (parent[0].tagName == 'LI'){
        parent.addClass('selected');
        parse_menu_activate_parent(parent);
      }
    }
  }

  function load_content(path){
    $('#content').prepend('<div id="content_loader"/>');

    $.ajax({
      url: path,
      success: load_content_process,
      error: load_content_process,
      dataType: 'html'
    });

  }

  function load_content_process(data_xhr, status){

    // Let 404 errors through to allow their page messages to render
    if (data_xhr.status == 404){
      status = '404';
      data_xhr = data_xhr.responseText;
    }

    if (status != 'error') {
      if ($('#content', data_xhr).length != 0 && data_xhr !=''){
        // Set page title
        $.address.title(data_xhr.match(/<title>(.*?)<\/title>/)[1]);

        // Pull over various ID content
        $.each(['masthead', 'content', 'footer'], function(i, id){
          $('#'+id).html($('#'+id, data_xhr).html());
        });
        
        // Pull over content class
        $('#content').attr('class', $('#content', data_xhr).attr('class'));

        // And for good measure, copy the classes to the wrapper as well
        $('#wrapper').attr('class', $('#content').attr('class'));

        // Need this object for reference, otherwise the HTML text is readonly
        // by the following functions!
        if ($('#navmenu', data_xhr).length){
          $navmenu = $('#navmenu', data_xhr);

          if (force_menu_refresh){
            parse_menu_activate_parent($('li.selected', $navmenu));
            menu_data = parse_menu($navmenu);
            render_children(0, menu_data, '/', true);
            force_menu_refresh = false;
          }
        }

        // Run page init scripts
        page_load_init();
      }else{
        status = 'error';
        data_xhr = {};
        data_xhr.status = 'Content element not found';
      }
    }

    if (status == 'error') {
      var msg = 'Sorry but there was an error: ';
      $("#content").html('<div class="error">' + msg + data_xhr.status + " " + data_xhr.statusText + '</div>');
    }
  }

}


function load_product_content(path){
  $('#product-list').prepend('<div id="content_loader"/>');
  $.ajax({
    url: path,
    success: load_product_content_process,
    error: load_product_content_process,
    dataType: 'html'
  });

}

function load_product_content_process(data_xhr, status){
  if (status != 'error') {
    if ($('#product-list', data_xhr).length != 0 && data_xhr !=''){
      // Set page title
      $.address.title(data_xhr.match(/<title>(.*?)<\/title>/)[1]);

      // Pull over various ID content
      $.each(['product-list'], function(i, id){
        $('#'+id).html($('#'+id, data_xhr).html());
      });

      // Run page init scripts
      page_load_init();
    }else{
      status = 'error';
      data_xhr = {};
      data_xhr.status = 'Content element not found';
    }
  }

  if (status == 'error') {
    var msg = 'Sorry but there was an error: ';
    $("#product-list").html('<div class="error">' + msg + data_xhr.status + " " + data_xhr.statusText + '</div>');
  }
}
