/*---------------------------------------------
 * treemenuv1.0
 * Vijayakrishnan
 * Phykon Solutions (P) Ltd.
 *---------------------------------------------*/

/**
 * Revision #1
 * 1. Added node state save/load using cookies
 *---------------------------------------------*/

/**
 * global variables
 *---------------------------------------------*/
// none

/**
 * generate tree menu inside the specified DIV using the given input data
 * p_DivID - the div inside which to create the tree
 * p_Input - the input data (array of strings)
 * p_OpenLinksInNewWindow - if this is true, the node links will be opened a new window
 *---------------------------------------------*/
function generateTreeMenu(p_DivID, p_Input, p_OpenLinksInNewWindow) {
	var tree = $(p_DivID);
	if(!tree) {
		alert('Specified component cannot be found - '+p_DivID);
		return;
	}
	tree.addClassName('treemenu');
	if(!p_Input || p_Input.length<=0) {
		alert('No input data given for creating the tree');
		return;
	}
	
	if(!p_OpenLinksInNewWindow) p_OpenLinksInNewWindow=false;
	
	var html = '';
	var fields = null;
	
	var book = '';
	var chapter = '';
	var page = '';
	var type = '';
	var level = '';
	var icon = '';
	var text = '';
	var active = '';
	var ce = '';
	
	var prevLevel = '';
	var linkURL = '';
	var linkClass = 'node_link';
	
	var i = 0;
	var j = 0;
	for(i=0; i<p_Input.length; i++) {
		
		fields = _parseDataLine(p_Input[i]);
		if(fields==false) return;
		
		//Book,Chapter,Page,Type,1,Icon,Text,Active,CE
		book = fields[0];
		chapter = fields[1];
		page = fields[2];
		type = fields[3];
		level = fields[4];
		icon = fields[5];
		text = fields[6];
		active = fields[7];
		ce = fields[8];
		
		if(level<=prevLevel) {
			for(j=0; j<(prevLevel-level+1); j++) html+='</div>\n';
		}
		
		linkURL = '';
		if(page!='NULL' && page!=0) {
			if(type==-1) {
				linkURL = "../../"+book+"/content/"+page+".asp";
			}
			else {
				linkURL = "../../"+book+"/content/"+chapter+"_"+page+".asp";
			}
		}
		
		linkClass = 'node_link';
		if(active!='TRUE' && active!=1) {
			linkClass = 'node_link_inactive';
		}
		
		
		// id attribute added in revision #1
		var ntext = 'node_'+(i+1);
		
		html += '<div id="'+ntext+'" class="node_title" ce="'+ce+'" ico="'+icon+'">';
		
		html += '<img class="node_icon" src="images/folder.gif" onclick="_toggleExpand(this, true);" />';
		if(linkURL!='' && linkClass=='node_link') {
			html += '<a href="'+linkURL+'" ';
			if(p_OpenLinksInNewWindow) html += 'target="_blank" ';
			html += 'class="'+linkClass+'">'+text+'</a>';
		}
		else
			html += '<span class="'+linkClass+'">'+text+'</span>';
		html += '</div>';
		
		html += '<div class="node_outer">';
		
		prevLevel = level;
		
	}
	
	if(prevLevel>=0) {
		for(j=0; j<(prevLevel+1); j++) html+='</div>\n';
	}
	
	tree.update(html);
	
	// make sure all nodes with children show 'open' icon
	var nodeIcons = $$('img.node_icon');
	var nodeParent;
	for(i=0; i<nodeIcons.length; i++) {
		nodeParent = Element.extend(Element.extend(nodeIcons[i]).parentNode);
		if(nodeParent.next().innerHTML!='') {
			nodeIcons[i].src = '../../'+nodeParent.getAttribute('ico')+'icon_open.png';
		}
	}
	
	// make sure CE is taken into account correctly & set the ICON property
	for(i=0; i<nodeIcons.length; i++) {
		nodeParent = Element.extend(Element.extend(nodeIcons[i]).parentNode);
		if(nodeParent.next().innerHTML!=''){
			if(nodeParent.getAttribute('ce')!='OPEN') { // check CE
				_toggleExpand(nodeIcons[i], false);
			}
		}
		else {
			nodeIcons[i].src = '../../'+nodeParent.getAttribute('ico')+'icon.png'; // set ICON for child nodes
			
			// make sure children-holder-nodes without children are hidden (IE causes trouble otherwise)
			nodeParent.next().hide();
		}
	}
	
	// check if anything is node's state cookied, if so restore - revision #1
	var cookieValue = false;
	for(i=0; i<nodeIcons.length; i++) {
		nodeParent = Element.extend(Element.extend(nodeIcons[i]).parentNode);
		if(nodeParent.next().innerHTML!='') {
			cookieValue = _getCookieValue(nodeParent.id+'_state');
			if(cookieValue=='open' || cookieValue=='close') { // otherwise it means cookies are not supported
				if(cookieValue=='open') {
					if(!_isExpanded(nodeIcons[i])) _toggleExpand(nodeIcons[i], false);
				}
				else {
					if(_isExpanded(nodeIcons[i])) _toggleExpand(nodeIcons[i], false);
				}
			}
		}
	}
	
}

