/*
* Author		:	VP
* Version		:	v14
* date			:	
* History		:		
							
						
						- 111206 v14 : modification of => the <tr> exception on these func :
										switch_display_all(class);  
										switch_display_obj(id);
										hide_obj(id);
										display_obj(id) 
														
						- 111127 v14 :
								 whichBrs();
								 switch_display_all();
								 hide_all_obj();
								 add of htmlentities();
								 add of getElementsByClassName();
								 Mod of debug();
								
						-111018 v14 : 
								 add addslashes(str)
								 add stripslashes(str)
								 add nl2br(str, is_xhtml)
								 is_string
								
						-111005 v13 : 
								 Add of hiText()
						- 110724 v12 : 
								 name modification of f_display_obj and f_hide_obj functions (weren't used anywhere). Now display_obj and hide_obj
								 Add of switch_display_obj(id) function
						- 091128
								Add the function scan_for_class();
						- 090724
								Add the scanObject functions.
*/
//--------------------------------------------------------------------
// THE DEBUGGER
function debug(x){
	document.getElementById('debug').innerHTML = document.getElementById('debug').innerHTML+ "<br>"+ x;
	document.getElementById('debug').style.display='block';
}
//--------------------------------------------------------------------
// Returns the browser
// CAUTION : this function is called at it's end
function whichBrs() {
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("opera") != -1) return 'Opera';
	if (agt.indexOf("staroffice") != -1) return 'Star Office';
	if (agt.indexOf("webtv") != -1) return 'WebTV';
	if (agt.indexOf("beonex") != -1) return 'Beonex';
	if (agt.indexOf("chimera") != -1) return 'Chimera';
	if (agt.indexOf("netpositive") != -1) return 'NetPositive';
	if (agt.indexOf("phoenix") != -1) return 'Phoenix';
	if (agt.indexOf("firefox") != -1) return 'Firefox';
	if (agt.indexOf("safari") != -1) return 'Safari';
	if (agt.indexOf("skipstone") != -1) return 'SkipStone';
	if (agt.indexOf("msie") != -1) return 'IE';
	if (agt.indexOf("netscape") != -1) return 'Netscape';
	if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
	if (agt.indexOf('\/') != -1) {
	if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
	return navigator.userAgent.substr(0,agt.indexOf('\/'));}
	else return 'Netscape';} else if (agt.indexOf(' ') != -1)
	return navigator.userAgent.substr(0,agt.indexOf(' '));
	else return navigator.userAgent;
}
_browserName = whichBrs();


//--------------------------------------------------------------------
// use to display all the properties of an object according to its id. 
// VAR		: id:String = the id of an object
// RETURNS : the function scanObject(o);
function scanObjectById(id){
	var o = document.getElementById(id);
	return scanObject(o);
}
// use to display all the properties of an object
// VAR		: o:Javascript Object = a js object rererence
function scanObject(o){
	var res;
	res = "<ul>";
	for(x in o){
		res += "<li style='margin:0px'><span style='color:#f00'>"+x+" : </span>"+o[x]+"</li>";
	}
	res += "</ul>";
	debug (res);
}
//--------------------------------------------------------------------
// use to display one property of an object
function prop_object(id, prop){
	var o = document.getElementById(id);
	var res;
	res = "<span style='color:#f00'>"+prop+" : </span>"+o[prop];
	debug (res);
}
//--------------------------------------------------------------------
// use to have a cursor change on href
function func(){ }
//--------------------------------------------------------------------
// simply reload the page. problem if href ends with '#'
function reload_page(){
	var url;
	var href = document.location.href;
	if (href.substr(-1, 1) == "#"){ url = href.substr(0, -1) }else{ url = href; } 
	document.location = url;
}
//--------------------------------------------------------------------
// simply go to the desired page.
function go2page(page){
	document.location = page;
}
//--------------------------------------------------------------------
// simply go to the desired page.
function go2pageget(page, var_name, var_value){
	document.location = page+"?"+var_name+"="+var_value;
}
//--------------------------------------------------------------------
// simply go to the desired page.
function openBlankPage(page){
	window.open(page);
	
}

//--------------------------------------------------------------------
// simply return true or false if the var (send as STRING) is set or not.
function isset(varname){
	if(typeof( window[ varname ] ) != 'undefined'){
		return true;
	}else{
		return false;
	}
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
/* htmlentities php like function
*/
function htmlentities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
/* stripslashes php like fucntion
*/
function stripslashes (str) {
    return (str + '').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
        case '\\':
            return '\\';
        case '0':
            return '\u0000';
        case '':
            return '';
        default:
            return n1;
        }
    });
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
/* addslashes php like fucntion
*/
function addslashes (str) {
	return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}

