/*
   Copyright (C) 2005 PimenTech SARL (http://www.pimentech.fr)

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with this library; see the file COPYING.LIB.  If not,
   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.	
*/

/*
 * public functions :
 *		* jsload
 *		* jssubmit
 *
 * This file use browser_snifer and common libraries.
 * You should add a "onLoadFunction()" function which can load your AJAX at end of <BODY>.
 * You should add a "actionChanged()" function which can load your AJAX at end of a SUBMIT.
 */

// RENDER TYPES //
/* 
 * :) faster
 * :) works fine on all browser
 * :) less "can't render" random error from the browser
 * :( javascript in <script> is not interpreted
 */
var TXT_AJAX_RENDER = 1;
/*
 * :) xml complient
 * :) javascript in <script> is interpreted
 * :( slower
 * :( IE bugs (css + use tbody in table)
 * :( randomly doesn't work on the browser
 */
var XML_AJAX_RENDER = 2; 

// REQUEST TYPES //
/*
 * :) can send HTTP errors
 * :) works on IE, Gecko, Opera
 * :) almost works on khtml, Safari
 * :( but bugs on <= IE5.5 ?
 * :( not a W3C spec
 */
var XMLHTTPREQUEST = 1;

/*
 * :( doesn't work on Safari nor Opera nor khtml
 * :( you have to add a actionChange() call at the end of your calling file
 */
var IMPLEMENTATION = 2;

// default values 
var RENDER = TXT_AJAX_RENDER;
var REQUEST = XMLHTTPREQUEST;

// Write a "onLoadFunction" function in your page, 
// this function will be called when the body will be finished
function onLoadBody() {
	if (typeof startKupu ==	'function')
    	kupu = startKupu();

	// load all ajax functions
	if (typeof onLoadFunction == 'function')
		onLoadFunction();
}

// load an url in a nodeid
function jsload(nodeid, url) {
	debug_msg('jsload on ' + nodeid + ' for url ' + url);
	node = document.getElementById(nodeid);
	loadXML(url, jsloadhandler, node, false);
}

// load an url in a nodeid and load actionChanged
function jsreload(nodeid, url) {
	debug_msg('jsload on ' + nodeid + ' for url ' + url);
	node = document.getElementById(nodeid);
	loadXML(url, jsloadhandler, node, true);
}

// submit a form to an url and reload nodeid
function jssubmit(form, nodeid, url) {
	debug_msg('jssubmit on form ' + form + ' and node ' + nodeid + ' for url ' + url);
	var params = "";
	for (var i=0; i<form.length; i++) {
		var name = form[i].name;
		var value = form[i].value;
		var type = form[i].type;

		if (name) {
			if ((type == 'checkbox' && form[i].checked) || 
				(type == 'radio' && form[i].checked) || 
				(type != 'checkbox' && type != 'radio'))

				params += "&" + name + "=" + encodeURIComponent(value);
		}
	}
	jsreload(nodeid, url + "?fromjs=yes" + params);
	return false; // to disable 'real' form submit
}

function loadXML(url, handler, param, reload) {
	var xmldoc = false;
	browser = get_browser();

	if (REQUEST == XMLHTTPREQUEST) {
		debug_msg('try XMLHTTPREQUEST');
		if (browser != 'ie' && typeof XMLHttpRequest != 'undefined') {
			xmldoc = new XMLHttpRequest();
		}
		else if (browser == 'ie') {
			try {
  				xmldoc = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
   					xmldoc = new ActiveXObject("Microsoft.XMLHTTP");
  				} catch (E) {
   					xmldoc = false;
			  }
 			}
		}
		if (xmldoc) {
			xmldoc.open("GET", url, true);
			xmldoc.onreadystatechange = function() {
  				if (xmldoc.readyState==4) {
					if (xmldoc.status == 200) {
						handler(xmldoc, param, reload);
					}
   					else {
						alert('URL Error : status '+ xmldoc.status + '\n' + xmldoc.statusText);
					}
				}
  			}
			xmldoc.send('');
		}
	}
	
	if (REQUEST == IMPLEMENTATION) {
		debug_msg('try IMPLEMENTATION');
		if (document.implementation && document.implementation.createDocument) {
			xmldoc = document.implementation.createDocument("", "", null);
			xmldoc.onload = function(  ) { handler(xmldoc, param, reload); }
		}
		else if (window.ActiveXObject) { 
			try {
				xmldoc = new ActiveXObject("Microsoft.XMLDOM");
				xmldoc.onreadystatechange = function(  ) {         
					if (xmldoc.readyState == 4) handler(xmldoc, param, reload);
				}
			} catch (e) {
				xmldoc = false;				
			}	
		}
		xmldoc.load(url);
	}
	debug_msg('xmldoc : ' + xmldoc);
	return xmldoc;
}


