/*
************************************************************************************************
SCRIPT AUTHOR:	Francois Dolle										    Copyright: InFX Networks
MODIFIED BY:	Chris Merry

PREREQUISITES:	pagesupport.js for rtnEl(id) function only at present
				ajax.js for all ajax calls now

CHANGELOG:		now works with our common ajax library.
				various changes to optimise / reduce code size.
************************************************************************************************


************************************************************************************************
HOW TO GET EACH MENU STYLE TO WORK !!
************************************************************************************************

BREADCRUMB -> DEFINE : 
					MUST CALL "find_breadcrumb(node)"
						
					<div id='product_breadcrumb'>
						<script language="javascript">find_breadcrumb(159);<\/script>
					<\/div>

		
FINDER -> DEFINE : 			
					MUST CALL "create_finder(node,over/out)" (onclick->over, onmouseout->out)

					<div id="product_finder" class="menu">
						<div onmouseout="create_finder(0,0)" onclick="create_finder(0,1)">finder<\/div>
					<\/div>
					
					
NAVIGATION -> DEFINE :		MUST CALL "navigation(node,menu(1) or navigation(0))" to display all the children <if you want to display the brother put first_menu_node instead of menu_node in the ajax request function>

					<div id='product_navigation'>
						<script language="javascript">navigation(268);<\/script>
					<\/div>

EACH MUST HAVE A TIMEOUT IN THE ARRAY timeouts
*/

/**************************************************************************************************/
/**************************      SHARED VARIABLES           ***************************************/
/**************************************************************************************************/
var widget_script = '/cgi-bin/infxwidgets/widget-node-navigation.pl';
//var widget_script = '/cgi-bin/fd_breadcrumb2.pl';

/**************************************************************************************************/
/**************************      TIMEOUT VARIABLE ARRAY        ************************************/
/**************************************************************************************************/

var timeouts = new Array();
timeouts['product_navigation'] = null;
timeouts['product_finder'] = null;
timeouts['product_breadcrumb'] = null;
timeouts['product_breadcrumb_open'] = null;


/**************************************************************************************************/
/**************************      SHARED FUNCTIONS           ***************************************/
/**************************************************************************************************/

function truncate(s,l){		//truncate text
	if (s.length > l){
		s = s.substring(0,l-3) 
		for (var j=s.length;j>0;j--){
			if (s.charAt(j) == ";") j=-1
			if (s.charAt(j) == "&") return s.substring(0,j) + "...";
		}
		return s + "...";
	}
	return s;
}

/**************************      MENU CREATION              ***************************************/

function create_menu(json,node_id,whatisit,first){	//function called after an ajax request to put in the innerHTML of the parent its children
	//alert(whatisit);
	var cat = _ext.JSON.decode(json);
	
	// Creation of HTML code
	// add class if it is the second level or if it is in the rest of the menu because the CSS must be different between the first UL and the others
	var string = (first)?"<ul id='"+whatisit+"_ul_"+node_id+"'>":"<ul id='"+whatisit+"_ul_"+node_id+"' class='sub'>";
	
	for (var p in cat){
		var mover = "onmouseover=do_menu('"+cat[p].id+"',1,"+cat[p].leaf+",'"+whatisit+"')";
		var mout = "onmouseout=do_menu('"+cat[p].id+"',0,"+cat[p].leaf+",'"+whatisit+"')";
		
		var sub_div = "<div class='sub' id='"+whatisit+"_"+cat[p].id+"'><\/div>";
		var text_div = "<div "+mover+" "+mout+" onclick='navigate_menu("+_ext.JSON.encode(cat[p])+");'>"+truncate(cat[p].text,25)+"<\/div>";
		
		//put a bottom border but not for the last one
		var cls = (p != (cat.length-1))?"border":"";
		
		if(!parseInt(cat[p].leaf)){
			string += "<li id='"+whatisit+"_li_"+cat[p].id+"' class='folder "+cls+"'>"+sub_div+""+text_div+"<\/li>";
		}else{
			string += "<li id='"+whatisit+"_li_"+cat[p].id+"' class='file "+cls+"'>";	// LI
			string += "<div "+mover+" "+mout+" onclick='navigate_menu("+_ext.JSON.encode(cat[p])+");'>";	// DIV
			string += truncate(cat[p].text,25);
			string += "<\/div>";	// /DIV
			string += "<\/li>";	// /LI
		}	
	}
	string += "<\/ul>";
	// Insert my HTML code in the innerHTML of the ul parent
	rtnEl(whatisit+'_'+node_id).innerHTML = string;
	
	// BEN
	if (cat.length>0){
		rtnEl(whatisit+'_'+node_id).style.visibility = "visible";		
		rtnEl(whatisit+'_ul_'+node_id).style.visibility = "visible";	
	}
	
}

