/*******************************************************************************
*                                SPLat Controls                                *
*                          Product Development Group                           *
*                            Melbourne,  AUSTRALIA                             *
*                            http://www.splatco.com                            *
********************************************************************************
   DESCRIPTION:
   This is the website menu.

   DEPENDANCIES:
   - jquery
   - jquery.ddsmoothmenu-1.4.js
   - /menu.htm
   - /css/menu.css

********************************************************************************
*           Copyright (c) 2010 SPLat Controls. All rights reserved.            *
*******************************************************************************/

//** Smooth Navigational Menu- By Dynamic Drive DHTML code library: http://www.dynamicdrive.com
//** Script Download/ instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/
//** Menu created: Nov 12, 2008

//** Dec 12th, 08" (v1.01): Fixed Shadow issue when multiple LIs within the same UL (level) contain sub menus: http://www.dynamicdrive.com/forums/showthread.php?t=39177&highlight=smooth

//** Feb 11th, 09" (v1.02): The currently active main menu item (LI A) now gets a CSS class of ".selected", including sub menu items.

//** May 1st, 09" (v1.3):
//** 1) Now supports vertical (side bar) menu mode- set "orientation" to 'v'
//** 2) In IE6, shadows are now always disabled

//** July 27th, 09" (v1.31): Fixed bug so shadows can be disabled if desired.
//** Feb 2nd, 10" (v1.4): Adds ability to specify delay before sub menus appear and disappear, respectively. See showhidedelay variable below

