//==============================
// JAVASCRIPT MENU GENERATOR  ['Expando' Type]
// -----------------------------------------------------------
// Created by Spencer Rose, 
// Humanities Computing and Media Centre, 
// University of Victoria, 2002.
//==============================


// ---------------------------------------------
// Set Menu Object Properties:
//     CAPTION: what appears in the menu cell
//     URL: what document is loaded 
//     LEVEL: what directory level [root='0']

var M=new MainMenu();  // Menu Object

MainMenu.prototype.CreateMenu=MMCreateMenu;
MainMenu.prototype.CreatePlainMenu=MMCreatePlainMenu;

// ---------------------------------------------
// Establish Menu Properites:
function MMAddItem(Caption, URL, Level){
    var Item=new MenuItem(Caption, URL, Level);
    this.items[this.items.length]=Item;
}

MainMenu.prototype.AddItem=MMAddItem;

// ----
function MenuItem(Caption, URL, Level){
    this.caption=Caption;
    this.level=parseInt(Level);
    this.url=URL;
}


//==============================


// ---------------------------------------------
// Build Menu: NO CONDITIONS SET
function WriteMenu(){
	if (document.getElementById){document.write(M.CreateMenu());}
	//else {document.write(M.CreatePlainMenu());}
}

// ---------------------------------------------
// Establish menu object:
function MainMenu(){
    this.items=new Array();              // menu items array
	this.dirs=new Array();                // directory items array
    this.submenuOpen=new Array(); // current open submenu(s) array
    this.clickToggle=true;                 // body click toggle switch
}



// ---------------------------------------------
// Determine current location path:

function getPath(flag){

    var currLoc=window.location.href;         // current relative URL
    var rootIndex=currLoc.indexOf(M.dirRoot)+M.dirRoot.length+1;    // last character index
	var dirName='';                                   // current directory name
	var dirList=new Array();                       // list of directories
	var i=rootIndex; j=0;                                              // directory list index
	var upDir='';                                       // string for moving up direc. tree
	var dirPath='';                                     // current directory path

	// Create directory list:
	while (i<currLoc.length) {
		dirName='';
		while ((currLoc.charAt(i)!='\\')&&(currLoc.charAt(i)!='/')&&(i<currLoc.length)){
        dirName+=currLoc.charAt(i); 
		 i++;
		}
		i++;
		dirList[j]=dirName;
		j++;
	}

	// Determine direc. position rel. to root directory:
	if (flag==false) {	
		for (i=0;i<dirList.length-1;i++){ upDir+='../';}
		return upDir;
	}

	// Return directory path:
	if (flag==true) {	
		return dirList;
	}
}


//==============================


// ---------------------------------------------
// Write menu to browser:  


function MMCreateMenu(){
    var Output='';                                      // Menu Text String
	var i=0;                                            // Menu Item Counter

//First create the overall container:

    Output='<div id="menu" class="menu">';

    while(i<this.items.length){ 

		// markup for mainmenu item
		Output=formatItem(Output, i); 

		//increment item count:
        i++;
	}

	Output+='</div>';
	
	// ---------------------------------------------------
	// [DEBUGGER] -- alert display of menu HTML:
		// Display via alert message:
			// displayHTML(Output); 
		// Display via text output:
			// return '<plaintext>'+Output;
	// ---------------------------------------------------

	return Output;
}



// ---------------------------------------------
// Generate MainItem HTML script:

function formatItem(Output, i) {

	// Create a new menu item:
	Output += '<div onmouseover="OverItem(this,\'tab_' + i +  '\')"  onmouseout="OutItem(this, \'tab_' + i +  '\')"  id="tab_' + i +  '\"'; 

	// If menu item (or contained subitem) URL is the URL of the current page, highlight item:
	if (checkSelect(i)){Output += ' class="menu' + M.items[i].level + '_select" ';}
	else{Output += ' class="menu' + M.items[i].level + '_out" ';}

	//If menu item has a URL, make it link:
	if (M.items[i].url.length>0){
		// External links:
		if (M.items[i].url.indexOf('http')!=-1){Output += 'onclick="document.location=\'' +  M.items[i].url + '\'">';}
		// Internal links:
		if ((M.items[i].url!=getPath(true))&&(M.items[i].url.indexOf('http')==-1)&&(!checkSelect(i))) {Output += 'onclick="document.location=\'' + getPath(false)  + M.items[i].url + '\'">';}
		// Hightlighted internal links:
		if (checkSelect(i)) {Output += 'onclick="document.location=\'' + getPath(false)  + M.items[i].url + '\'">';}
	}
	// Directory tabs:
	else{Output += ' onclick="menuClick(\'dir_' + i +  '\')">';}

	//Add the menu item caption:
	Output += M.items[i].caption + '</div>';

	// Close new menu item:
	if (eval(i+1)<M.items.length) { 

		// Add subItem container if next item is a higher-level item:
		if (parseInt(M.items[eval(i+1)].level)>parseInt(M.items[i].level)){
			Output += '<div class="menu' + M.items[i+1].level + '_contain"  id="dir_' + i + '"';
			// If DHTML capable:  close pop-up
			if ((!checkSelect(i))&&(document.getElementById)) {Output+=' style="display: none;">';}
			// If DHTML incapable:  default pop-up
			else {Output+=' style="display: block;">';}
		}

		// Close subitem container(s) if next item is a lower-level item:
		if (parseInt(M.items[eval(i+1)].level)<parseInt(M.items[i].level)) {
			for (j=1;j<=eval(parseInt(M.items[eval(i)].level)-parseInt(M.items[i+1].level));j++) {Output += '</div>';}
		}
	}
	return Output;
}


// ---------------------------------------------
// [DEBUGGER]:  display menu markup

function displayHTML(Output) {

	var formattedHTML=Output.replace(/\x3Cdiv/g, '\n\t<div');
	formattedHTML=formattedHTML.replace(/\x3E\x3C\/div/g, '>\n\t</div');
	alert(formattedHTML);
}


//==============================


// ---------------------------------------------
// Extract/return menu index value from item id:

function getIndex (Id) {

	if ((Id.indexOf('tab_')!=-1)||(Id.indexOf('dir_')!=-1)){var end=Id.length;}	
	var start=Id.indexOf('_')+1;
	var selection=(Id.substring(start,end));
	return selection;
}


// ---------------------------------------------
// Check for selected sub/main menu items:

function checkSelect(i) {

    var currPath=getPath(true);       // current directory array 
	var testPath=M.items[i].url;       // current test URL
	var dirList=new Array();           // test directory array
	var j=0;                                  // character index
	var dirCheck=false;                 // directory flag
	var offsetLevel=0;                   // offset for creating virtual directory list
	var result=false;                      // result of menu check
	var k=0;                                 // test array index

	// Create test directory list:

	// If testing a directory (ie. no URL attached), create virtual URL:
	while (testPath.length==0) { 
			i++; 
			testPath=M.items[i].url;                // URL of next item in menu tree
			offsetLevel++;                            // level adjustment for virtual URL
			dirCheck=true;                           // sets first array item to empty
	}

	// Split path string and set test directory array:
	while (j<testPath.length) { 
		var dirName='';                                // test directory name
		while ((testPath.charAt(j)!='\\')&&(testPath.charAt(j)!='/')&&(j<testPath.length)){
			dirName+=testPath.charAt(j); 
			j++;
		}
		j++;
		dirList[k]=dirName;
		k++;
	}

	// Set empty items in virtual directory list to null:
	if (dirCheck) {
		for (k=dirList.length-1;k>dirList.length-offsetLevel-1;k-- ) {dirList[k]=null;}
	}

	// [DEBUGGER] display check selection:
	//alert(testPath + '  -->  '   + dirList + ' <-->  ' + currPath);

	// Check for external links:
	if ((dirList[0]=='http')||(dirList[0]=='www')){return false;}

	// Compare directories of test and current pathnames:
	for (n=0;n<dirList.length;n++) {
		if ((dirList[n]!=null)&&(dirList[n]!=currPath[n])) {return false;}
		if (dirList[n]==currPath[n]){result=true;}
		if (dirList[n]==null) {return result;}
	}
	return result;
}


// ---------------------------------------------
// MouseOver event handler:

function OverItem(menuItem, Id){ 

// [DEBUGGER] --signals when activated:
// alert("onmouseover for: " + Id)

    var selection=getIndex(Id); 

    if (checkSelect(selection)){menuItem.className='menu' + M.items[selection].level + '_select';}
    else {menuItem.className='menu' + M.items[selection].level + '_over';}

}