/**
 * parse the specified string of data into fields
 * assuming comma as the delimiter
 * p_Line - the element to be slid
 * internal - should NOT be called from outside this file
 *---------------------------------------------*/
function _parseDataLine(p_Line) {
	var line = p_Line.trim();
	var start = line.indexOf('(');
	if(start==-1) {
		alert('Error parsing data line - '+line);
		return false;
	}
	start++;
	var end = line.lastIndexOf(')');
	if(end==-1) {
		alert('Error parsing data line - '+line);
		return false;
	}
	line = line.substring(start, end);
	var fields = _splitFields(line); //line.split(',');
	if(!fields || fields.length<9) {
		alert('Error parsing data line - '+line);
		return false;
	}
	return fields;
}

/**
 * split the specified string of data into fields
 * supports quotes, dbl-quotes and escaped quotes
 * p_Line - the element to be slid
 * internal - should NOT be called from outside this file
 *---------------------------------------------*/
function _splitFields(p_Line) {
	var fields = new Array();
	var quoteStarted1 = false;
	var quoteStarted2 = false;
	var escaped = false;
	var fieldIndex = 0;
	var fieldStart = 0;
	var i = 0;
	for(i=0; i<p_Line.length; i++) {
		switch(p_Line.charAt(i)) {
			case '"':
				if(i>0) {
					if(p_Line.charAt(i-1)=="\\") break; // check if escaped char
				}
				if(quoteStarted1==false)
					quoteStarted1=true;
				else
					quoteStarted1=false;
				break;
			case "'":
				if(i>0) {
					if(p_Line.charAt(i-1)=="\\") break; // check if escaped char
				}
				if(quoteStarted2==false)
					quoteStarted2=true;
				else
					quoteStarted2=false;
				break;
			case ',':
				if(quoteStarted1==true || quoteStarted2==true) break;
				if(i>0) {
					fields[fieldIndex] = p_Line.substring(fieldStart, i);
					fieldIndex++;
				}
				fieldStart=i+1;
				break;
		}
	}
	fields[fieldIndex] = p_Line.substring(fieldStart, p_Line.length); // take in the final field
	return fields;
}

/**
 * callback function upon node click
 * p_Node - the node that is clicked
 *---------------------------------------------*/
function _toggleExpand(p_Node, p_SaveCookie) {
	var img = p_Node;
	var node = Element.extend(Element.extend(p_Node).parentNode);
	var children = node.next();
	if(!children) return;
	if(children.innerHTML!='') {
		if(children.visible()) {
			children.hide();
			img.src = '../../'+node.getAttribute('ico')+'icon_close.png';
			if(p_SaveCookie==true) _writeSessionCookie(node.id+'_state', 'close'); // added in revision #1
		}
		else {
			children.show();
			img.src = '../../'+node.getAttribute('ico')+'icon_open.png';
			if(p_SaveCookie==true) _writeSessionCookie(node.id+'_state', 'open'); // added in revision #1
		}
	}
}

/**
 * check if the specified node is expanded - added in revision #1
 *---------------------------------------------*/
function _isExpanded(p_Node) {
	var img = p_Node;
	var node = Element.extend(Element.extend(p_Node).parentNode);
	var children = node.next();
	if(!children) return false;
	if(children.innerHTML!='') {
		if(children.visible()) {
			return true;
		}
	}
	return false;
}

/**
 * utility string trim function
 *---------------------------------------------*/
String.prototype.trim = function() {
	a = this.replace(/^\s+/, '');
	return a.replace(/\s+$/, '');
};

/**
 * utitlity cookie functions
 * thanks to John Gardner [www.braemoor.co.uk/software]
 * added in revision #1
 *---------------------------------------------*/
function _testSessionCookie () {
	document.cookie ="testSessionCookie=Enabled";
	if (_getCookieValue ("testSessionCookie")=="Enabled")
		return true 
	else
		return false;
}
function _writeSessionCookie (cookieName, cookieValue) {
	if (_testSessionCookie()) {
		document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
		return true;
	}
	else return false;
}
function _getCookieValue (cookieName) {
	var exp = new RegExp (escape(cookieName) + "=([^;]+)");
	if (exp.test (document.cookie + ";")) {
		exp.exec (document.cookie + ";");
		return unescape(RegExp.$1);
	}
	else return false;
}


  
