// LTI.js 
/*
	Primary Javascript functions for LTI website.
	Includes functions for reading/setting cookies and loading menus
*/

var dsMenu = null;		// Represents the Menu xml file
var rows = null;		// Retrieved rows from dsMenu

//Region language cookies.
var reg;
var lang;
var pgReg;
var pgLang;

function loadPage(r, l, id) {
	//Called from <body> onload. Checks cookies and loads menus.
	pgReg = r;
	pgLang = l;
	loadCookies();
	
	//Retreive data from menu.xml file. 
	dsMenu = new Spry.Data.XMLDataSet("../../xml/menu11.xml", "menus/menu[@region='" + reg 
														+ "' and @lang = '"+lang+"']/menuitem", {useCache:false});
	//Use event listener to process data once XML is loaded			
	dsMenu.addObserver(isDataLoaded);
	dsMenu.loadData();
	
}

function loadCookies() {

	var e;
	var newCookie=false;

	//Retrieve reg, lang from cookie
	reg = getCookie("lti_reg");
	lang = getCookie("lti_lang");	
	
	if(reg!=pgReg) {
		newCookie=true;
	}
	if(lang!=pgLang){
		newCookie=true;
	}
	
	if(newCookie){
		e=getExpDate(365,0,0);	
		setCookie("lti_reg", pgReg, e, "", "", "");
		setCookie("lti_lang", pgLang, e, "", "", "");
		reg=pgReg;
		lang=pgLang;
	}
}


/***************************************
		MENU HANDLING FUNCTIONS
***************************************/
function isDataLoaded(notificationType, dataSet, data) {
	//Even listener: checks if menu.xml is loaded successfully
	if(notificationType=='onPostLoad'){
		rows=dsMenu.getData();
		writeMenus();
	} else if(notificationType=='onLoadError') {
		alert('Error Loading Data');
	}
};

function writeMenus() {
	//Create actual menu code.
	
	//Variables to for top menu
	var strTopMenu = "";	//HTML code for top menu
	var strTopLine = "";
	
	//Variables for left sidebar menu
	var strLeftMenu = "";	//HTML code for left menu
	var strLeftLine = "";
	var thisMenu = "0"
	var thisChild = "0"
	var bolShowChild = false;
	//Icon for selected menu
	var strSelected = "";
	
	//Retrieve current file name
	var thisFile = getPageName();
	var	oldMenu = 0;
	
	//Left Menu
	//Search dsMenu for a filename (src attribute) matching current filename.
	//Retrieve its menu and child number.
	//If not found, system just writes the top level menus.
	var foundRow = dsMenu.findRowsWithColumnValues({"@src" : thisFile}, true);
	
	if(foundRow != null) {
		thisMenu = foundRow["@menu"];
		thisChild = foundRow["@child"];
	} 
	//else {
		//For testing, provide default.
	//	thisMenu = "2";
	//	thisChild = "1";
	//}
	
	//Initial code for menus
	strLeftMenu = "<ul>"
	
	if (thisFile=='home.html') {
		strLeftMenu += "<li><a class='selectedItem' href='home.html'>Home</a></li>";
	} else {
		strLeftMenu += "<li><a href='home.html'>Home</a></li>";
	}
	
	//Loop through each row of menu.xml
	for(var i=0; i<rows.length; i++){

		if(rows[i]["@child"]==0) {		//If first level menu (child=0)
			
			//Top menu OLD VERSION
//			strTopLine = "<li><a class='MenuBarItemSubmenu' href='" + 
//				rows[i]["@src"] + "'>" + rows[i]["menuitem"].toUpperCase() + "</a><ul>";
			
//			if(rows[i]["@menu"]!=1){
				//If not first top menu, terminate previous submenu
//				strTopLine = "</ul></li>" + strTopLine;
//			}	

			//Top menu NEW VERSION
			if(rows[i]["@hasChild"]==1) {
				//If item has a child, prepare for a drop down
				strTopLine = "<li><a class='MenuBarItemSubmenu' href='" + 
					rows[i]["@src"] + "'>" + rows[i]["menuitem"].toUpperCase() + "</a><ul>";
			} else {
				strTopLine = "<li><a href='" + 
					rows[i]["@src"] + "'>" + rows[i]["menuitem"].toUpperCase() + "</a></li>";
			}
			
			if(rows[i]["@menu"]!=1){
				if(oldMenu==1) {
					//If not first top menu, terminate previous submenu
					strTopLine = "</ul></li>" + strTopLine;
				} 
			}	
			oldMenu = rows[i]["@hasChild"];
			
			//Left Menu		
			if(rows[i]["@menu"]==thisMenu) {
				//If this menu is parent of or is the active page, add selection symbol.
				// and toggle flag to show children
				strLeftLine = "<li><a class='selectedItem' href='" + rows[i]["@src"] + 
					"'>" + rows[i]["menuitem"] + "</a><ul>";
				bolShowChild = true;
			} else {
				//If not active, just show plain enty
				strLeftLine = "<li><a  href='" + rows[i]["@src"] + "'>" + 
					rows[i]["menuitem"] + "</a></li>";
			
				//If previous menu was a child menu, add termination and toggle flag.		
				if(bolShowChild) {
					strLeftLine = "</ul></li>" + strLeftLine;
					bolShowChild = false;
				} 
			}
			
		} else {		// Show child menus
			
			//Top menu
			strTopLine = "<li><a href='" + rows[i]["@src"] + "'>" + 
				rows[i]["menuitem"] + "</a></li>";
			
			//Left Menu
			//Only show siblings or children of active page
			if(rows[i]["@menu"]==thisMenu) {
			 	if(rows[i]["@child"]==thisChild) {
					//If this is the active page
					strLeftLine = "<li><a class='selectedItem' href='" + rows[i]["@src"] + 
						"'>" + rows[i]["menuitem"] + "</a></li>";
				} else {
					strLeftLine = "<li><a href='" + rows[i]["@src"] + 
						"'>" + rows[i]["menuitem"] + "</a></li>";
				}
			} else {
				//hide submenu
				strLeftLine = "";
			}
		} 
		
		//Copy lines to menu strings and go to next row
		strTopMenu += strTopLine;
		strLeftMenu += strLeftLine;
	}
	//alert();
	//Write html codes to menu divs
	document.getElementById("MenuBar1").innerHTML=strTopMenu;
	document.getElementById("section_nav").innerHTML=strLeftMenu;
	getPageName();
	// Spry object to handle drop down menubar. Must be inserted here so it reads menu
	// after the html code has been inserted.
	var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", 
					{imgDown:"../SpryAssets/SpryMenuBarDownHover.gif",
					imgRight:"../SpryAssets/SpryMenuBarRightHover.gif"});
}