// ---------------------------------------------
// MouseOut event handler:

function OutItem(menuItem, Id){ 

// [DEBUGGER] --signals when activated:
// alert("onmouseout for: " + Id)

    var selection=getIndex(Id); 

    if (checkSelect(selection)){menuItem.className='menu' + M.items[selection].level + '_select';}
    else {menuItem.className='menu' + M.items[selection].level + '_out';}
}


// ---------------------------------------------
// OnClick event handler:

function menuClick(Id){ 

// [DEBUGGER] --signals when activated:
// alert("onclick for: " + Id)

// Contract the previous submenu:

    var selection=getIndex(Id); 

    if (Id!='all') {

		// Toggle body click switch:
		M.clickToggle=!M.clickToggle;

		// Same submenu level is expanded:
        if ((M.submenuOpen[M.items[selection].level]!=Id)&&(M.submenuOpen[M.items[selection].level]!=null)) {
			// Close opened submenu(s):
			for (j=M.items[selection].level;j<M.submenuOpen.length;j++) {
				Contract(M.submenuOpen[j]);
				M.submenuOpen[j]=null;
			}
			// Open selected submenu:
			Expand(Id);
			M.submenuOpen[M.items[selection].level]=Id;
			return
		}

		// Selected submenu is already expanded:
        if (M.submenuOpen[M.items[selection].level]==Id) {
			// Close selected submenu(s):
			for (j=M.items[selection].level;j<M.submenuOpen.length;j++) {
				Contract(M.submenuOpen[j]);
				M.submenuOpen[j]=null;
			}
			return
		}

		// Same submenu level is not expanded:
		if (M.submenuOpen[M.items[selection].level]==null) {
			// Open selected submenu:
			Expand(Id);
			M.submenuOpen[M.items[selection].level]=Id;
		   return;
		}
    }

	if (Id=='all') {

		// Close all opened submenu(s):
		if (M.clickToggle) {
			for (j=M.submenuOpen.length;j>=0;j--) {
			Contract(M.submenuOpen[j]);
			M.submenuOpen[j]=null;
			}
		}

		// Reset body click switch:
		M.clickToggle=true;
	}
}


// ---------------------------------------------
// Expand submenu:

function Expand(Id){

    var el=document.getElementById(Id);
    if (el != null){el.style.display='block';}
}

// ---------------------------------------------
// Collapse submenu:

function Contract(Id){

    var el=document.getElementById(Id);
    if (el != null){el.style.display='none';}
}


//==============================


// ---------------------------------------------
// Display path of directories for current filename:

function WritePath(file) {

	var currPath=getPath(true);   // current pathname
	var viewPath ='';                   // displayed pathname

	// Add selected directories:
	for (i=0;i<M.items.length-1;i++) {
		if (checkSelect(i)) {
			if (M.items[i].url.indexOf(currPath[currPath.length-1])==-1) {viewPath+= M.items[i].caption + '&nbsp;&#062;&#062;&nbsp;'};
		}
	}

	// Add file's title to directory list:
	viewPath+= document.title;

	// Markup directory pathname:
	viewPath='<div class="dirPath">'  + viewPath + '</div>'; //alert(viewPath);

	// Display directory pathname:
	document.write(viewPath);
}




// ---------------------------------------------
// BROWSER FAILURE: Write disabled menu to browser:
// CSS classes:
//    Main menu items with submenu: 'mainhead'
//    Main menu item anchors: 'mainlink'
//    Sub menu items with submenu: 'subhead'
//    Sub menu item anchors: 'sublink'