/**************************     ON EVENTS ON THE MENU       ***************************************/

function do_menu(node_id,isover,isleaf,whatisit){	// function which display the rest of my menu called on mouseover of an element or on mouseout
	//alert('hello');
	if(isover) {	// Onmouseover
		//var f = "timeout_"+whatisit+"(0,whatisit)";
		//eval(f);
		timeout_menu_types(0,whatisit);
		
		
		var li_el = rtnEl(whatisit+'_li_'+node_id);
		alter_class(li_el,'hilite','add');
		
		var el = rtnEl(whatisit+'_'+node_id);
		//if(!el){
		//	var firstdiv = document.createElement("div");
		//	firstdiv.setAttribute("id",whatisit+"_"+node_id);
		//	rtnEl(whatisit).appendChild(firstdiv);
		//	el = rtnEl(whatisit+'_'+node_id);
		//}
		//rtnEl('debug').innerHTML = rtnEl('debug').innerHTML + "over:"+node_id+"<br>";

		if(el){
			el.style.display = 'inline';
			
			if(el.innerHTML == ""){
				ajax_post_request(widget_script,{'menu_node':node_id},"create_menu(http_request.responseText,'"+node_id+"','"+whatisit+"',0);");
			}else{
				//Hide all of my grandchildren
				hide_grand_children(node_id,whatisit);
				//Show my children (now)
				//alert(el.childNodes[0].ChildNodes.length);
				
				// BEN
				if (el.childNodes[0].childNodes.length>0){// only show menu if the menu is not empty
					//rtnEl(whatisit+'_'+node_id).style.visibility = "visible";		
					rtnEl(whatisit+'_ul_'+node_id).style.visibility = "visible";	
					rtnEl(whatisit+'_ul_'+node_id).style.display = "block";	
				}

			}
			
			
			// BEN  don't show here if it is notyet loaded, do the show in create_menu and only if there is some content
			//rtnEl(whatisit+'_'+node_id).style.visibility = "visible";				
			//rtnEl(whatisit+'_'+node_id).style.display = "inline";
		}
		
		//Hide the children of my brothers
		hide_brother_children(node_id,whatisit);
	}else{			// Onmouseout
		//var f = "timeout_"+whatisit+"(1,whatisit)";
		//eval(f);
		
		timeout_menu_types(1,whatisit);
		
		//to call a function which hide the children of the first level
		//and a function which hide all the div in first level -> close_menu(node_id)
	}
}

/**************************        HIDE GRAND CHILDREN         ***************************************/

function hide_grand_children(node_id,whatisit){	// to have a clean display, I just want to show my children so I have to hide my grandchildrens
	// get the div which contains my children
	div_node = rtnEl(whatisit+'_'+node_id);
	//alert(div_node.id);
	//if the div has child
	if(div_node.childNodes[0]){
		//For all the children of that div
		for(var i=0; i<div_node.childNodes[0].childNodes.length;i++){
			var el = div_node.childNodes[0].childNodes[i];
			// remove the class "hilite" of the children of my chidren equivalent to the :hover in CSS
			alter_class(el,'hilite','remove');
			
			//if it is a leaf the "el.childNodes[1]" has no property
			if(el.childNodes[1]){
				//hide all the div which contains my grandchildren
				el.childNodes[0].style.visibility = "hidden";
				el.childNodes[0].style.display = "none";
			}
		}
	}
}

/**************************        HIDE BROTHERS         ***************************************/

