

// * Ajax *

function loadDynContent(pPage, pNodeName) {}

function ldPage(pPage, pNodeName, fnc) {
    //parameters: {company: 'example', limit: 12} , postBody : $('frm_identification').serialize(true),

    new Ajax.Request(pPage, {
 	 	
 	    method:'post',
 	    
	    onSuccess: function(transport) {
    	
	      var response = transport.responseText || "no response text";
	      setNodeContent(pNodeName, response);
	      
		  if (fnc!=undefined && fnc!=null) eval(fnc);
	      return true;
	    },
	    
	    onFailure: 
		    function(){ alert('Ajax message : something went wrong on loading of the page '+ pPage); return false; }
	});
}


function ldPageParam(pPage, pParam, pNodeName, fnc, replyparam) {
	
    // - pParam : parameters au format hashtable : {company: 'example', limit: 12} 
	// ou en récupérant d'un formulaire :		 $('frm_identification').serialize(true)
	// à passer à l'attribut parameters ou postBody :,
	// - fnc : nom de la fonction à executer après load / null
	// - replyparam : indicateur qui indique qu'il faut passer la réponse du request comme paramètre à la fonction
	//					/ false

    new Ajax.Request(pPage, {
 	 	
 	    method:'post',
 	    encoding:'UTF-8',
 	    parameters: pParam,
	    onSuccess: function(transport) {
    	
	      var response = transport.responseText || "no response text";
		  if (pNodeName!=undefined && pNodeName!=null)
	      	setNodeContent(pNodeName, response);
	      
		  if (fnc!=undefined && fnc!=null && fnc!="") {
			  			  
			  if ( replyparam!=undefined && replyparam!=null && replyparam==true) {
				  //$data=str_replace("'", "\'", $data);
				  response = response.replace(/\'/g, "\\\'");
				  fnc  =fnc+"('"+response+"')"; 
			  }
			  if (fnc.indexOf("(")==-1) fnc += "()"; 
			  eval(fnc);
		  }
	    },
	    
	    onFailure: 
		    function(){ alert('Ajax message : something went wrong on loading of the page '+ pPage); return false; }
	});

}
		

function post(url, values, ptarget, fnc) {
	    
	// Determine Target
	var ltarget=ptarget;
	if (ptarget==undefined || ptarget==null ) 
		ltarget="_blank";
			
	// Prepare iFrame : set onload
	if (ltarget != "_blank") {
 		if (fnc!=null) 
 			setOnload_IFrame(ptarget, fnc);
	}

	// Do the (form) post 
	// transform id,value -> id (=name), name, value, type(=hidden)
	if (url!="") {
		
		// Create & do post
		if (ltarget != "_blank") {
			var frmelements=new Array();
			if ((values!=undefined) && (values!=null)) {
				for (var i=0; i<values.length; i++) {
					var value=values[i];
					frmelements[i]=new formElement( value.name, value.name, value.value, "hidden");
				}
			}
			//console.debug(url);
			var form = crform('form', url, frmelements, ltarget); 
			$(document.body).insert(form); 
			form.submit(); 
			form.remove();
		}

		
		if (ltarget == "_blank") {
	 		//var availHeight=window.screen.availHeight; var availWidth=window.screen.availWidth;
	 		var height="400"; var width="500";
	 		var options="resizable=no,scrollbars=no,width="+width+",height="+height; 
	 		var win=window.open(url, "Login", options);
	 		childswins[childswins.length]=win;
	 	}

	}
}


function setOnload_IFrame(ifr, fnc) {
	
	if ( ifr.substr(0,3)== "ifr" ) {
		if (fnc!=undefined && fnc!=null) //getNodeRef(ifr).onload=fnc;
			$(ifr).observe("load", fnc);
		
	}

}

function crform(pname, url, values, ltarget) {
	
	var form = new Element('form', {method: 'post', action:url, target:ltarget, name:pname });
	if (values!=null) {
		for (var i=0; i<values.length; i++) {
			var item = values[i];
			var attributes=new Object();
			if (item.id!="") attributes.id=item.id;
			attributes.name=item.name;
			attributes.value=item.value;
			attributes.type=item.type;
			
			form.insert(new Element('input', attributes));
		}
	}
	return form;
}

// Forms 
// Create a form in window myversion (Prototype don't seems to manage this)
function createForm(win, name, url) {

	var newform 	= win.document.createElement("form");
	win.document.body.appendChild(newform);
	newform.method = "post";
	newform.name 	= name;
	newform.action	= url;
	
	return newform;

}

// Add element to a form
function createNewFormElement(win, inputForm, elementId, elementName, elementValue) {
	
	var newElement 	= win.document.createElement("input");
	newElement.id	= elementId;
	newElement.name	= elementName;
	newElement.type	= 'hidden';
	newElement.value= elementValue;
	
	inputForm.appendChild(newElement);
	return newElement;
}

// Object form
function creForm(name, url) 			{ this.form = createForm(this.win, name,url);	 }
function addElmToForm(id, name, value)	{ createNewFormElement(this.win, this.form, id, name, value);}
function FormObject(pwin) {
	this.win	= pwin;
	this.form	= null;
	this.create	= creForm;
	this.add 	= addElmToForm;
}



/* DOM specific button management for this appli */

function showbtns(node, yn, auth) {
	
	if (yn && (auth!=undefined && auth!=null && auth==false) ) return;
	
	var btnsid=getBtnref(node, yn);
	visibilityDOMNode(btnsid, yn);
	//showhideDOMNode(btnsid, yn);
}


function visibilityBtns(node, yn, auth) {
	
	
	if (yn==false || (auth==undefined || auth==null || auth==true ) ) {
		var btnsid=getBtnref(node, yn);
		visibilityDOMNode(btnsid, yn);
	}
	
}


function getBtnref(node, yn) {

	var posSep = node.id.indexOf("_");
	var idp1=node.id.substr(0,posSep);
	var idp2=node.id.substr(posSep+1);

	var btnsid=idp1+"btns_"+idp2;
	return btnsid;
}

// Combo

function filterComboList(plist, pval) {

	var node=getNodeRef(plist);
	var lines=node.getElementsByTagName("div");
	var showhide="block";
	var id="";
	for (var i=0; i<lines.length; i++) {
		showhide="none";
		id=lines[i].id.substring(3);
		// Contains 
		if (pval=="") 
			showhide="block"
		else if ( id.toUpperCase().indexOf(pval.toUpperCase())>=0) 
			showhide="block";
		// Starting with
		//if (id.substring(0, pval.length).toUpperCase()==pval.toUpperCase() ) showhide="block";
		lines[i].style.display=showhide;
	}
}

function toggleCombo(nId, openclose) {
	
	var vis=false;
	if (openclose!=undefined && openclose!=null) {
		vis=openclose;
	}
	else
		vis = (getNodeRef(nId+"listframe").style.display=="none");
	
	showhideDOMNode(nId+"listframe", vis);
	if (vis==true) 
		filterComboList(nId+"list", getNodeValue(nId+"sel"));
	
	toggleComboBtn("combo"+nId+"Button", vis);
}



function toggleComboBtn(pnode, openclose) {
	
	var node=getNodeRef(pnode);
	var open=false;
	if (openclose!=undefined && openclose!=null) {
		open=openclose;
	}
	else if ( node.src.indexOf("combo.")>=0 ) open=true;
	
	node.src="./images/" + ((open==true) ? "reduce.gif" : "combo.jpg") ;

}

function keyeditem(pid, plabel) {
	this.id=pid;
	this.label=plabel;
}


/* Fills node pid+"list" with list (les items), 
 * fnc et fncparam : la fonction à appeler sur un clic sur un item. 
 */
function fillComboFiltered(pid, list, fnc, fncparam, refreshfnc) {
	
	//pid +"_Id"
	var content="";
	var id="";
	var label="";
	var temp = document.createElement("div");
	for (var i=0; i<list.length; i++) {
		id 		= list[i].id;
		label  	= list[i].label;
		
		//label=label.unescapeHTML(); //Prototype ne fonctionne pas bien ne fait que les symboles & < > 
		// html= html.escapeHTML();

		// Unescape
		temp.innerHTML = label;
		label = temp.childNodes[0].nodeValue;
		
		label = label.toUpperCase();
		// escape
		label=htmlentities(label,"ENT_QUOTES");
		
		//label  = label.replace(/\'/g, "\\\'");
		
		content+="<div id='ar_"+id+"' style='margin:0px; padding:0px 3px 0px 13px; text-indent:-10px; color:#111; cursor:pointer' onmouseover='this.style.color=\"#00a\";' onmouseout='this.style.color=\"#111\";'";
		content+=" onmouseup='toggleCombo(\""+pid+"\", false); "+
		"setNodeValue(\""+pid+"_Id\",\"" +id +"\"); "+
		"setNodeValue(\""+pid+"sel\",\"" +label +"\");"+
		fnc+"(\""+id+"\",\""+fncparam+"\")'";
		content+=">";
		
		// refreshbtn
		if (i==0) {
			if (refreshfnc!=undefined && refreshfnc!=null)
				content+="<img src='./images/refresh.jpg' style='float:right; height:20px; width:18px; margin:0px; cursor:pointer' onmouseup='"+refreshfnc+"' />";
		}
		
		content+=label+"</div>";
	}
	setNodeContent(pid+"list", content);
	// clean up
	temp.removeChild(temp.firstChild);
	//temp.parentNode.removeChild(temp); //document.documentElement.removeChild(temp)

}


function fillCombo(nId, list) {
	
	var content="";
	for (var i=0; i<list.length; i++) {
		content +="<option value='"+list[i]+"'>"+list[i]+"</option>";
	}
	setNodeContent(nid, content); 

}

function nav_ie() {
	return (navigator.appVersion.match(/\bMSIE\b/)) ? true : false ;
}


function htmlentities (string, quote_style, charset, double_encode) {
    // Convert all applicable characters to HTML entities  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/htmlentities    
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +   improved by: Rafal Kukawski (http://blog.kukawski.pl)
    // +   improved by: Dj (http://phpjs.org/functions/htmlentities:425#comment_134018)    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'    
	var hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style),  symbol = '';
    string = string == null ? '' : string + '';
 
    if (!hash_map) {        
    	return false;
    }
    
    if (quote_style && quote_style === 'ENT_QUOTES') {
        hash_map["'"] = '&#039;';    }
    
    if (!!double_encode || double_encode == null) {
        for (symbol in hash_map) {
            if (hash_map.hasOwnProperty(symbol)) {               
            	string = string.split(symbol).join(hash_map[symbol]);
            }
        }
    } else {
        string = string.replace(/([\s\S]*?)(&(?:#\d+|#x[\da-f]+|[a-zA-Z][\da-z]*);|$)/g, function (ignore, text, entity) {            for (symbol in hash_map) {
                if (hash_map.hasOwnProperty(symbol)) {
                    text = text.split(symbol).join(hash_map[symbol]);
                }
            }            
            return text + entity;
        });
    }
    return string;
}

function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/get_html_translation_table    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    var entities = {},
        hash_map = {},        decimal;
    var constMappingTable = {},
        constMappingQuoteStyle = {};
    var useTable = {},
        useQuoteStyle = {}; 
    // Translate arguments
    constMappingTable[0] = 'HTML_SPECIALCHARS';
    constMappingTable[1] = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
 
    useTable = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT'; 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: " + useTable + ' not supported');
        // return false;
    } 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    } 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';
  
    // ascii decimals to real symbols
    for (decimal in entities) {
        if (entities.hasOwnProperty(decimal)) {
            hash_map[String.fromCharCode(decimal)] = entities[decimal];        }
    }
 
    return hash_map;
}

function unescapeHTML(pData) {
	var temp = document.createElement("div");
	temp.innerHTML = pData;
	var text = temp.childNodes[0].nodeValue;
	temp.removeChild(temp.firstChild);
	return text;
}