var ddsmoothmenu={

//Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs):
arrowimages: {down:['downarrowclass', 'down.gif', 23], right:['rightarrowclass', 'right.gif']},
transition: {overtime:300, outtime:300}, //duration of slide in/ out animation, in milliseconds
shadow: {enable:true, offsetx:5, offsety:5}, //enable shadow?
showhidedelay: {showdelay: 100, hidedelay: 200}, //set delay in milliseconds before sub menus appear and disappear, respectively

///////Stop configuring beyond here///////////////////////////

detectwebkit: navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1, //detect WebKit browsers (Safari, Chrome etc)
detectie6: document.all && !window.XMLHttpRequest,

//function to fetch external page containing the panel DIVs
getajaxmenu:function( $, setting )
{
   var data = '';
   var splatcoid = $.cookie( 'splatcoid' );
   var $menucontainer=$('#'+setting.contentsource[0]); //reference empty div on page that will hold menu

   $menucontainer.html("Loading Menu...");

   if( splatcoid )
      data = 'splatcoid=' + splatcoid;

   $.ajax({
      cache: true, //permit caching (menu set to expire after 30min)
      url: setting.contentsource[1], //path to external menu file
      data: data,
      async: true,
      error:function(ajaxrequest){
         $menucontainer.html('Menu error ' + ajaxrequest.responseText)
      },
      success:function(content){
         $menucontainer.html(content)
         ddsmoothmenu.buildmenu($, setting)
         breadcrumbs(content);
      }
   })
},

buildmenu:function($, setting)
{
   //copy the default values
   var smoothmenu=ddsmoothmenu;

   //reference main menu UL
   var $mainmenu=$( "#" + setting.mainmenuid + ">ul" );

   $mainmenu.parent().get(0).className = setting.classname || "ddsmoothmenu";

   //get all list items that have children
   var $headers=$mainmenu.find("ul").parent();

   //loop through each LI header
   $headers.each( function(i)
   {
      var $curobj=$(this).css({zIndex: 100-i}); //reference current LI header

      var $subul=$(this).find('ul:first');

      $subul.data('timers', {});

      this._dimensions={ w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()};

      //TRUE if this is top level header
      this.istopheader = $curobj.parents("ul").length == 1;

      //position the first children below the toplevel menu (seems only required for IE6)
      if( this.istopheader && setting.orientation!='v' )
         $subul.css( {top:this._dimensions.h + "px"} );

      //add down arrows or '...'
      if( this.istopheader )
         //add padding to the "A" or "SPAN" and then append a down arrow image
         $curobj.children(":first").css(this.istopheader? {paddingRight: smoothmenu.arrowimages.down[2]} : {})
         .after( '<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1])
         +'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0])
         + '" style="border:0;" />' );
      else
         //follow the "a" or "span" with a new "span" that contains "..." and is positioned off the right edge
         $curobj.children(":first").after( '<span style="padding:0; position:absolute; right:1em; top:0;" >...</span>' );

      if( smoothmenu.shadow.enable )
      {
         //store this shadow's offsets
         this._shadowoffset=
         {
            x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w),
            y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)
         };
         if (this.istopheader)
            $parentshadow=$(document.body);
         else
         {
            var $parentLi=$curobj.parents("li:eq(0)");
            $parentshadow=$parentLi.get(0).$shadow;
         }
         //insert shadow DIV and set it to parent node for the next shadow div
         this.$shadow = $('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>')
         .prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'});
      }
      $curobj.hover(
      //hoverIn
      function(e)
      {
         var $targetul=$subul; //reference UL to reveal

         var header=$curobj.get(0); //reference header LI as DOM object

         clearTimeout( $targetul.data('timers').hidetimer );

         $targetul.data('timers').showtimer = setTimeout(function()
         {
            header._offsets = {left:$curobj.offset().left, top:$curobj.offset().top};

            var menuleft = header.istopheader && setting.orientation != 'v' ? 0 : header._dimensions.w - 5;

            //calculate this sub menu's offsets from its parent
            menuleft = header._offsets.left + menuleft + header._dimensions.subulw > $(window).width()
            ? ( header.istopheader && setting.orientation != 'v' ? -header._dimensions.subulw + header._dimensions.w : -header._dimensions.subulw + 5)
            : menuleft;

            /* There's a horrible bug in IE6,7,8 in that positioning a submenu based on the left edge fails when the parent has right aligned text.
            No other browser suffers this problem, but the solution is to position using the right edge.  This works in IE and all other browsers. */
            if( !header.istopheader )
            {
               //figure the position of the right edge based on the chosen left edge
               menuright = header._dimensions.w - menuleft - header._dimensions.subulw;

               //set the css to use the right edge
               menuedge = {right:menuright+"px"};
            }
            else
               //if we're the first submenu, stick with the left edge
               menuedge = {left:menuleft+"px"};

            //add the width too
            menuedge.width = header._dimensions.subulw+'px';

            //if 1 or less queued animations
            if( $targetul.queue().length <= 1 )
            {
               $targetul.css( menuedge ).fadeIn( ddsmoothmenu.transition.overtime );

               if( smoothmenu.shadow.enable )
               {
                  var shadowleft = header.istopheader ? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft;
                  var shadowtop = header.istopheader ? $targetul.offset().top+smoothmenu.shadow.offsety : header._shadowoffset.y;
                  //in WebKit browsers, restore shadow's opacity to full
                  if (!header.istopheader && ddsmoothmenu.detectwebkit)
                  {
                     header.$shadow.css({opacity:1});
                  }
                  header.$shadow.css( {overflow:'', width:header._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'} ).animate( {height:header._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime );
               }
            }
         }, ddsmoothmenu.showhidedelay.showdelay);
      },
      //hoverOut
      function(e)
      {
         var $targetul=$subul;

         var header=$curobj.get(0);

         clearTimeout($targetul.data('timers').showtimer);

         $targetul.data('timers').hidetimer = setTimeout(
         //on timeout
         function()
         {
            $targetul.fadeOut( ddsmoothmenu.transition.outtime );
            if( smoothmenu.shadow.enable )
            {
               //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them
               if( ddsmoothmenu.detectwebkit )
               {
                  header.$shadow.children('div:eq(0)').css({opacity:0});
               }
               header.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime);
            }
         }, ddsmoothmenu.showhidedelay.hidedelay );
      } ); //end hover
   }); //end $headers.each()

   //now we've calculated the dimensions, hide all the menus
   $mainmenu.find("ul").hide();

   //when hovering on a parent list item, add the "selected" class (:hover is limited in IE6)
   $mainmenu.find("li").hover(
   //hoverIn
   function(e)
   {
      //add the 'selected' class to the list item <li> AND content <a>, <span>, <img>
      $(this).addClass('selected').children('a,span,img').addClass('selected');
   },
   //hoverOut
   function(e)
   {
      //remove the 'selected' class from list item & content
      $(this).removeClass('selected').children('a,span,img').removeClass('selected');
   });

   //this code fades the parent menu when focus moves to a submenu
   //(note the parent doesn't lose focus because the submenu DOM is within the parent even though it's on screen position is different)
   $mainmenu.find("ul").hover(
   //hoverIn
   function(e)
   {
      //add the 'fade' class to the parent ul container AND all it's list items AND their content items
      $(this).parents('ul:first').addClass('fade').children('li').addClass('fade').children('a,span,img').addClass('fade');
   },
   //hoverOut
   function(e)
   {
      //remove the 'fade' class to the parent ul container
      $(this).parents('ul:first').removeClass('fade').children('li').removeClass('fade').children('a,span,img').removeClass('fade');
   });

   //when a menu hyperlink is clicked, close the menu to ensure <BACK> returns to a page with a closed menu
   $mainmenu.find("a").click(
   function(e)
   {
      //remove the 'fade' & 'selected' classes from list item & content
      $mainmenu.find('*').removeClass('fade selected');

      //hide the submenus
      $mainmenu.find("ul").css({display:'none', visibility:'visible'});
   });
},