function hide_brother_children(node_id,whatisit){	//hide all the children brother for the rest of the menu
	// Get element LI in the HTML hierachi, and get the DIV parent of the UL and of the LI
	li_node = rtnEl(whatisit+'_li_'+node_id);
	div_parent = li_node.parentNode.parentNode;
	//For all the LI in the DIV
	for (var i=0;i<div_parent.childNodes[0].childNodes.length;i++){
		var el = div_parent.childNodes[0].childNodes[i];
		//if it is itself
		if(el.id != whatisit+'_li_'+node_id){
			// here is brother not self
			// remove the class "hilite" of the brothers equivalent to the :hover in CSS
			alter_class(el,'hilite','remove');
			//if it is a leaf the "el.childNodes[1]" has no property
			if(el.childNodes[1]){
				//hide the content of the brothers children
				el.childNodes[0].style.visibility = "hidden";
				el.childNodes[0].style.display = 'none';
			}
		}
	}
}

/**************************************************************************************************/
/**********************          FUNCTIONS FOR BREADCRUMB               ***************************/
/**************************************************************************************************/


/**********************    FIRST FUNCTION CALLED FOR BREADCRUMB         ***************************/

function find_breadcrumb(breadcrumb_node){	//first function called
	// make an ajax request to get all the path "breadcrumb" of the selected node the callback function is "create_breadcrumb"
	ajax_post_request(widget_script,{'breadcrumb_node':breadcrumb_node},"create_breadcrumb(http_request.responseText,"+breadcrumb_node+",'product_breadcrumb',0);");
}

/**************************        BREADCRUMB CREATION        *************************************/

function create_breadcrumb(json,node_id,whatisit){	//create the breadcrumb first level
	//alert(whatisit);
	var s = _ext.JSON.decode(json);

	var string = "<ul>";
	//string += "<!--<li class='top'><label>You are here:&nbsp;</label><\/li>//-->";
	string += "<li class='top'><a href='/index.shtml'>Home</a><\/li> ";
	
	//will there is child I create the path until I am on the selected node
	while(s.child){
		string += " <span class='divider'>&#187;</span> <div class='menu' id='"+whatisit+"_"+s.id+"'><\/div> <li id='"+whatisit+"_li_"+s.id+"' onmouseover=\"delayed_display_menu('"+s.id+"',1,'"+whatisit+"',2000);\" onmouseout=delayed_display_menu('"+s.id+"',0,'"+whatisit+"',0) class='top'><a href='#navigate-to' onmousedown='navigate_menu("+_ext.JSON.encode(s)+");'>"+s.name+"</a><\/li>";
		s = s.child;
	}
	string += "<\/ul>";
	rtnEl('product_breadcrumb').innerHTML = string;

}

/**************************   ON EVENTS ON THE BREADCRUMB   ***************************************/

function delayed_display_menu(node_id,over,whatisit,delay){	// function which just manages the first level of my breadcrumb close to the function "do_menu"
	if (timeouts['product_breadcrumb_open']) clearTimeout(timeouts['product_breadcrumb_open']);
	if (over){
		timeouts['product_breadcrumb_open'] = setTimeout("display_menu('"+node_id+"',"+over+",'"+whatisit+"')",delay);
	}else{
		display_menu(node_id,over,whatisit);
	}
}


function display_menu(node_id,over,whatisit){	// function which just manages the first level of my breadcrumb close to the function "do_menu"
	//alert(whatisit);
	//timeout_breadcrumb(0,whatisit);
	
	//Open breadcrumb with delayed action
	//if(delay || timeouts[whatisit+'_delay'] != null){
	//	if(timeouts[whatisit+'_delay'] != null){
	//		clearTimeout(timeouts[whatisit]+'_delay');
	//		timeouts[whatisit+'_delay']=null;
	//	}
	//	setTimeout("display_menu('"+node_id+"','"+over+"','"+whatisit+"');",delay);
	//}
	timeout_menu_types(0,whatisit);
	var el = rtnEl(whatisit+'_li_'+node_id);
	if(over){	 // Onmouseover
		
		//hilite the breadcrumb top item
				
		alter_class(el,'hilite','add');
		alter_class(el,'active','add');

		if(rtnEl(whatisit+'_'+node_id)){
			//if the content of my node has not already been loadded
			if(rtnEl(whatisit+'_'+node_id).innerHTML == ""){
				ajax_post_request(widget_script,{'first_menu_node':node_id},"create_menu(http_request.responseText,'"+node_id+"','"+whatisit+"',1);");
			}
			//Hide all the brother children in the breadcrumb first level
			close_menu(node_id,whatisit);
			//Hide all of my grandchildren
			hide_grand_children(node_id,whatisit);
		}
	}else{		// Onmouseout
		// Get element LI in the HTML hierachi, and get the DIV parent of the UL and of the LI

		// remove the class "hilite" of the breadcrumb top item, and replace with "active"
		alter_class(el,'hilite','remove');
		alter_class(el,'active','add');

		//SetTimeout 
		timeout_menu_types(1,whatisit);
	}
}


