/**
* 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 5.0.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;
}

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();
}

function fire_workflow(fire,key,col){
	document.getElementById('action').value=fire;
	document.getElementById('wf_key').value=key;
	document.getElementById('wf_col').value=col;
	document.getElementById('form_header').submit();
}

function fire_link(apps,module,cond){
	document.location="main.php?application="+application+"&page="+module+"&"+cond;
}


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 tab_pressed(event){
	if(event.shiftKey==1){
	if(event.keyCode == 39){
		var object = event.target.parentNode.parentNode.parentNode;
		var ind = event.target.parentNode.parentNode.cellIndex;
		oEvent = document.createEvent("MouseEvents");
		var trgt = object.cells[ind+1];
		oEvent.initMouseEvent("click",    // le type d'evenement souris
  		true,       // est-ce que l'evenement doit se propager (bubbling)?
  		true,       // est-ce que le défaut pour cet evenement peut être annulé?
  		window,     // l' 'AbstractView' pour cet evenement
  		0,          // details -- Pour les evenements click, le nombre de clicks
  		0,          // screenX
  		0,          // screenY
  		0,          // clientX
  		0,          // clientY
  		false,      // est-ce que la touche Ctrl est pressée?
  		false,      // est-ce que la touche Alt est pressée?
  		false,      // est-ce que la touche Shift est pressée?
  		false,      // est-ce que la touche Meta est pressée?
  		0,          // quel est le bouton préssé
  		null      // l'élement source de cet evenement
		);
		event.target.blur();
		trgt.dispatchEvent(oEvent);
	}
	if(event.keyCode == 37){
		var object = event.target.parentNode.parentNode.parentNode;
		var ind = event.target.parentNode.parentNode.cellIndex;
		oEvent = document.createEvent("MouseEvents");
		var trgt = object.cells[ind-1];
		oEvent.initMouseEvent("click",    // le type d'evenement souris
  		true,       // est-ce que l'evenement doit se propager (bubbling)?
  		true,       // est-ce que le défaut pour cet evenement peut être annulé?
  		window,     // l' 'AbstractView' pour cet evenement
  		0,          // details -- Pour les evenements click, le nombre de clicks
  		0,          // screenX
  		0,          // screenY
  		0,          // clientX
  		0,          // clientY
  		false,      // est-ce que la touche Ctrl est pressée?
  		false,      // est-ce que la touche Alt est pressée?
  		false,      // est-ce que la touche Shift est pressée?
  		false,      // est-ce que la touche Meta est pressée?
  		0,          // quel est le bouton préssé
  		null      // l'élement source de cet evenement
		);
		event.target.blur();
		trgt.dispatchEvent(oEvent);
	}
	if(event.keyCode == 38){
		var object = event.target.parentNode.parentNode.parentNode;
		var cell_ind = event.target.parentNode.parentNode.cellIndex;
		var row_ind = object.rowIndex;
		var trgt = object.parentNode.rows[row_ind-2].cells[cell_ind];
		oEvent = document.createEvent("MouseEvents");
		oEvent.initMouseEvent("click",    // le type d'evenement souris
  		true,       // est-ce que l'evenement doit se propager (bubbling)?
  		true,       // est-ce que le défaut pour cet evenement peut être annulé?
  		window,     // l' 'AbstractView' pour cet evenement
  		0,          // details -- Pour les evenements click, le nombre de clicks
  		0,          // screenX
  		0,          // screenY
  		0,          // clientX
  		0,          // clientY
  		false,      // est-ce que la touche Ctrl est pressée?
  		false,      // est-ce que la touche Alt est pressée?
  		false,      // est-ce que la touche Shift est pressée?
  		false,      // est-ce que la touche Meta est pressée?
  		0,          // quel est le bouton préssé
  		null      // l'élement source de cet evenement
		);
		event.target.blur();
		trgt.dispatchEvent(oEvent);
	}
	if(event.keyCode == 40){
		var object = event.target.parentNode.parentNode.parentNode;
		var cell_ind = event.target.parentNode.parentNode.cellIndex;
		var row_ind = object.rowIndex;
		var trgt = object.parentNode.rows[row_ind].cells[cell_ind];
		oEvent = document.createEvent("MouseEvents");
		oEvent.initMouseEvent("click",    // le type d'evenement souris
  		true,       // est-ce que l'evenement doit se propager (bubbling)?
  		true,       // est-ce que le défaut pour cet evenement peut être annulé?
  		window,     // l' 'AbstractView' pour cet evenement
  		0,          // details -- Pour les evenements click, le nombre de clicks
  		0,          // screenX
  		0,          // screenY
  		0,          // clientX
  		0,          // clientY
  		false,      // est-ce que la touche Ctrl est pressée?
  		false,      // est-ce que la touche Alt est pressée?
  		false,      // est-ce que la touche Shift est pressée?
  		false,      // est-ce que la touche Meta est pressée?
  		0,          // quel est le bouton préssé
  		null      // l'élement source de cet evenement
		);
		event.target.blur();
		trgt.dispatchEvent(oEvent);
	}
	}
}


function focusin_input(event){
	var object = event.target;
	if(object.tagName == "TD"){
		object = object.childNodes[1];
	}
	if(object.getAttribute('title') == "INPUT" || object.getAttribute('title') == "CALLTO"){
		var thetext = thetext = object.innerHTML;
		if(thetext != ""){
			object.removeChild(object.lastChild);
		}else{
			thetext = "";
		}
		thetext = unescape(thetext);		
		var inp = document.createElement("input");
		inp.setAttribute("id", "moninput");
		inp.setAttribute("value", ""+thetext);
		inp.setAttribute("onblur", "javascript:focusout_input(event);");
		inp.setAttribute("style", "width:100%");
		
		object.appendChild(inp);
		inp.focus();
		inp.click();
		inp.value = inp.value.replace("&amp;","&");
	}
	if(object.getAttribute('type') == "COMPLETION"){
		var thetext = thetext = object.innerHTML;
		if(thetext != ""){
			object.removeChild(object.lastChild);
		}else{
			thetext = "";
		}
		var inp = document.createElement("input");
		inp.setAttribute("id", "completion_text");

		inp.setAttribute("value", ""+thetext);
		inp.setAttribute("onkeyup", "javascript:recup_datas(event);");
		inp.setAttribute("style", "width:100%;");
		object.appendChild(inp);
		var oparent = inp.parentNode;
		var id = ""+oparent.parentNode.parentNode.id;
		var colonne = (""+oparent.parentNode.id).replace(id,"");
		inp.setAttribute("name", ""+id+";"+colonne);
		inp.focus();
		inp.click();
		inp.value = inp.value.replace("&amp;","&");
		document.getElementById("completion").style.left = event.pageX+"px";
		document.getElementById("completion").style.top = event.pageY+"px";
	}
	
}


function focusout_input(event){
	var object = event.target;
	var oparent = object.parentNode;
	var otext = ""+object.value;
	oparent.removeChild(object);
	var t = document.createTextNode(otext);
	oparent.appendChild(t);
	var module_id = document.getElementById('module_id').value;
	var object_id = ""+oparent.parentNode.parentNode.id.replace("KEY","");;
	var colonne = (""+oparent.parentNode.id).replace(object_id,"");
	var val = otext;
	update_database(module_id,object_id,colonne,val);
}

var http;
function update_database(module_id,object_id,colonne,val){
	http = createRequestObject();
	val = escape(val);
	http.open('get', 'engine/miniclic/ajax/php/update_include.php?module_id='+module_id+'&colonne='+colonne+'&object_id='+object_id+'&value='+val);
	http.onreadystatechange = check_update;
	http.send(null);
}

function check_update(){
	if(http.readyState == 4){
		var response = http.responseText;
		if(response == "KO"){
			alert("Erreur lors de la maj de la cellule");
		}
	}
}



function recup_datas(e) {
 	var sel = document.getElementById("completion_select") ;
 	var nb_el = sel.options.length ;
 	var selIndex = sel.selectedIndex ;
	var minimum_caractere = 1;
	var module_id = document.getElementById('module_id').value;
	var object = e.target;
	var oparent = object.parentNode;
	var id = ""+oparent.parentNode.parentNode.id;
	var colonne = (""+oparent.parentNode.id).replace(id,"");

	http = createRequestObject();
	if (!document.getElementById("completion_text").value){
		sel.style.display = 'none';
	}else{
 		val = document.getElementById("completion_text").value ;
 		if (val.length >= minimum_caractere) {
 			http.open("GET", "engine/miniclic/ajax/php/datas_include.php?module_id="+module_id+"&colonne="+colonne+"&val="+escape(val), true);
 			http.onreadystatechange = handleHttpResponse_recup_datas;
 			http.send(null);
 		}
 	}
 }

function handleHttpResponse_recup_datas(){
 	if (http.readyState == 4){
		datas = eval('(' + http.responseText + ')');
 		var sel = document.getElementById("completion_select") ;
 		sel.attributes['size'].value = datas.length;
 		// on vide le select
 		while(sel.options.length > 0)
 			sel.options[0] = null
 		for(i=0 ; i<datas.length ; i++){
			var tmp_datas = datas[i].split(";");
 			sel.options[sel.options.length] = new Option(tmp_datas[0],tmp_datas[1]);
		}
 		if (sel.options.length) {
 			sel.selectedIndex = 0 ; // on selection le premier element de la liste
			document.getElementById("completion").style.visibility = "visible";
 			sel.style.display = 'block';
		}else{
			sel.style.display = 'none';
		}
 	}
}

 function recup_datas_click() {
 	var sel = document.getElementById("completion_select") ;
	var res = getSelected(sel);
	var str = "";
	var ids = "";
	for (var intLoop=0; intLoop < res.length; intLoop++) {
		str += res[intLoop].text+" ";
		ids += res[intLoop].value+";";
	}
 	document.getElementById("completion_text").value = str;
	var tmp = document.getElementById("completion_text").name.split(";");
	var id = tmp[0];
	var colonne = tmp[1];
	var table = document.getElementById('module_id').value;
	update_database(table,id,colonne,ids);
 	sel.style.display = 'none';
	document.getElementById("completion").style.visibility = "hidden";
 }


function getSelected(opt) {
      var selected = new Array();
      var index = 0;
      for (var intLoop=0; intLoop < opt.length; intLoop++) {
         if (opt[intLoop].selected) {
            index = selected.length;
		selected[index] = new Object;
            selected[index].value = opt[intLoop].value;
            selected[index].text = opt[intLoop].text;
         }
      }
      return selected;
   }


var current_id;
	

function generate_pdf(){
	var inpNodes = document.getElementById('miniclic').getElementsByTagName('input');
	var result = "";
	for(var i in inpNodes){
		var inp = inpNodes[i];
		if (inp.type == 'checkbox'){
			if(inp.checked){
				if(inp.id != "allcheck" && inp.id != "rr_str"){
					result += inp.id.replace(/CK/,"")+";";	
				}
			}
		}
	}
	document.location = document.getElementById("PDFS").options[document.getElementById("PDFS").selectedIndex].value + "?values="+result;
}


//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.parentNode.tagName.toLowerCase() == "td" ){
			var object = e.target;
			var object_id = ""+object.parentNode.parentNode.parentNode.id;
			var colonne = e.target.parentNode.parentNode.id.replace(ligne,"");
			var module_id = document.getElementById("module_id").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 = "";
			var module_id = document.getElementById("module_id").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+'\')"  onMouseOver="context_hl(1, this)" onMouseOut="context_hl(0, this)">Rechercher/Remplacer</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){
		document.getElementById("remplacer").style.visibility = "visible";
		document.getElementById("remplacer").style.visibility = "visible";
		document.getElementById("rr_colonne").value = colonne;
	}

	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){
		
	}

	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);
	}

	function positionne(p_id, p_posX, p_pos_Y){
		document.getElementById(p_id).style.left = p_posX;
		document.getElementById(p_id).style.top = p_pos_Y;
	}

	function getPositionCurseur(e){
		//ie
		if(document.all){
			curX = event.clientX;
			curY = event.clientY;
		}
	
		//netscape 4
		if(document.layers){
			curX = e.pageX;
			curY = e.pageY;
		}
	
		//mozilla
		if(document.getElementById){
			curX = e.clientX;
			curY = e.clientY;
		}	
	}

	var ecartX;
	var ecartY;
	var objectToDrag;

	function beginDrag(p_obj,e){
		isDragging = true;
		objectToDrag = p_obj;
		getPositionCurseur(e);
		ecartX = curX - parseInt(objectToDrag.style.left);
		ecartY = curY - parseInt(objectToDrag.style.top);
	}

	function drag(e){
		var newPosX;
		var newPosY;
		if(isDragging == true){
			getPositionCurseur(e);
			newPosX = curX - ecartX;
			newPosY = curY - ecartY;
			objectToDrag.style.left = newPosX + 'px';
			objectToDrag.style.top = newPosY + 'px';
		}
	}

	function endDrag(){
		isDragging = false;
	}


	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;
