// JavaScript Document for Mike Behnke, Homework 7, INP271
var jslib = {

	createCookie : function (name,value,expiration,path,domain,secure) {
  	var data = name + "=" + escape(value);
  	if (expiration) { data += "; expires=" + expiration.toGMTString(); }
  	if (path) { data += "; path=" + path; }
  	if (domain) { data += "; domain=" + domain; }
  	if (secure) { data += "; secure"; }
  	document.cookie = data;
	},
	
	findCookie : function(name) {
    var query = name + "=";
    var querylength = query.length;
    var cookielength = document.cookie.length;
    var i=0;
    while (i < cookielength) {
      var startValue = i + querylength;
      if (document.cookie.substring(i,startValue) == query) {
         return this.findValue(startValue);
      }
      i = document.cookie.indexOf(" ", i) + 1;
      if (i == 0) {break;}
    }
    return null;
  },

  findValue : function(startValue) {
    var endValue = document.cookie.indexOf(";", startValue);
    if (endValue == -1) {
       endValue = document.cookie.length;
    }
    return unescape(document.cookie.substring(startValue,endValue));
  },
  
	// improve performance by reducing object lookups 
	getObj : function(idvalue) {
		return document.getElementById(idvalue);
	},
		
	getElementsByClass : function (searchClass,node,tag) {
    // this array will hold the nodes that have the desired class
    var classElements = [];
    // if we did not pass the node parameter, assume document
    if (node == null) {node = document;}
    // if we did not pass the tag parameter, grab every node
    if (tag == null) {tag = '*';}
    // gather all the element nodes to look through; by default is everything in document
    var els = node.getElementsByTagName(tag);
    // to improve loop performance, determine the length ahead of time
    var elsLen = els.length;
    // establish the pattern to search for within className
    var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)");
    // look through all the class properties to see if there is a match
    // the j variable is the counter variable that increments each time a
    // match is found and becomes the next item in classElements
    for (var i = 0, j = 0; i < elsLen; i++) {
        if (pattern.test(els[i].className)) {
           classElements[j] = els[i];
           j++;
        }
    }
    // send back the array of elements to whatever variable called this function
    return classElements;
	},	
	
	// associate nodes with events and functions
  addEvent : function(obj, type, func) {
       if (obj.addEventListener) {obj.addEventListener(type, func, false);}
       else if (obj.attachEvent) {
           obj["e" + type + func] = func;
           obj[type + func] = function() {obj["e" + type + func] (window.event);}
           obj.attachEvent("on" + type, obj[type + func]);
       }
       else {obj["on" + type] = func;}
   },
	 theImgs : [], imgOver : [], imgOff : [],
   roll : function() {

    if (!document.getElementById && !document.getElementsByTagName) { return; }

		// locating document nodes
    var nav = document.getElementById('nav');
    jslib.theImgs = nav.getElementsByTagName('img');
    var theLinks = nav.getElementsByTagName('a');

    // creating arrays to hold rollover images, plus a variable for image file
    // extension and a variable to hold the total number of images to speed up the loop
    var suffix, totalImgs = jslib.theImgs.length;

    for (var i=0, j=0; i<totalImgs; i++) {
			if (jslib.theImgs[i].parentNode.nodeName != 'LI') {
	      // extract the image's extension by determining the position of the last
	      // dot in the file name and then getting the substring after that dot
	      suffix = jslib.theImgs[i].src.substring(jslib.theImgs[i].src.lastIndexOf('.'));

	      // creating a new Image() object and storing it in the imgOff array with
	      // a src that is the same as the image currently hard-coded in the page
	      jslib.imgOff[i] = new Image();
	      jslib.imgOff[i].src = jslib.theImgs[i].src;
	
	      // creating a new Image() object for the rollover image and giving it a
	      // src that is the regular image name with '-over' before the extension
	      jslib.imgOver[i] = new Image();
	      jslib.imgOver[i].src = jslib.theImgs[i].src.substring(0,jslib.theImgs[i].src.lastIndexOf('.')) + "_over" + suffix;

  	    // assigning number properties to each img and link in the document
				jslib.theImgs[i].number = i;
 	    	theLinks[j].number = i;

 	    	// using the number to synchronize the regular and rollover images as
	     	// well as the links and the rollover images
	     	jslib.addEvent(jslib.theImgs[i],'mouseover', function() {
	       	jslib.theImgs[this.number].src = jslib.imgOver[this.number].src;
	     	});
	     	jslib.addEvent(jslib.theImgs[i],'mouseout', function() {
	       	jslib.theImgs[this.number].src = jslib.imgOff[this.number].src;
	     	});
	     	jslib.addEvent(theLinks[j],'focus', function() {
	       	jslib.theImgs[this.number].src = jslib.imgOver[this.number].src;
	     	});
 	    	jslib.addEvent(theLinks[j],'blur', function() {
 	      	jslib.theImgs[this.number].src = jslib.imgOff[this.number].src;
	     	});
				j++;
    	}
		}
  },

	// Rollover menu's script
	openMenus : [],   // array for menu levels currently displayed
  pressedNav : [],  // array tracking which item is pressed at each level
  timer : null,     // timer for when to close menus

  // array of id values for submenus, which correspond to the link
  // sequence in the whole navigation sequence
  subMenus : ['','','sub_select','','sub_account'],
	
  nav_init : function() {
    if (!document.getElementById || !document.getElementsByTagName) { return; }
    var navHolder = document.getElementById('nav');
    var navItems = navHolder.getElementsByTagName('a');
		var subnav = document.getElementById('sub_nav');
		var lists = subnav.getElementsByTagName('ul');

    // disabling the visibility of the sub menus
		
    for (var i=0, allLists = lists.length; i<allLists; i++) {
        lists[i].style.visibility = 'hidden';

				// enable hover state for top level nav when in subnav menu
				for (var j=0, snlen = jslib.subMenus.length; j < snlen; j++) {
				  if (jslib.subMenus[j] == lists[i].id) {lists[i].number = j+1;}
				}

				// add mouseover/mouseout events to the UL, works in FF/IE/Opera
				if (lists[i].number) {
				  jslib.addEvent(lists[i],'mouseover', function() {
						jslib.theImgs[this.number].src = jslib.imgOver[this.number].src;
	     		});
        	jslib.addEvent(lists[i],'mouseout', function() {
	       		jslib.theImgs[this.number].src = jslib.imgOff[this.number].src;
	     		});

					// make tabbing work in IE/Opera by focusing/bluring on the links
					// instead of the UL, which just worked in FireFox
					var snlinks = lists[i].getElementsByTagName('a');
					for (var k=0, snllen=snlinks.length; k<snllen; k++) {
					  snlinks[k].number = lists[i].number;
						jslib.addEvent(snlinks[k],'focus',function() {
	       			jslib.theImgs[this.number].src = jslib.imgOver[this.number].src;
						});
						jslib.addEvent(snlinks[k],'blur', function() {
	       			jslib.theImgs[this.number].src = jslib.imgOff[this.number].src;
	     			});
					}
			 }
			 
    }

    // adding a number property to each nav link, to synchronize
    // them with the subMenus[] array; adding event handlers
    for (var i=0, allNavItems = navItems.length; i<allNavItems; i++) {
        navItems[i].number2 = i;
        jslib.addEvent(navItems[i],'mouseover', jslib.display);
        jslib.addEvent(navItems[i],'focus', jslib.display);
        jslib.addEvent(navItems[i],'mouseout', jslib.setTimer);
        jslib.addEvent(navItems[i],'blur', jslib.setTimer);
    }

  },

  display : function() {

    // a new link has been moused over or given focus, so erase the countdown
    if (jslib.timer) { clearTimeout(jslib.timer); }

    var menuLvl, menuToShow, num = this.number2;

    // Determine menu level
    if (num <= 4 || num == 13 || num == 14) { menuLvl = 1; }
    if (((num > 4) && (num <= 12)) || ((num > 14) && (num <=16))) { menuLvl = 2; }
    
    // stop if the user is mousing over or tabbing to the same item again
    if (jslib.openMenus[menuLvl] && jslib.openMenus[menuLvl] == jslib.subMenus[num]) { return; }

     // shut off any other submenus
     if (jslib.openMenus[menuLvl]) { jslib.closeAllMenus(menuLvl); }

     // if there is no item in subMenus[] at that position, then do nothing
     // if there is an item in subMenus[] at that position, change the indicated
     // sub menu's visibility
     if (!jslib.subMenus[num]) {}
     else {
        menuToShow = document.getElementById(jslib.subMenus[num]).style;
        menuToShow.visibility = 'visible';
     }

     // assign that open menu to the openMenus[] array, with the position
     // in the array the same as the menu level (1 or 2)
     jslib.openMenus[menuLvl] = jslib.subMenus[num];

     // alter visual display if there is no class assigned to that item
     // if there is already a class assigned, then we assume it is "over" and do nothing
     if (this.className) { return; }
     this.className = 'over';

     // replace whatever item is in the pressedNav[] array with the one just activated
     // remove the class from that previous item
     if (jslib.pressedNav[menuLvl]) { jslib.pressedNav[menuLvl].className = ''; }
     jslib.pressedNav[menuLvl] = this;

   },

   // setting a 6 second timer
   setTimer : function() {
     if (jslib.timer) { clearTimeout(jslib.timer); }
     jslib.timer = setTimeout('jslib.closeAllMenus(1)',6000);
   },

   // shutting down all menus, wiping all "over" classes and emptying out all
   // the items in openMenus[] and pressedNav[]
   closeAllMenus : function(lvl) {

     for (var i=jslib.openMenus.length - 1; i>=lvl; i--) {
        if (jslib.openMenus[i]) {
            var menuToHide = document.getElementById(jslib.openMenus[i]).style;
            menuToHide.visibility = 'hidden';
        }
        jslib.openMenus[i] = null;
        if (jslib.pressedNav[i]) {
            jslib.pressedNav[i].className = '';
            jslib.pressedNav[i] = null;
        }
     }
  },
  
  subOverState : function () {

	}

}

jslib.addEvent(window,'load',jslib.roll);
jslib.addEvent(window,'load',jslib.nav_init);