/**************************************************************************************************/
/**********************              FUNCTIONS FOR FINDER               ***************************/
/**************************************************************************************************/

function create_finder(finder_node,over){	//first function called
	var whatisit = "product_finder";
	
	if(over){
		//timeout_finder(0,whatisit);	
		timeout_menu_types(0,whatisit);

		//creation of my finder container
		var mycontainer = rtnEl(whatisit);
		if(!rtnEl(whatisit+"_"+finder_node)){
		
			var firstdiv = document.createElement("div");
			firstdiv.setAttribute("id",whatisit+"_"+finder_node);
			mycontainer.appendChild(firstdiv);
			
			// make an ajax request to get all the path "breadcrumb" of the selected node the callback function is "create_breadcrumb"
			ajax_post_request(widget_script,{'menu_node':finder_node},"create_menu(http_request.responseText,'"+finder_node+"','"+whatisit+"',1);");
		}
		else{
			rtnEl(whatisit+"_"+finder_node).style.display = "inline";
			//Hide all of my grandchildren
			hide_grand_children(finder_node,whatisit);
		}
	}else{
		//timeout_finder(1,whatisit);
		timeout_menu_types(1,whatisit);
	}
}



/**************************************************************************************************/
/**********************            FUNCTIONS FOR NAVIGATION             ***************************/
/**************************************************************************************************/


/*************************** FIRST FUNCTION CALLED FOR NAVIGATION *********************************/

function navigation(parent_node,option,type){	//first function called
	var callback_function = (option)?"create_menu":"create_navigation";
	var whatisit = (type)?type:"product_navigation";
			
	//creation of my navigation container
	var mycontainer = rtnEl(whatisit);
	if(!rtnEl(whatisit+"_"+parent_node)){
	
		var myfirstdiv = document.createElement("div");
		myfirstdiv.setAttribute("id",whatisit+"_"+parent_node);
		mycontainer.appendChild(myfirstdiv);
		
		// make an ajax request to get all the path "breadcrumb" of the selected node the callback function is "create_breadcrumb"
		ajax_post_request(widget_script,{'menu_node':parent_node},callback_function+"(http_request.responseText,'"+parent_node+"','"+whatisit+"',1);");
	}
}


/**************************      NAVIGATION CREATION          *************************************/
function create_navigation(json,node_id,whatisit){	//create the navigation if we don't want a menu

	//alert(whatisit);
	var cat = _ext.JSON.decode(json);

	// Creation of HTML code
	var string;
	//add class if it is the second level or if it is in the rest of the menu because the CSS must be different between the first UL and the others
	string = "<ul id='"+whatisit+"_ul_"+node_id+"'>";
	
	//alert(cat.length);
	for (var p in cat){
		//alert(p);
		
		var click = "onclick='navigate_menu("+_ext.JSON.encode(cat[p])+");'";
		var mover = "onmouseover=navigation_hilite('"+cat[p].id+"',1,'"+whatisit+"')";
		var mout = "onmouseout=navigation_hilite('"+cat[p].id+"',0,'"+whatisit+"')";
		var text_div = "<div "+click+" "+mover+" "+mout+">"+truncate(cat[p].text,25)+"<\/div>";
		
		//put a bottom border but not for the last one
		var cls = (p != (cat.length-1))?"border":"";
		
		string += (!cat[p].leaf)?"<li id='"+whatisit+"_li_"+cat[p].id+"' class='folder "+cls+"'>"+text_div+"<\/li>":"<li id='"+whatisit+"_li_"+cat[p].id+"' class='file "+cls+"'><div "+mover+" "+mout+" onclick='navigate_menu("+_ext.JSON.encode(cat[p])+");'>"+truncate(cat[p].text,25)+"<\/div><\/li>";
		string += "";
		
	}
	string += "<\/ul>";
	// Insert my HTML code in the innerHTML of the ul parent

	rtnEl(whatisit+'_'+node_id).innerHTML = string;
			
	// BEN
	if (cat.length>0){
		rtnEl(whatisit+'_'+node_id).style.visibility = "visible";		
		rtnEl(whatisit+'_ul_'+node_id).style.visibility = "visible";	
	}
	
}