// Only for the XML_AJAX_RENDER
function _build_tree(dom, bloc) {
	if (dom.nodeType==3 || dom.nodeType==4 || dom.nodeType==7 || dom.nodeType==8) {
		if (dom.nodeValue == '')
			return
		var text = document.createTextNode(dom.nodeValue);
		bloc.appendChild(text);
		return;
	}
	else if (dom.nodeType == 1) {
		var node = document.createElement(dom.nodeName);
		var attrs = dom.attributes;
		for (var i=0; i<attrs.length; i++) {
			try{
				node.setAttribute(attrs[i].name, attrs[i].value);
				if (attrs[i].name.substring(0,2) == "on") {
					//eval('node.' + attrs[i].name + ' = "' + attrs[i].value + '";');
					node[attrs[i].name]=new Function(attrs[i].value);
				}
			} catch (e) {
				debug_msg('function _build_tree from ajax.js :\nAttribute : ' + attrs[i].name + ' = ' + attrs[i].value + '\n' + e);
			}
		}
	

		for (var n = dom.firstChild; n != null; n=n.nextSibling) {
			_build_tree(n, node);
		}
		bloc.appendChild(node);
		return;
	}
	debug_msg("nodetype inattendu : " + dom.nodeType);
}

// what to do with the xml document
function jsloadhandler(xmldoc, destnode, reload) {

	if (RENDER == XML_AJAX_RENDER) {
		debug_msg('XML_AJAX_RENDER');
		var bloc = document.createElement("DIV");
		if (typeof xmldoc.responseXML != 'undefined')
			xmldoc = xmldoc.responseXML;

		var body_dom = xmldoc.childNodes;
		for (var i=0; i<body_dom.length; i++) {
			_build_tree(body_dom[i], bloc);
		}	
		destnode.replaceChild(bloc, destnode.firstChild);
	}

	else if (RENDER == TXT_AJAX_RENDER) {
		debug_msg('TXT_AJAX_RENDER');
		var txt = '';
		if (typeof xmldoc.responseText != 'undefined') {
			txt = xmldoc.responseText;
		}
		else {
			try {
			txt = (new XMLSerializer()).serializeToString(xmldoc);
			} catch (e) {
				txt = xmldoc.xml;
			}
		}
		if (txt != '') {
			txt = txt.replace(/<\!\[CDATA\[|\]\]>/g, '');
		}
		destnode.innerHTML = txt;
	}

	if (reload && typeof actionChanged != 'undefined') {
		actionChanged();
	}
}
/*
   Copyright (C) 2005 PimenTech SARL (http://www.pimentech.fr)

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with this library; see the file COPYING.LIB.  If not,
   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.	
*/


var agt = navigator.userAgent.toLowerCase();
var Major = parseInt(navigator.appVersion);
var Minor = parseFloat(navigator.appVersion);

// Note: Opera and WebTV spoof Navigator.  We do strict client detection.
// If you want to allow spoofing, take out the tests for opera and webtv.

var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
	        && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
            && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));

var is_gecko = (agt.indexOf('gecko') != -1);

function get_type_nav() {
	if (is_nav) {
		if (Major <= 4)
			return Major;
		else if (agt.indexOf(";nav") != -1 || agt.indexOf("; nav") != -1)
			return 0;
		else if (Major >=5)
			return 6;
	}
	if (is_gecko)
		return 6;
	return 0;
}

var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
function get_ie_release() {
	if (is_ie) {
		if (Major < 4)
				return 3;
		else if	(Major == 4 && agt.indexOf("msie 4")!=-1)
				return 4;
		else if (Major == 4 && agt.indexOf("msie 5.0")!=-1)
				return 5;
		else if (Major == 4 && agt.indexOf("msie 5.5") !=-1)
				return 5.5;
		else if (Major == 4 && agt.indexOf("msie 6.") !=-1)
				return 6;
		}
	return 0;
}


var is_aol   = (agt.indexOf("aol") != -1);
function get_aol_release() {
	ie_release = get_ie_release ();
	if (is_aol) {
    	if (ie_release == 3)
			return 3;
		else if (ie_release == 4)
			return 4;
		else if (agt.indexOf("aol 5") != -1)
			return 5;
   		else if (agt.indexOf("aol 6") != -1)
			return 6;
	}
	return 0;
}

