/**
* MiniClick
* Gestionnaire de tableau collaboratif
* Copyright (C) 2006 Guillaume Monet <gm@ibreizh.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 
*
* @package miniclick
* @version 3.1.0
*/
var table;

	function createRequestObject() {
		var ro;
		var browser = navigator.appName;
		if(browser == "Microsoft Internet Explorer"){
			ro = new ActiveXObject("Microsoft.XMLHTTP");
		}else{
			ro = new XMLHttpRequest();
		}
		if (!ro) {
			alert('Cannot create XMLHTTP instance');
			return false;
		}
		return ro;
	}


	var http;
	var obj;

	function semon(object,table,colonne,id) {
		if(document.getElementById(object).getAttribute("readonly") != "readonly"){
			http = createRequestObject();
			obj = object;
			http.open('get', 'engine/miniclic/ajax/php/semaphore_include.php?action=IN&table='+table+'&colonne='+colonne+'&id='+id);
			http.onreadystatechange = handleResponse;
		//si la reponse est 0 le semaphore n'est pas posц╘ pour une raison ou une autre et on bloque la cellule en edition
			http.send(null);
		}
	}

	function semoff(object,table,colonne,id){
		if(document.getElementById(object).getAttribute("readonly") != "reaonly"){
			http = createRequestObject();
			obj = object;
			//On test d'abord si c'etait ici que l'on a mis le sem
			http.open('get', 'engine/miniclic/ajax/php/semaphore_include.php?action=OUT&table='+table+'&colonne='+colonne+'&id='+id);
			http.onreadystatechange = handleResponse;
			//On va relacher le semaphore
			http.send(null);
			sendTrigger(table,colonne,id,document.getElementById(obj).value);
		}
	}

	var rhttp;
	function getTrigger(){
		rhttp = createRequestObject();
		rhttp.open('get','engine/miniclic/ajax/php/trigger_include.php?action=GET&table='+table);
		rhttp.onreadystatechange = handleTriggerResponse;
		rhttp.send(null);
		setTimeout("getTrigger()", 3000);
	}

	var shttp;
	function sendTrigger(table,colonne,id,val){
		shttp = createRequestObject();
		shttp.open('get','engine/miniclic/ajax/php/trigger_include.php?action=SEND&table='+table+'&colonne='+colonne+'&id='+id+'&val='+val);
		shttp.send(null);
	}
	
	//fonction de mise Ю jour auto des combo box du module d'importation
	var chttp;
	function majcombo(num_table,num_select){
		var nom_table = document.getElementById('select_table'+num_table).value;
		chttp = createRequestObject();
		chttp.open('get','engine/miniclic/module_import/combo_import_include.php?action=GET&nom_table='+nom_table+'&num='+num_table+'&num_select='+num_select);
		chttp.onreadystatechange = handleComboResponse;
		chttp.send(null);
		
	}
	
	function handleTriggerResponse() {
		if(rhttp.readyState == 4){
			var response = rhttp.responseText;
			var array = response.split(';');
			var object = array[1];
			var colonne = array[2];
			var newvalue = array[3];
			var id = object + colonne ;
			if(id != ""){
				document.getElementById(id).value = newvalue;
			}
		}
	}

	function handleResponse() {
		if(http.readyState == 4){
			var response = http.responseText;
			if(""+response == "SEMON"){
				document.getElementById(obj).setAttribute("readonly","readonly");
				document.getElementById(obj).setAttribute("class","semon");
			}else{
				if(response == "SEMCRE"){
					document.getElementById(obj).removeAttribute("readonly");
					document.getElementById(obj).removeAttribute("class");
				}
			}
		}
	}
	
	function handleComboResponse() {
		if(chttp.readyState == 4){
			var response = chttp.responseText;
			var array = response.split(' ');
			var num = array[0];
			var num_select = array[1];
			var nom_table = array[2];
			var requete= array[3].split(',');
			handleComborow(num,requete);
			//window.open(requete.length,num);
			//Selection automatique des select en dessous
			for (var j=0;j<num_select;j++){
				if (document.getElementById('select_table'+j).value=="NM"){
					document.getElementById('select_table'+j).value=nom_table;
					handleComborow(j,requete);
				}
			}
		}
	}

	function handleComborow(num,requete){
		var item;
			// Efface les noeuds de la liste dÐroulante Ð® mettre Ð® jour
			while (document.getElementById('select_row'+num).hasChildNodes()){

				document.getElementById('select_row'+num).removeChild(document.getElementById('select_row'+num).lastChild);
			}
			// CrÃ©Ã© des nouveaux noeud pour la liste.
			for (var j=0;j<requete.length-1;j++){
				var champ=requete[j].split('-');
				var opt = document.createElement("option");
				// Attribut des valeurs aux champs.
				opt.value = champ[0];
				opt.text = champ[0];
				document.getElementById('select_row'+num).appendChild(opt);
			}
			var opt = document.createElement("option");
			opt.value = "NM";
			opt.text = "Not mapped";
			document.getElementById('select_row'+num).appendChild(opt);
	}

	function OuvrirPopup(page,nom,option) {
		window.open(page,nom,option);
	}


	function order(header,order){
		document.getElementById('sort').value=header;
		document.getElementById('order').value=order;
		document.getElementById('form_header').submit();
	}

	function fire_action(fire){
		document.getElementById('action').value=fire;
		document.getElementById('form_header').submit();
	}

	var current_id;
	function okp(id){
		current_id = id;
		var semid = "";
                var browser = navigator.appName;
                if (browser == "Microsoft Internet Explorer") {
                        semid = id.srcElement.alt;
                }else{
                        semid = id.target.alt;
                }
                document.getElementById(semid).value="ON";
	}

	var checkflag = false;
	
	function checkAll(){
		checkflag = ! checkflag;
		var inpNodes = document.getElementById('miniclic').getElementsByTagName('input');
		for(var i in inpNodes){
			var inp = inpNodes[i];
			if (inp.type == 'checkbox'){
				inp.checked = checkflag;
				display_checkbox_picture(inp.id)
			}
		}
	}
	
	function check(id){
		document.getElementById(id).checked = ! document.getElementById(id).checked;
		display_checkbox_picture(id);
	}

	function display_checkbox_picture(id){
		if(document.getElementById(id).checked == true){
			document.getElementById("img"+id).src = "img/ck2.gif";
		}else{
			document.getElementById("img"+id).src = "img/uck.gif";
		}
	}

	function change_value(id){
		document.getElementById(id).value =document.getElementById("SELECT"+id).options[document.getElementById("SELECT"+id).selectedIndex].value;
		okp(document.getElementById(id).alt);
	}


	function auto_calc(id){
		document.getElementById("temp"+id).value = document.getElementById(id).value;
		var cellid = document.getElementById(id).alt.replace(/SEM/,"");
		var reg=new RegExp("[\\*|\\/|\\-|\\+|\\(|\\)]", "g");
		tab = document.getElementById(id).value.split(reg);
		var part_num=0;
		while (part_num < tab.length){
			if(!IsNumeric(tab[part_num])){
				document.getElementById(id).value = document.getElementById(id).value.replace(tab[part_num],document.getElementById(""+cellid+tab[part_num]).value);
			}
			part_num++;
		}
		document.getElementById(id).value = eval(document.getElementById(id).value);
	}

	function reveal_calc(id){
		document.getElementById(id).value = document.getElementById("temp"+id).value;
	}

	function IsNumeric(sText){
		var ValidChars = "0123456789.";
		var IsNumber=true;
		var Char;
		for (i = 0; i < sText.length && IsNumber == true; i++){
			Char = sText.charAt(i); 
			if (ValidChars.indexOf(Char) == -1){
				IsNumber = false;
			}
		}
		return IsNumber;
	}

	//Methode de la prochaine version en ajax
	function deleteTableRow(){
		var checkbox = new Array();
		var inpNodes = document.getElementById('miniclic').getElementsByTagName('input');
		for(var i in inpNodes){
			var inp = inpNodes[i];
			if (inp.type == 'checkbox'){
				checkbox.push(inp);
			}
		}
		for (i = checkbox.length -1; i != 0; i--) {
			var inp = checkbox[i];
			if(inp.checked){
				document.getElementById('miniclic').deleteRow(i);
			}
		}
	}



	//Menu contextuel
	var context_elemt = new Array();
	var context_x = 0;
	var context_y = 0;

	function context_position(e){
		context_x = (navigator.appName.substring(0,3) == "Net") ? e.pageX : event.x+document.body.scrollLeft;
		context_y = (navigator.appName.substring(0,3) == "Net") ? e.pageY : event.y+document.body.scrollTop;
	}

	function context_open(e){
		
		if (e.target.tagName.toLowerCase() == "input" && e.target.parentNode.tagName.toLowerCase() == "td" ){
			
			var ligne = ""+e.target.alt.replace("SEM","");
			var colonne = e.target.name.replace(ligne,"");
			var table = document.getElementById("table").value;
			http = createRequestObject();
			http.open('get','engine/miniclic/ajax/php/archive_include.php?table='+table+'&colonne='+colonne+'&ligne='+ligne);
			http.onreadystatechange = createmenu;
			http.send(null);
			document.getElementById("context_box").style.top = context_y+"px";
			document.getElementById("context_box").style.left = context_x+"px";
			document.getElementById("context_ombre").style.top = context_y+4+"px";
			document.getElementById("context_ombre").style.left = context_x+4+"px";
			document.getElementById("context_box").style.visibility = "visible";
			document.getElementById("context_ombre").style.visibility = "visible";
		}
		if (e.target.tagName.toLowerCase() == "input" && e.target.parentNode.tagName.toLowerCase() == "th" ){

			var colonne = e.target.id;
			var where = document.getElementById("where").value;
			where = addslashes(where);
			var where = "";
			var table = document.getElementById("table").value;
			var texte = "<div class='context_menuitems' style='border:0px solid #9D9DA1; background-color:#9fc1ff;'>Menu</div>";
			var context_ombre_txt = '<div class="context_menuitems"><br /></div>';
			texte += '<div class="context_menuitems" onClick="javascript:rechercher_remplacer(\''+colonne+'\',\''+table+'\',\''+where+'\')"  onMouseOver="context_hl(1, this)" onMouseOut="context_hl(0, this)">Remplacer</div>';
			context_ombre_txt += '<div class="context_menuitems"><br /></div>';
			texte += '<div class="context_menuitems" onClick="javascript:rechercher_remplacer(\''+colonne+'\',\''+table+'\')"  onMouseOver="context_hl(1, this)" onMouseOut="context_hl(0, this)">Tri Ascendant</div>';
			context_ombre_txt += '<div class="context_menuitems"><br /></div>';
			texte += '<div class="context_menuitems" onClick="javascript:rechercher_remplacer(\''+colonne+'\',\''+table+'\')"  onMouseOver="context_hl(1, this)" onMouseOut="context_hl(0, this)">Tri Descendant</div>';
			context_ombre_txt += '<div class="context_menuitems"><br /></div>';
			change(texte,"context_box");
			change(context_ombre_txt,"context_ombre");
			document.getElementById("context_box").style.top = context_y+"px";
			document.getElementById("context_box").style.left = context_x+"px";
			document.getElementById("context_ombre").style.top = context_y+4+"px";
			document.getElementById("context_ombre").style.left = context_x+4+"px";
			document.getElementById("context_box").style.visibility = "visible";
			document.getElementById("context_ombre").style.visibility = "visible";
		}
		return false;
	}

	function rechercher_remplacer(colonne,table,where){
		OuvrirPopup('engine/miniclic/ajax/php/remplace_include.php?table='+table+'&colonne='+colonne+'&where='+where,'test', 'resizable=no, location=no, width=300, height=200, menubar=no, status=no, scrollbars=no, menubar=no');
	}

	function addslashes(ch) {
		ch = ch.replace(/\\/g,"\\\\") 
   		ch = ch.replace(/\'/g,"\\'") 
		ch = ch.replace(/\"/g,"\\\"")
		return ch
	}



	function context_close(){
		document.getElementById("context_box").style.top = 0+"px";
		document.getElementById("context_box").style.left = 0+"px";
		document.getElementById("context_ombre").style.top = 0+"px";
		document.getElementById("context_ombre").style.left = 0+"px";
		document.getElementById("context_box").style.visibility = "hidden";
		document.getElementById("context_ombre").style.visibility = "hidden";
	}

	function createmenu(){
		if(http.readyState == 4){
			var response = http.responseText;
			var texte = "<div class='context_menuitems' style='border:0px solid #9D9DA1; background-color:#9fc1ff;'>Archivage</div>";
			var context_ombre_txt = "<br />";
			context_elemt = response.split(":");
			cible = context_elemt[0];
			for(a=1;a<context_elemt.length-1;a++){
				texte += '<div class="context_menuitems" onClick="javascript:archivechange(\''+cible+'\',\''+context_elemt[a]+'\')"  onMouseOver="context_hl(1, this)" onMouseOut="context_hl(0, this)">'+context_elemt[a]+'</div>';
				context_ombre_txt += '<div class="context_menuitems"><br /></div>';
			}
			change(texte,"context_box");
			change(context_ombre_txt,"context_ombre");
		}
	}

	function archivechange(cible,valeur){
		document.getElementById(cible).value = valeur;
		document.getElementById(document.getElementById(cible).alt).value = "ON";
	}

	function context_hl(mode, element){
		if(mode == 1){
			element.style.background = '#316AC5';
			element.style.color = '#ffffff';
		}else{
			element.style.background ='#ffffff';
			element.style.color = '#000000';
		}
	}

	function change(textehtml,box) {
		var rng=document.createRange();
		var elem_calq=document.getElementById(box);
		rng.setStartBefore(elem_calq);
		var html=rng.createContextualFragment(textehtml);
		while (elem_calq.hasChildNodes()){
			elem_calq.removeChild(elem_calq.lastChild);
		}
		elem_calq.appendChild(html);
		
         }

	if(navigator.appName.substring(0,3) == "Net"){
		document.captureEvents(Event.MOUSEMOVE);
	}


	document.write('<div id="context_box" style="z-index:500;position:absolute;width:200px; border:1px solid;  border-color:#fff #bbb #bbb #fff; background-color:#ffffff; font-size:12px; cursor:default; visibility:hidden;" >');
	document.write('Archive');
	document.write('</div>');
	document.write('<div id="context_ombre" style="z-index:400;position:absolute;width:200px; border:1px solid;  border-color:#888888; background-color:#888888; font-size:12px; color:#9D9DA1 ;cursor:default; visibility:hidden;"></div>')
	document.onmousemove=context_position;
	document.oncontextmenu=context_open;
	document.onclick=context_close;

	/*getTrigger();*/
