// This script is included on EVERY page (so make sure you are careful
// about referencing things that possibly don't exist on that page!)


// The "khclient.js" script MUST be loaded BEFORE this script, so that
// the KH.include() method is defined with "includeDir" set to the
// lib directory in the war file.
KH.include( "kh/ToolTip.js" );
KH.include( "kh/MultiMenu.js" );


if ( !VWEB ) var VWEB = {};

    //  adding anonymous function that will run on every page
    //  to the KH "initMethods" list
    KH.addInitMethod( function() {

        //  initialize the drop-down menus by starting with all the expected
        //  activators on the nav-bar, and depending on id-naming conventions
        //  to find our way through the category menus.
	//  (top-level menus delayed by 300ms)
        var initmenu = KH.MultiMenu.initMenu;
        var menu, activator;
        activator = $("schedule");
        menu = $("schedule-menu");
        if ( activator && menu )  initmenu( activator, menu, 300 );
        activator = $("quicklinks");
        menu = $("quicklinks-menu");
        if ( activator && menu )  initmenu( activator, menu, 300 );
        activator = $("courses");
        menu=$("category-menu");
        if ( activator && menu ) {
            initmenu( activator, menu, 300 );
            var items = menu.select( "a" );
	    for ( var i=0; i<items.length; i++ ) {
	        var id = items[i].id;
	        if ( ! id  ||  id.substring(0,5) != "item-" )  continue;
	        var sub = $( "subcat-"+id.substring(5) );
	        //  second-level menus delayed by 100ms
	        if ( sub )  initmenu( id, sub, 100 );
	    }
        }

        //  initialize all "gridlist" and "rhslist" boxes
        var list = $$(".gridlist, .rhslist");
        for ( var i=0; i<list.length; i++ ) {
            var rows = list[i].select("tr");
            for ( var j=0; j<rows.length; j++ ) {
	        if ( j==0 )  continue;  // don't do the column header row
	        rows[j].onmouseover = function() {
					this.addClassName("hovering");
				      }
	        rows[j].onmouseout =  function() {
					this.removeClassName("hovering");
				      }
	        rows[j].onclick =     VWEB.clickListRow;
	        // hijack any original links, requiring there to be at least
	        // one, so we can get the href and title from it.
	        var links = rows[j].select("a");
	        if ( !links  ||  links.length < 1 )  throw "There must be "
	    			+ "at least one <a> in each GridBox row";
	        rows[j].savedHref = links[0].href;
	        if ( !rows[j].title )  rows[j].title = links[0].title;
	        for ( var k=0; k<links.length; k++ ) {
		    links[k].onclick = VWEB.hijackGridClick;
	        } // end of loop over all links in the row
	    } // end of loop over all rows in list
        } // end of loop over all lists on the page

        //  initialize all hijacked elements anywhere in the page
        VWEB.initHijacks( document.body );
    } );


    //  initialize any objects that have classname "hijack"
    VWEB.initHijacks = function( node, flag ) {

        //  for all elements contained by the specified node that have
	//  class "hijack" as well as another class that tells us how
	//  to use the click, hijack clicks on that element.
	node = Element.extend( node );
        var list = node.select(".hijack");
        var el, tok;
        for ( var i=0; i<list.length; i++ ) {
	    el = list[i];
	    //  set the flag on this element if one was provided
	    if ( flag )  el.hijackFlag = flag;
	    //  if it contains an "end-N" class, then hijack it so that
	    //  a click will go back by "N" pages
	    if ( (tok=el.className.match(" end-[1-9]+")) ) {
	        var n = tok[0].substring(5)-0;
	        el.hijackBack = n;
	        el.onclick = VWEB.hijackClickBack;
	    } else if ( el.className.indexOf(" lightbox") > 1 ) {
		//  this is just a placeholder for lightbox hijacking:
		//  We'll save the href if there is one, otherwise,
		//  it's probably a submit button, so we'll save "#"
		//  but we're not really doing the hijack anyway, so
		//  it's going to do whatever it does regardless!!!!
		if ( el.href )  el.hijackHref = el.href;
		else            el.hijackHref = "#";
	    }
        } // end of loop over all objects with class "hijack"
    }


    VWEB.hijackClickBack = function( evt ) {
	if ( !evt ) evt = window.event;
	this.blur();
	if ( evt.preventDefault ) evt.preventDefault();
	else evt.returnValue = false;
	if ( !this.hijackBack )  return;
	history.go( -this.hijackBack );
    }


    //  hijack a click on a link that we're disabling here, so
    //  it doesn't do a page refresh and also to blur the clicked link
    //  so we don't end up with that stupid-looking focus box on FF
    VWEB.hijackGridClick = function( evt ) {
	if ( !evt ) evt = window.event;
        this.blur();
	if ( evt.preventDefault ) evt.preventDefault();
	else evt.returnValue = false;
	//  if the link has class-name "gridkeeplink", then we actually
	//  WILL execute the link and block event bubbling so that
	//  our underlying "clickListRow()" won't get the event
	if ( this.hasClassName("gridkeeplink") )  {
	    evt.cancelBubble = true;
	    document.location = this.href;
	}
    }

    //  handle click on a row in any rhslist or gridlist
    VWEB.clickListRow = function() {
        this.removeClassName( "hovering" );
	if ( this.savedHref )  document.location = this.savedHref;
    }

    //  show a tool-tip for a category/sub-category menu item
    //  (This is not being used now, because the ToolTip is not
    //  being initialized with it, since the category descriptions
    //  are built into the page for now.)
    VWEB.categoryTooltip = function( eventnum ) {
        if ( eventnum != 2 )  return;
	//  these menus occur on "/catalog/" and "/category/"
	//  pages, so find that in the href
	var pos = this.href.indexOf("/catalog/");
	if ( pos < 0 )  pos = this.href.indexOf("/category/");
	//  hopeless if we can't find the category code in the href!
	if ( pos < 0 )  return;
	//  strip off through the first slash of the string we just matched
	var code = this.href.substring(pos+1);
	//  then strip off through it's trailing slash
	pos = code.indexOf( "/" );
	code = code.substring( pos+1 );
	//  then strip off trailing "/index.html" or just ".html"
	pos = code.indexOf( "/index.html" );
	if ( pos < 0 )  pos = code.indexOf( ".html" );
	if ( pos > 0 )   code = code.substring(0,pos);
	//  now we have the code!
        var content = "This box should contain the description for course "
            + "category '" + code + "'";
        return ( content );
    }

    VWEB.extractCode = function( s ) {
	//  if it contains (ends with) index.html, strip that off
        var pos = s.indexOf( "/index.html" );
	if ( pos >=0 )  s = s.substring( 0, pos );
	//  strip off everything through the last slash
        pos = s.lastIndexOf( "/" );
	if ( pos >=0 )  s = s.substring( pos+1 );
	//  if it still contains a ".", remove it and everything after it
	pos = s.indexOf( "." );
	if ( pos >=0 )  s = s.substring( 0, pos );
	//  hopefully, that'll be the code
	return ( s );
    }

    //  this method expects the "acctmgr" and "territory" objects
    //  created by the "AcctMgrInformation" and "TerritoryInformation"
    //  classes to have been defined.  If they're not, it may produce
    //  some kind of error message as the return value.
    VWEB.nAcctMgr = 0;
    VWEB.getAcctMgrContent = function( terrcode, format ) {
	var terrname, mgrs=[];
	var isTerrDefined = ( typeof territory != "undefined" );
	if ( terrcode  &&  terrcode != ""  &&  isTerrDefined ) {
	    var terrobj = territory[terrcode];
	    terrname = terrobj[0];
	    if ( !format ) {
	        var url = scheduleUrl+"/location/"+terrcode+".html";
	        terrname = "<a href=\""+url+"\">"+terrname+"</a>";
	    }
	    if ( terrobj[1] )  mgrs = terrobj[1].split(",");
	}
	//  if not done yet, count the number of defined account managers
	var isAcctMgrDefined = ( typeof acctmgr != "undefined" );
	if ( isAcctMgrDefined && !VWEB.nAcctMgr ) {
	    for ( var k in acctmgr )  VWEB.nAcctMgr++;
	}
	//  define a "break" string only for tooltip format=0 (or undefined)
	var ttbreak = ( !format ) ? "<br/>" : " ";
	var content;
	if ( terrname ) {
	     //  the message we use depends on whether just one, just a couple,
	     //  or most of the account managers are assigned to this territory
	     if ( mgrs.length < 1  ||  mgrs.length>(VWEB.nAcctMgr-1) ) {
	         content = "Contact Verhoef's Sales Office at"+ttbreak
		     + "800.533.3893, or the Account Manager"+ttbreak
		     + "listed for your own state to schedule"+ttbreak;
		 if ( terrcode == "WBILT" ) {
		     content += "<b>"+terrname + "</b> classes.\n";
		 } else {
		     content += "classes in <b>"+terrname+"</b>.\n";
		 }
	     } else {
		 var plural, verb;
	         if ( mgrs.length == 1 ) {
		     plural="";
		     verb="is";
		 } else {
		     plural="s";
		     verb="are";
		 }
		 if ( !format ) {
		     content = "Your Verhoef Account Manager"+plural
		     	+ " for<br/><b>"+terrname+"</b> "+verb+":\n";
		 } else {
		     content = "For information or to sign up for a class,"
		        + " contact your Account Manager:";
		 }
		 var mgr;
		 for ( var i=0; i<mgrs.length; i++ ) {
		      mgr = acctmgr[mgrs[i]];
		      if ( !mgr  ||  mgr.length<3 )  continue; 
		      if ( !format ) {
		          content +="<div style='padding:6px 0px 0px 20px;'>"
				+ "<nobr><b>"+mgr[0]+"</b></nobr><br/>"
				+ "phone: "+mgr[1]+"<br/>"
				+ "email: <a href='mailto:"+mgr[2]+"'>"
				+     mgr[2]+"</a></div>\n";
		      } else {
		          content += "<br/><b>"+mgr[0]+"</b> "
				+ "at "+mgr[1]+" or "
				+ "<a href='mailto:"+mgr[2]+"'>"+mgr[2]+"</a>";
		      }
		 }  // end loop over all acct mgrs for this territory
	     }  // end of case for a small number of acct-mgrs
	} else {
	    content = "Unable to get information for '"+terrcode+"'";
	}  // end of all cases
        //  we got the content, so return it
        return ( content );
    }

    //  Following enables Google Analytics on every page
    //  that includes this script, which is every page on the
    //  public (but not on the admin) site.
    //
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-17712469-3']);
    _gaq.push(['_trackPageview']);

    (function() {
      var ga = document.createElement('script');
      ga.type = 'text/javascript';
      ga.async = true;
      ga.src = ('https:'==document.location.protocol?'https://ssl':'http://www')
      			+ '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(ga, s);
    })();