var is_opera = (agt.indexOf("opera") != -1);
function get_opera_release() {
    if (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1)
		return 2;
    else if (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1)
		return 3;
    else if (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1)
		return 4;
    else if (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1)
		return 5;
	else if (agt.indexOf("opera 6") != -1)
		return 6;
	else if (agt.indexOf("opera 7") != -1)
		return 7;
	else if (agt.indexOf("opera 8") != -1)
		return 8;
	return 0;
}

function get_gecko_release() {
	if (is_gecko) {
		if (agt.indexOf("rv:1.6") != -1)
			return 1.6;
		else if (agt.indexOf("rv:1.7") != -1)
			return 1.7;
		else if (agt.indexOf("rv:1.8") != -1)
			return 1.8;
	}
	return 0;
}

function get_browser() {
	if (is_opera)
		return 'opera';
	if (is_ie) {
		if (is_aol)
			return 'aol';
		return 'ie';
	}
	if (is_gecko)
		return 'gecko';
}

function get_release () {
	browser = get_browser();
	switch(browser) {
		case 'opera':
			return get_opera_release();
		case 'gecko':
			return get_gecko_release();
		case 'ie':
			return get_ie_release();
		case 'aol':
			return get_aol_release();
	}
	return 0;
}/*
   Copyright (C) 2005 PimenTech SARL (http://www.pimentech.fr)

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with this library; see the file COPYING.LIB.  If not,
   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.	
*/

if (!document.getElementById) {
	if (document.all) {
		document.getElementById = function() {
			if (typeof document.all[arguments[0]] != "undefined") {
				return document.all[arguments[0]];
			}
			else{
				return null;
			}
		}
	}
	else if (document.layers) {
		document.getElementById = function() {
			if (typeof document[arguments[0]] != "undefined" ) {
				return document[arguments[0]];
			} 
			else {
				return null;
			}
		}
	}
 }


// popup javascript pour confirmation de formulaire
function delete_confirm(element, text) {
	return confirm("Attention : \nVoulez-vous vraiment supprimer " + element + " ?" + text);
};

// creer popup html sans plantage firefox + centrée
function PopupCentrer(page, largeur, hauteur, options) {
	var top=(screen.height-hauteur)/2;
	var left=(screen.width-largeur)/2;
	window.open(page,"","top="+top+",left="+left+",width="+largeur+",height="+hauteur+","+options);
};

// redirection javascript
function redirect(url) {
	window.location = url;
}

// affiche le bloc de type id_on , efface le block de type id_off
function autoDisplay(id) {
  undisplay(id + '_off');
  display(id + '_on');
}

// inverse de autoDisplay
function autoUndisplay(id) {
  display(id + '_off');
  undisplay(id + '_on');
}

function display(id) {
	var object = document.getElementById(id);
	object.style.display = 'block';
}

function undisplay(id) {
	var object = document.getElementById(id);
	object.style.display = 'none';
}

// verifie que tous les champs de class 'necessary' sont remplis
// necessite un <p class="error_necessary">
function verif_form(form_name) {
	list = detect_necessary_fields(form_name);
	if (! eval_form(list)) {
		var p_error = document.getElementById(form_name);
		if (! p_error)
			alert('You have forgotten to implement <p class="error_necessary> element !');
		else
			p_error.style.display = 'block';
		return false;
	}
	return true;
}

// for verif_form function
function eval_form(list) {
	var return_value = true;
	for (var i=0; i<list.length; i++) {
		var el = list[i];
		if (! el.value) {
			try {
				el.style.borderColor = 'red';
				el.style.borderWidth = '2px';
			} catch(e) { ; }
			return_value = false;
		}
		else {
			try {
				el.style.borderColor = '#8cacbb';
				el.style.borderWidth = '1px';
			} catch (e) { ; }
		}
	}
	return return_value;
}

// for verif_form function
function detect_necessary_fields(form_name) {
	var form = document.forms[form_name];
	var list_necessary = new Array();
	for (var i=0; i<form.elements.length; i++) {
		if (form.elements[i].className.indexOf('necessary', 0) > -1) {
			list_necessary.push(form.elements[i]);
		}
	}
	return list_necessary;
}

// submit a form
function load_form(name, action) {
	var form = document.forms[name];
	form.action = action;
	form.submit();
}

/*
 * Debug messages
 */

var js_debug = false;

function debug_msg(message) {
	if (js_debug && 
		!confirm('Javascript debug message\n' + 
		  '-------------------------------------------------\n' + message + '\n' +
		  '-------------------------------------------------\n' + 'Keep debugging mode on ?')
		)
		js_debug = false;
}

