/* AJAX FUNCTIONS */
	var xhr = null; 

	function getXhr(){
		if(window.XMLHttpRequest) // Firefox et autres
		   xhr = new XMLHttpRequest(); 
		else if(window.ActiveXObject){ // Internet Explorer 
		   try {
	                xhr = new ActiveXObject("Msxml2.XMLHTTP");
	            } catch (e) {
	                xhr = new ActiveXObject("Microsoft.XMLHTTP");
	            }
		}
		else { // XMLHttpRequest non supporté par le navigateur 
		   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
		   xhr = false; 
		} 
	}
	
	// Node cleaner
	function go(c){
		if(!c.data.replace(/\s/g,''))
			c.parentNode.removeChild(c);
	}

	function clean(d){
		var bal=d.getElementsByTagName('*');

		for(i=0;i<bal.length;i++){
			a=bal[i].previousSibling;
			if(a && a.nodeType==3)
				go(a);
			b=bal[i].nextSibling;
			if(b && b.nodeType==3)
				go(b);
		}
		return d;
	} 

	// call function for get method
	function get_xhr(url){
		getXhr();
		// define what will append when the response will be received
		xhr.onreadystatechange = function(){
			// Do something only if everything is allright
			if(xhr.readyState == 4 && xhr.status == 200){
				content = clean(xhr.responseXML.documentElement);
				// get response list
				var responses= content.getElementsByTagName("response");
				if(responses){
					table= document.getElementById("tree");
							
					for(var i=0; i<responses.length; i++){
						
						id=getAttribute(responses[i], "id");
						
						if(id){
							
						
							add_responses_in_table(table, "line_"+id, responses[i]);
							loaded["responses"][id]= responses[i];
							
						}
						
					}
				}
				
				
				// get action_list
				var actions= content.getElementsByTagName("action");
				if(actions.length>0){
					document.getElementById("forum_action_part").innerHTML=actions[0].firstChild.nodeValue;
					// save datas to avoid further reloading
					id=getAttribute(actions[0], "id");
					type=getAttribute(actions[0], "type");
					if(!loaded["actions"][id])
						loaded["actions"][id]= new Array();
					loaded["actions"][id][type]= actions[0].firstChild.nodeValue;
				}
					
				var messages= content.getElementsByTagName("message");
			}
		}
		xhr.open("GET", url,true);
		xhr.send(null);	
	}
/* END AJAX */