/**************************      NAVIGATION hilite         *************************************/
// This is really 'do_menu' but it is a simple version for fixed navigation
function navigation_hilite(node_id,over,whatisit){
	alter_class(rtnEl(whatisit+"_li_"+node_id),'hilite',(over)?'add':'remove');
}

/************************         CLOSE ALL MENUS FOR NAVIGATION, AND SUB MENU FOR BREADCRUMB/FINDER    *************************/

function close_menu(node_id,whatisit){	//Hide all the brother children in the breadcrumb first level
	//alert(whatisit);
	var container = rtnEl(whatisit);
	// For all the brother
	for (var i=0;i<container.childNodes[0].childNodes.length;i++){
		// if it exists a tagname
		var el = container.childNodes[0].childNodes[i];
		if(el.tagName){
			//if the tagname equal 'div' (I want to hide just the div)
			if(el.tagName.toLowerCase() == 'div' ){
				el.style.display = (el.id != whatisit+'_'+node_id)?'none':'inline';
			}
			// breadcrumb top item show it is active
			else if(el.tagName.toLowerCase() == 'li' ){
				//if it is not self
				if(el.id != whatisit+'_li_'+node_id){
					alter_class(el,'active','remove');
				}
			}
		}
	}
}


/************************         ADD REMOVE CLASSES     *************************/
function alter_class(element,classname,action){
	if(element){
		var classRegEx = new RegExp(" "+classname,"g");
		element.className = element.className.replace(classRegEx,"");
		if(action == 'add') element.className += " "+classname;
	}
}

/************************         CLOSE THE TOP MENU FOR BREADCRUMB/FINDER     *************************/
function close_menu_types(node_id,whatisit){
	if(whatisit.indexOf('finder') != -1){
		var obj = rtnEl(whatisit+"_0");
		if(obj) obj.style.display = "none";
	}else if(whatisit.indexOf('navigation') != -1){
		var container = rtnEl(whatisit);
		var ul_elements = container.getElementsByTagName('ul');
		for(var x=0;x<ul_elements.length;x++){ 
			if(x == 0){
				var li_elements = ul_elements[x].getElementsByTagName('li');
				for(var y=0;y<li_elements.length;y++){ alter_class(li_elements[y],'hilite','remove'); }		
			}else{
				ul_elements[x].style.display = 'none';
			}
		}
		
		//if(container.childNodes[2].childNodes[0]){
		//	for (var i=0;i<container.childNodes[2].childNodes[0].childNodes.length;i++){
		//		container.childNodes[2].childNodes[0].childNodes[i].childNodes[0].style.display = "none";
		//	}
		//}
	}else if(whatisit.indexOf('breadcrumb') != -1){
		close_menu(node_id,whatisit);
	}
}

function debug(text){
	var panel = rtnEl('debug_panel');
	panel.innerHTML += text + "<br>";
}

function timeout_menu_types(set,whatisit){
	if(!set){
		// ClearTimeout
		clearTimeout(timeouts[whatisit]);
		timeouts[whatisit]=null;
		//debug("Clear timeout <b>"+whatisit+"</b> - <i>"+timeouts[whatisit]+"</i>");
	}else{
		//SetTimeout 
		//call "close_menu" after a laps oftime
		timeouts[whatisit] = setTimeout("close_menu_types('ul_0','"+whatisit+"');",1000);
		//debug("Set timeout <b>"+whatisit+"</b> - <i>"+timeouts[whatisit]+"</i>");
	}
}

function navigate_menu(node){
	if(typeof(node.post) == 'object'){
		//alert("form post action: "+node.action);
		var form = document.createElement("form");
		form.action = node.action;
		form.method = 'post';
		form.id = _ext.id();
		
		for(var p in node.post){
			var el = document.createElement("input");
			el.type = "hidden";
			el.name = p;
			el.value = (_ext.isObject(node.post[p]))?_ext.JSON.encode(node.post[p]):node.post[p];
			form.appendChild(el);
		}
		document.body.appendChild(form);
		form.submit();
	}else{
		//alert("standard link: "+node.link);
		if(node.link != null && node.link != '') location.href = node.link;
	}
}