init:function( setting )
{
   //override default menu colors (default/hover) with custom set?
   if( typeof setting.customtheme=="object" && setting.customtheme.length == 2 )
   {
      var mainmenuid='#'+setting.mainmenuid;
      var mainselector=(setting.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid;
      document.write('<style type="text/css">\n'
         +mainselector+' ul li a {background:'+setting.customtheme[0]+';}\n'
         +mainmenuid+' ul li a:hover {background:'+setting.customtheme[1]+';}\n'
      +'</style>');
   }

   this.shadow.enable = (document.all && !window.XMLHttpRequest)? false : this.shadow.enable; //in IE6, always disable shadow

   //ajax menu?
   jQuery(document).ready( function($)
   {
      //is this page embedded in a frame?
      if (top.location != location)
      {
         //yes, so reload out of a frame
         top.location.href = document.location.href;
         return;
      }

      //if external ajax menu
      if( typeof setting.contentsource == "object" )
      {
         ddsmoothmenu.getajaxmenu( $, setting );
      }
      //else if markup menu
      else
      {
         ddsmoothmenu.buildmenu( $, setting );
      }
   });
}

} //end ddsmoothmenu variable

ddsmoothmenu.arrowimages.down[1] = '/images/down.gif';
ddsmoothmenu.arrowimages.right[1] = '/images/right.gif';
ddsmoothmenu.shadow.enable = false;

//load and show the menu when the DOM is ready providing the container is visible
$( function()
{
   //preload the menu images
   $( 'body' ).append( '<div style="display:none;">\
   <img src="' + ddsmoothmenu.arrowimages.down[1] + '">\
   <img src="' + ddsmoothmenu.arrowimages.right[1] + '">\
   </div>' ); //"

   //load the menu
   vLoadMenu();

//display made in Aus for selected countries, ref http://code.google.com/apis/ajax/documentation/ & http://www.iso.org/iso/iso-3166-1_decoding_table
//if( typeof( google ) != "undefined" && google.loader.ClientLocation )
//switch( google.loader.ClientLocation.address.country_code ) case "AU": case "CA": case "NZ":

   $('#footer').append('<div style="position:absolute; right:10px; top:3px;">\
   <span style="display:inline-block; color:#ccc; font-size:11px; text-align:right; vertical-align:top;">Designed and Made<br>in Australia</span>\
   <img src="/images/aus.gif" width="47" height="40" alt="Made in Australia">\
   </div>'); //"

   //scan every search box
   $('input[name="q"]').each( function()
   {
      //does this one have any content?
      if( $(this).val().length )
         //yes, so remove the image
         $(this).removeClass( 'searchbgimg' );
   });
});

//called on keyup within a search box, will remove the background image when the user enters content
function vSrchKeyUp( This )
{
   switch( $(This).val().length )
   {
   case 0:
      $(This).addClass( 'searchbgimg' );
      break;

   case 1:
      $(This).removeClass( 'searchbgimg' );
      break;
   }
}

//fetch the menu and put it in the menu placeholder
function vLoadMenu()
{
   //have we not already called init?
   if( typeof vLoadMenu.initCalled == 'undefined' )
   {
      //flag it's now been called
      vLoadMenu.initCalled = true;

      ddsmoothmenu.init(
      {
         mainmenuid: "smoothmenu",
         //customtheme: ["#1c5a80", "#18374a"], //override default menu CSS background values? Uncomment: ["normal_background", "hover_background"]
         contentsource: ["smoothmenu", "/menu.htm"] //"markup" or ["container_id", "path_to_menu_file"]
      });
   }
}


/*------------------------------------------------------------------------------
DESCRIPTION:
 This function is called when the menu has been fetched.  It finds the current
 page then displays the breadcrumbs within the element that has an id of
 "breadcrumbs".
PARAMETERS:
  -> site menu unordered list
RETURNS:
 <-  nil
------------------------------------------------------------------------------*/
function breadcrumbs( content )
{
   //zero the crumbs
   var crumbs = '';

   //unescape the current path (convert %20 into <space> etc)
   var path = unescape( location.pathname );

   //find the page in the menu (href's that contain the path), keep only the first one, get each <li> parent, then get the first child of the li and process it
   $( content ).find( 'a[href*="' + path + '"]' ).first().parents( 'li' ).children( ':first-child' ).each(
   function( index )
   {
      //the first item passed to this loop is the last element (current page) in the path with each loop moving higher up the path
      //get the anchor href if there is one (this element is either a 'span' or 'a')
      var href = $(this).attr( 'href' );

      //get the text
      var text = $(this).text();

      //is this an anchor?
      if( href )
         //yes, then prepend a crumb link
         crumbs = '<a href="' + href + '">' + text + '</a>' + crumbs;
      else
         //no, so just prepend crumb text
         crumbs = '<span>' + text + '</span>' + crumbs;

      //prepend a ">>" separator
      crumbs = '&raquo;' + crumbs;
   });

   //prepend the homepage link
   crumbs = '<a href="/">Home</a>' + crumbs;

   //show the breadcrumbs
   $( '#breadcrumbs' ).html( crumbs );
}