function MMCreatePlainMenu(){

    var Output = '';

// Create a buffer for the closing code:
    var i=0;
    while(i<this.items.length){

// Then, for each menu item, check if it's a main item or not:
        if (this.items[i].level==0){

// MAIN ITEM:

// If it has a URL, make it link:
			if (this.items[i].url.length > 0){
				Output += '<a class="mainlink" href="';
				if (this.items[i].url.indexOf('http')!=-1){Output += this.items[i].url + '">';}
				else {Output += getPath(false)  + this.items[i].url + '">';}
				Output += this.items[i].caption + '</a><br />';
			}
		
			else{Output += '<span class="mainhead">' + this.items[i].caption + '</span><br />';}
     
       }

       else{
// SUBITEM:

// If it has a URL, make it link:
		if (this.items[i].url.length > 0){
            Output += '<a class="sublink" href="';
			if (this.items[i].url.indexOf('http://')!=-1){Output += this.items[i].url + '">';}
            else {Output += getPath(false) + this.items[i].url + '">';}
			Output += this.items[i].caption + '</a><br />';
		}

        else{Output += '<span class="subhead">' + this.items[i].caption + '</span><br />';}

        }
        i++;
    }


// Write the Menu to the Browser:

// [DEBUGGER] -- display menu HTML:
 alert(Output);

    return Output;
}

//==============================

// --------------------------------------------- 
// >>> Enter Menu Changes Here:

// [1] MENU ITEMS:
// SYNTAX: M.AddItem('### CAPTION ###', '### RELATIVE URL ###',### MENU/DIRECTORY LEVEL/'external' ###);

// Add Root Directory: [NOTE: directory which contains 'index.htm(l)]'
M.dirRoot='ling';

// Main Page Item: [NOTE: must have url: "index.htm(l)"]
M.AddItem('Home', 'index.htm', 0);

// Main Item:
M.AddItem('Faculty', 'faculty/index.htm', 0);

// Main Item:
M.AddItem('Undergraduate', '', 0);
	// Sub-Items:
	M.AddItem('FAQs', 'undergraduate/index.htm', 1);
	M.AddItem('Programs', 'undergraduate/undergrad_programs.htm', 1);
	M.AddItem('What is Linguistics?', 'undergraduate/linguisticsis.htm', 1);
	// Added Jan 26 2005 Ricardo Serrano
	M.AddItem('Course Union', 'http://web.uvic.ca/~undrling', 1);

// Main Item:
M.AddItem('Graduate', '', 0);
	// Sub-Items:
	M.AddItem('General Info', 'graduate/index.htm', 1);
	M.AddItem('Programs', 'graduate/grad_programs.htm', 1);
	M.AddItem('Funding', 'graduate/funding.htm', 1);
	M.AddItem('Grad Students', 'graduate/grad_students.htm', 1);

// Main Item:
M.AddItem('Research', '', 0);
	// Sub-Items:
	M.AddItem('Research Areas', 'research/index.htm', 1);
	M.AddItem('Facilities', 'research/facilities.htm', 1);
	M.AddItem('Current projects', 'research/projects.htm', 1);

// Main Item:
M.AddItem('Courses', '', 0);
	// Sub-Items:
	M.AddItem('Course Listing', 'courses/index.htm', 1);
	M.AddItem('Timetable', 'courses/timetable_spring.htm', 1);

// Main Item:
M.AddItem('Resources', '', 0);
	// Sub-Items:
	M.AddItem('Course Materials', 'resources/index.htm', 1);
	M.AddItem('IPA Materials', '', 1);
		// Sub-Sub-Items:
		M.AddItem('Charts', 'resources/ipa/charts.htm', 2);
		// Cooment on April 2005 John suggest not to use it. Now the whole site is available to uvic user thtough netlinkid 
		// authentication
		//M.AddItem('Journal', 'resources/ipa/jipa.htm', 2);
		M.AddItem('Handbook', 'resources/ipa/handbook.htm', 2);
		M.AddItem('Miscellania', 'resources/ipa/miscellania.htm', 2);
	M.AddItem('Links', 'resources/links.htm', 1);
		
// Main Item: Changed in Sep 2004 Ricardo  Serrano
//M.AddItem('Events', 'events/index.htm', 0);
M.AddItem('Information', '', 0);
	// Sub-Items:
	M.AddItem('News', 'information/news.htm', 1);
	//M.AddItem('Events', 'events/index.htm', 1);
	//M.AddItem('Jobs', 'information/index.htm', 1);
	M.AddItem('Events', 'information/events.htm', 1);
	//M.AddItem('Jobs', 'information/jobs.htm', 1);

// Main Item: Changed in April 2005 Ricardo  Serrano
M.AddItem('Jobs', 'jobs/index.htm',0);

// Main Item:
M.AddItem('Contact us', 'contact.htm',0);


// ---------------------------------------------  