//-------------------------------------------------------------------
//-------------------------------------------------------------------
/* nl2br php like fucntion
*/
function nl2br (str, is_xhtml) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Atli ήσr
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Maximusya
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');
    // *     returns 1: 'Kevin<br />\nvan<br />\nZonneveld'
    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
    // *     returns 3: '<br />\nOne<br />\nTwo<br />\n<br />\nThree<br />\n'

    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';

    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// emule the php trim function
function trim(str){
	return str.replace(/^\s+|\s+$/g, '') ;
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// emule the php is_string function
function is_string(s){
	return typeof(s)=='string';
}
//--------------------------------------------------------------------
// cursor = pointer
function cursor_in(o){
	o.style.cursor = 'pointer';
}
//--------------------------------------------------------------------
// cursor = auto
function cursor_out(o){
	o.style.cursor = 'auto';
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// for the table tr list
function tr_over(tr){
	var l = tr.childNodes;
	for(x in l){
		td = l[x];
		if (td.nodeName=="TD"){
			td.style.backgroundImage="url('images/main/hi50.png')";
		}
	}
}
//--------------------------------------------------------------------
function tr_out(tr){
	var l = tr.childNodes;
	for(x in l){
		td = l[x];
		if (td.nodeName=="TD"){
			td.style.backgroundImage="none";
		}
	}
}
//--------------------------------------------------------------------
// Put a zero before a Number if it's < 10
function put_zero(num){
	if (num<10) num = "0"+num;
	return num;
}

//--------------------------------------------------------------------
// display a hidden onject
function display_obj(id){
	var o = document.getElementById(id);
	var display = o.tagName == "TR" ? "table-row" : "block";
	o.style.display = display;
}
//--------------------------------------------------------------------
// display a hidden onject
function hide_obj(id){
	var o = document.getElementById(id);
	o.style.display = 'none';
}
//--------------------------------------------------------------------
// display a hidden onject
function switch_display_obj(id){
	var o = document.getElementById(id);
	var display = o.tagName == "TR" ? "table-row" : "block";
	var disp = o.style.display == 'none' ? display : "none";
	o.style.display = disp;
}
//--------------------------------------------------------------------
// PURPOSE	:	switch the display of all element with the selected className according to the display of the LAST element
function switch_display_all(class_name){
	a=new Array();
	a = getElementsByClassName(document, class_name);
	var offon = "";
	for (x in a){
		if (offon == "") offon = a[a.length-1].style.display;
		var display = a[a.length-1].tagName == "TR" ? "table-row" : "block";
		if (a[x].style != undefined)  a[x].style.display = offon == "none" ? display : "none";
	}
}

//--------------------------------------------------------------------
// PURPOSE	:	
function hide_all(class_name){
	a=new Array();
	a = getElementsByClassName(document, class_name);
	for (x in a){
		if (a[x].style != undefined) a[x].style.display = "none";
	}
}
//--------------------------------------------------------------------
function display_popup(openclose){
	
	if (openclose=="open"){
		var h = document.body.scrollHeight+"px";
	}else{
		var h = "0%";
	}
	document.getElementById('popup_mask').style.height = h;
	

	if (openclose=="close"){
		document.getElementById('popup').innerHTML = "";
	}
		
}


function scrollTop (){
	body=document.body
		d=document.documentElement
		if (body && body.scrollTop) return body.scrollTop
		if (d && d.scrollTop) return d.scrollTop
		if (window.pageYOffset) return window.pageYOffset
		return 0
}


function wait_ajax(){
	// nothing for the moment
	
	
	/*
	display_popup('open');
	var popup = document.getElementById('popup');
	popup.innerHTML = "<div style='width:500px; margin:auto; margin-top:300px;'><h1>Veuillez patienter</h1></div>";
	*/
}

// function from rico.
// return a list of all the elements with the desire tag name and class name
document.getElementsByTagAndClassName = function(tagName, className) {
  if ( tagName == null )
     tagName = '*';

  var children = document.getElementsByTagName(tagName) || document.all;
  var elements = new Array();

  if ( className == null )
    return children;

  for (var i = 0; i < children.length; i++) {
    var child = children[i];
    var classNames = child.className.split(' ');
    for (var j = 0; j < classNames.length; j++) {
      if (classNames[j] == className) {
        elements.push(child);
        break;
      }
    }
  }

  return elements;
}


// change the display css of desired DOM objects
function f_display_list_tab(name, display){
//	alert(display);
	var lt = document.getElementsByTagAndClassName('td',  'list_tab_'+name);
	var display_value;
	if (display){ display_value = 'table-cell'; }else{ display_value = 'none'; }
	for(var x in lt){
		lt[x].style.display=display_value;
	}
	
}

// info on : http://www.quirksmode.org/dom/getElementsByTagNames.html
function getElementsByTagNames(list,obj) {
	if (!obj) var obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}


//-------------------------------------------------------------------
//-------------------------------------------------------------------



// Verify the mail validity

function verif_mail(email){
		var arobase=email.indexOf("@");
		var point= email.lastIndexOf(".");
		if((arobase < 3)||(point + 2 > email.length) ||(point < arobase+3)){
			return false;
		}else{
			return true;
		}
}

//-------------------------------------------------------------------
//-------------------------------------------------------------------


function isDateValid(saisie, year_on_2_numbers) {
	if (saisie == "") return false;
	saisie = (saisie).split("/");
	if ((saisie.length != 3) || isNaN(parseInt(saisie[0])) || isNaN(parseInt(saisie[1])) || isNaN(parseInt(saisie[2]))) return false;
	var laDate = new Date(eval(saisie[2]),eval(saisie[1])-1,eval(saisie[0]));
	if (year_on_2_numbers){
		var annee = saisie[2];
		
		return ((laDate.getDate() == eval(saisie[0])) && (laDate.getMonth() == eval(saisie[1])-1) && (annee.length == 2));
	}else{
		var annee = laDate.getYear();
		if ((Math.abs(annee)+"").length < 4) annee = annee + 1900;
		return ((laDate.getDate() == eval(saisie[0])) && (laDate.getMonth() == eval(saisie[1])-1) && (annee == eval(saisie[2])));
	}
}

//-------------------------------------------------------------------
//-------------------------------------------------------------------
// secure some caracters
//-------------------------------------------------------------------
//-------------------------------------------------------------------
function secure_string_for_ajax(str){
	
	var reg=new RegExp("(&)", "g");
	str = str.replace(reg,'|#and#|');
	
	var reg=new RegExp("(\\+)", "g");
	str = str.replace(reg,'|#plus#|');

	
	return str;
}



//-------------------------------------------------------------------
//-------------------------------------------------------------------
// VP_SCAN :  how to act on DOM obj according to their class name
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//--------------------------------
function vp_button_hi(o){o.style.cursor="pointer"; o.className="button_hover";}
function vp_button_norm(o){o.style.cursor="auto"; o.className="button";}
//--------------------------------
function vp_button_reactions(o){
	o.onmouseover = function(){ vp_button_hi(o); }
	o.onmouseout = function(){ vp_button_norm(o); }
}
//--------------------------------
// Scan the whole body searching objects with class 'vp_button'
// and apply the function button_reaction to them
function vp_scan_page(o){
	var atmp;
	var c;
	var l = o.childNodes;
	var x;
	var y;
	for(x in l){
		if (l[x] && l[x].className != undefined){
			//debug( l[x].className+" / "+l[x].id);
			c = l[x].className;
			atmp = c.split(' ');
			for (y in atmp){
				if(atmp[y] == "button"){
					vp_button_reactions(l[x]);
				}
			}
			
			if (l[x].childNodes.length > 0) vp_scan_page(l[x]);
		}
	}
}
//window.onload=function(){ vp_scan_page(document.body); }

//--------------------------------
//--------------------------------
//--------------------------------
// Scan an element searching objects with wanted className
/*
USAGE : 
	var elements = getElementsByClassName(document, className),
		n = elements.length;
	for (var i = 0; i < n; i++) {
		var e = elements[i];
	}

*/
function getElementsByClassName(node,classname) {
  if (node.getElementsByClassName) { // use native implementation if available
    return node.getElementsByClassName(classname);
  } else {
    return (function getElementsByClass(searchClass,node) {
        if ( node == null )
          node = document;
        var classElements = [],
            els = node.getElementsByTagName("*"),
            elsLen = els.length,
            pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;

        for (i = 0, j = 0; i < elsLen; i++) {
          if ( pattern.test(els[i].className) ) {
              classElements[j] = els[i];
              j++;
          }
        }
        return classElements;
    })(classname, node);
  }
}


//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Open_popup
/*
							- $jumi[0] = the popup src file
							- $jumi[1] = the width of the iframe
							- $jumi[2] = the height of the iframe
							- $jumi[3] = "yes" OR "no" for the scrollbars
*/
//-------------------------------------------------------------------
//-------------------------------------------------------------------
function open_popup(url, title, width, height, toolbar, menubar, scrollbars, resizable){
	newwindow=window.open (url, title, 'width='+width+', height='+height+', toolbar='+toolbar+', menubar='+menubar+', scrollbars='+scrollbars+', resizable='+resizable+', location=no, directories=no, status=no');

	
}



//-------------------------------------------------------------------
//-------------------------------------------------------------------
/* Highlight the given text in the given DOM element
*/
function hiText(termid, element_id) {

	var tempinnerHTML = document.getElementById(element_id).innerHTML;
	var regex = new RegExp(termid+"(?=[^>]*<)","ig");
	document.getElementById(element_id).innerHTML = tempinnerHTML.replace(regex,'<span class="highlighted">'+termid+'</span>');
}
/*
<?php // We launch a js search term highlight if the search_string is not empty
if ($search_string != "") { ?> hiText('<?php echo $search_string;?>', 'result_table'); <?php } ?>
*/