/* BEGIN CALLED FUNCTION */
	var loaded= {"responses": new Array(), "actions": new Array()};
	//var actions= new Array();
	
	
	// the only one called function
	function forum_action(id, read, toggle){
		var param="";
		if(read)
			param+= forum_read(id);
		if(toggle)
			param+= toggle_responses(id);
		if(param.length>0)
			get_xhr(window.location.pathname+"?ajax"+param);
	}
	
	
	function toggle_responses(id){
	//	return false;
		var to_load="";
		var line= document.getElementById("line_"+id);
		if(line){
			var icon= getChildren(line, "div", "class", "icon opendir");
			
			if(icon)
				to_load= forum_hide_responses(id);
			else
				to_load= forum_show_responses(id);
		}
		return to_load;
	}
	
	
	function forum_show_responses(id){
	//	get_xhr(window.location.pathname+"?ajax&expand="+id);
		//alert("display");
		var to_load="";
		var line= document.getElementById("line_"+id);
		if(line){
		//	setAttribute(line, "class", "displayed");
			var icon= getChildren(line, "div", "class", "icon dir");
			if(icon)
				setAttribute(icon, "class", "icon opendir");
			if(loaded["responses"][id])
				add_responses_in_table(document.getElementById("tree"), "line_"+id, loaded["responses"][id]);	
			else
				to_load="&expand="+id;
		}
		return to_load;
	}
	
	function forum_hide_responses(id){
		var line= document.getElementById("line_"+id);
		if(line){
			//setAttribute(line, "class", "");
			var icon= getChildren(line, "div", "class", "icon opendir");
			if(icon)
				setAttribute(icon, "class", "icon dir");
				
			while(line.nextSibling && getAttribute(line.nextSibling, "id").indexOf("line_")==-1)
				line.parentNode.removeChild(line.nextSibling);
			
			
		
			//resp.style.display="none";		
		}
		return "";
	}
	
	function add_responses_in_table(table, line_id, resp){
		// add rows and cells
		var row_pos=get_row_number(table, line_id);
		var tr_list= resp.firstChild.nodeValue.match(/<tr(.|\n|\r)*?tr>/g);
		for(var j=0; j<tr_list.length; j++){
			row_pos++;
			var tr= table.insertRow(row_pos);
			setAttribute(tr, "id", tr_list[j].replace(/(\W*<tr(.*?id='([^'"]*)'))(.|\n|\r)*/, "$3") );
			setAttribute(tr, "class", tr_list[j].replace(/(\W*<tr(.*?class='([^'"]*)'))(.|\n|\r)*/, "$3") );
			var td_list= tr_list[j].match(/<td(.|\n|\r)*?td>/g);
			for(var k=0; k<td_list.length; k++){
				var td= tr.insertCell(k);
				if(td_list[k].match(/(\W*<td(.*?id='([^'"]*)'))(.|\n|\r)*/, "$3"))
					setAttribute(td, "id", td_list[k].replace(/(\W*<td(.*?id='([^'"]*)'))(.|\n|\r)*/, "$3") );
				if(td_list[k].match(/(\W*<td(.*?class='([^'"]*)'))(.|\n|\r)*/, "$3"))
					setAttribute(td, "class", td_list[k].replace(/(\W*<td(.*?class='([^'"]*)'))(.|\n|\r)*/, "$3") );
			
				td.innerHTML=td_list[k].replace(/(<td.*?>)((?:.|\n|\r)*?)(<\/td>)/g, "$2");
			}
		}
	}
	
	function forum_read(id){
		var to_load="";
		curr_read= getChildren(document.getElementById('tree'), "tr", "class", "selected");
		if(curr_read!=null){	// unset selected element
			//read[curr_read.id]=document.getElementById("forum_action_part").innerHTML;
			setAttribute(curr_read, "class", "");
		}
			
		if(loaded["actions"][id] && loaded["actions"][id]["read"]){	// avoid reloading already known datas
			document.getElementById("forum_action_part").innerHTML= loaded["actions"][id]["read"];
		}else{
			//get_xhr(window.location.pathname+"?ajax&read="+id);
			to_load="&read="+id
		}
		if(document.getElementById("line_"+id))
			document.getElementById("line_"+id).setAttribute("class", "selected");
		else if(document.getElementById("resp_"+id))
			document.getElementById("resp_"+id).setAttribute("class", "selected");
		return to_load;
	}


	function get_row_number(table, row_id){
		tr_list= getChildren(table, "tr", "", "", "all");
		for(var i=0; i<tr_list.length; i++){
			if(tr_list[i].id==row_id)
				return i;
		}
		return -1;
	}
	
	
	function tree_pack(){
		tr_list= getChildren(table, "tr", "", "", "all");
		for(var i=0; i<tr_list.length; i++){
			if(tr_list[i].id.indexOf("line_")!=-1)
				forum_hide_responses(tr_list[i].id.replace("line_",""));
		}
	}
	
	function getURI(start){
		if(!start)
			start=0;
		var read=-1;
		var expand= new Array();
		var tr_list= getChildren(document.getElementById("tree"), "tr", "", "", "all");
		for(var i=0; i<tr_list.length; i++){
			if(tr_list[i].id.indexOf("line_")!=-1){
				var icon= getChildren(tr_list[i], "div", "class", "icon opendir");
				if(icon)
					expand[expand.length]= tr_list[i].id.replace("line_","");
			}
			if(getAttribute(tr_list[i], "class")=="selected")
				read= tr_list[i].id.replace(/(line|resp)_/,"");
		}
		var uri=window.location.pathname+"?read="+read+"&expand="+ expand.join(",")+"&start="+start;
		return uri;
	}
	
	function save_scroll(){
		var cook= "forum_scroll=";
		if(document.getElementById("show_tree")){
			cook+="_divT_"+document.getElementById("show_tree").scrollTop;
			cook+="_divL_"+document.getElementById("show_tree").scrollLeft;
		}
		cook+="_bodyT_"+document.getElementsByTagName("body")[0].scrollTop;
		cook+="_bodyL_"+document.getElementsByTagName("body")[0].scrollLeft;
		cook+="_htmlT_"+document.getElementsByTagName("html")[0].scrollTop;
		cook+="_htmlL_"+document.getElementsByTagName("html")[0].scrollLeft;
		//alert(div_top+"\n"+body_top+"\n"+html_top);
		document.cookie= cook+";path="+window.location.pathname;
	}
	
	function restore_scroll(){
		var div_top= document.cookie.replace(/.*?=divT_([0-9]*).*/, "$1");
		var div_left= document.cookie.replace(/.*?_divL_([0-9]*).*/, "$1");
		var body_top= document.cookie.replace(/.*?_bodyT_([0-9]*).*/, "$1");
		var body_left= document.cookie.replace(/.*?_bodyL_([0-9]*).*/, "$1");
		var html_top= document.cookie.replace(/.*?_htmlT_([0-9]*).*/, "$1");
		var html_left= document.cookie.replace(/.*?_htmlL_([0-9]*).*/, "$1");
		document.getElementsByTagName("html")[0].scrollTop= html_top;
		document.getElementsByTagName("html")[0].scrollLeft= html_left;
		document.getElementsByTagName("body")[0].scrollTop= body_top;
		document.getElementsByTagName("body")[0].scrollLeft= body_left;
		if(document.getElementById("show_tree")){
			if(div_top.search(/^[0-9]*$/) != -1)
				document.getElementById("show_tree").scrollTop= div_top;
			if(div_left.search(/^[0-9]*$/) != -1)
				document.getElementById("show_tree").scrollLeft= div_left;
		}
		//delete the cookie
		var date= new Date();
		date.setTime (date.getTime() - 100000);
		document.cookie="forum_scroll=; expires="+date.toGMTString();
	}
	
	window.onunload= save_scroll;
	window.onload= restore_scroll;

/* END CALLED FUNCTIONS */

/* ELEMENTS MANIPULATION */

	// need to redefine this function due to IE problem
	function getAttribute( elm, aname ) {
		try{
			var avalue = elm.getAttribute( aname );
		}catch(exept){
		}
		if (!avalue) {
			try{
				for ( var i = 0; i < elm.attributes.length; i ++ ) {
					var taName = elm.attributes[i].name.toLowerCase();
					if ( taName == aname ) {
						avalue = elm.attributes[i].value;
						return avalue;
					}
				}
			}catch(exept){
				avalue="";
			}
		}
		return avalue;
	};
	
	// need to redefine this function due to IE problem
	function setAttribute( elm, attr, val ) {
		if(attr=="class"){
			elm.setAttribute("className", val);
			elm.setAttribute("class", val);
		}else{
			elm.setAttribute(attr, val);
		}
	};
	
	/* return a child element
		elem: element we are searching in
		elem_type: type of the eleemnt we are searching (DIV, A, etc...)
		elem_attribute: attribute of the searched element that must match
		elem_attribute_match: value that elem_attribute must match
		option: "all" if must return an array of all children, otherwise return the first match element
		depth: depth of search (-1 or no set => unlimited)
	*/
	function getChildren(elem, elem_type, elem_attribute, elem_attribute_match, option, depth)
	{	
		if(!option)
			var option="single";
		if(!depth)
			var depth=-1;
		if(elem){
			var children= elem.childNodes;
			var result=null;
			var results= new Array();
			for (var x=0;x<children.length;x++) {
				strTagName = new String(children[x].tagName);
				children_class="?";
			//	if(strTagName== "tr")
					
					
				if(strTagName!= "undefined"){
					child_attribute= getAttribute(children[x],elem_attribute);
						
					if((strTagName.toLowerCase()==elem_type.toLowerCase() || elem_type=="") && (elem_attribute=="" || child_attribute==elem_attribute_match)){
						if(option=="all"){
							results.push(children[x]);
						}else{
							return children[x];
						}
					}
					if(depth!=0){
						result=getChildren(children[x], elem_type, elem_attribute, elem_attribute_match, option, depth-1);
						if(option=="all"){
							if(result.length>0){
								results= results.concat(result);
							}
						}else if(result!=null){												
							return result;
						}
					}
				}
			}
			if(option=="all")
				return results;
		}
		return null;
	};	
	

/* END MANIPULATION */