function getPageName() {
	//Returns the current page name
	
	var strPath = window.location.pathname;
	var strFile = strPath.substring(strPath.lastIndexOf("/") + 1);
	return(strFile);
}
/***************************************
		COOKIE HANDLING FUNCTIONS
***************************************/

// utility function to retrieve an expiration date in proper
// format; pass three integer parameters for the number of days, hours,
// and minutes from now you want the cookie to expire (or negative
// values for a past date); all three parameters are required,
// so use zeros where appropriate
function getExpDate(days, hours, minutes) {
    var expDate = new Date();
    if (typeof days == "number" && typeof hours == "number" &&
        typeof minutes == "number") {
        expDate.setDate(expDate.getDate() + parseInt(days));
        expDate.setHours(expDate.getHours() + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
        return expDate.toUTCString();
    }
}

// utility function called by getCookie()
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
    return decodeURI(document.cookie.substring(offset, endstr));
}

// primary function to retrieve cookie by name
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return "";
}

// store cookie value with optional details as needed
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + encodeURI(value) +
        ((expires) ? "; expires=" + expires : "") +
         ((path) ? "; path=" + path : "; path=/") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

// remove the cookie by setting ancient expiration date
function deleteCookie(name,path,domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "; path=/") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

/***************************************
		Other FUNCTIONS
***************************************/
// Returns address
function getML(strN, dom) {
	var s1 = "ilt";
	var s2;
	var s3 = "&#64;";
	var s4 = "&#46;";
	var s5;
	var res;
	var len
	
	len = String(strN).length;
	
	s5 = String(strN).substr(len-1, 1);
	s5 += String(strN).substr(0, len-1);
	s2 = s5 + s3; 
	s2 += "lift-tekelecar";
	if(dom==1) {
		s2 += s4 + "it";
	} else {
		s2 += s4 + "com";
	}
	
	res = "<a href=\"ma" + s1;
	res += "o:" + s2;
	res += "\">";
	res += s2 + "<\/a>";
	
	document.write(res);
}

// Runs an AJAX script to load product manual links from PDF file directory
// This uses the docs.php file, which must exist in same dir as calling page. 
// docs.php uses PHP to generate JS code, these function then insert into calling page.
url = document.location.href;
xend = url.lastIndexOf("/") + 1;
var base_url = url.substring(0, xend);

function loadDocs (url) {
	if (url.substring(0, 4) != 'http') {
		url = base_url + url;
	}

	// Create new JS element
	var jsel = document.createElement('SCRIPT');
	jsel.type = 'text/javascript';
	jsel.src = url;
	document.body.appendChild (jsel);

	return true;
}