if(!window.console){
	window.console={};
	window.console.debug=function(){};
}
//add a replaceAl function
String.prototype.replaceAll=function(s1, s2) {
	return this.replace(new RegExp(s1,"g"), s2);
}
String.prototype.startsWith=function(str){
	return this.substring(0,str.length)==str;
}
String.prototype.count=function(s1) { 
	return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}

String.prototype.trim = function(){return
	(this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))}

String.prototype.contains = function(str){
	return this.indexOf(str)>0}

String.prototype.reLast=function(count){
	return this.slice(0, -count);
}
//utils functions

function innerText(node){
	if(document.all){
		return node.innerText;
	} else{
		return node.textContent;
	}
}
function getSimpleStyle(style){
	var res="";
	res+="color:"+style.color;
	res+=";top:"+style.top;
	res+=";left:"+style.left;
	res+=";font-weight:"+style.fontWeight;
	res+=";font-size:"+style.fontSize;
	return res;
}
function disableSelection(target){
	if (typeof target.onselectstart!="undefined") //IE route
		target.onselectstart=function(){return false}
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
		target.style.MozUserSelect="none"
	else //All other route (ie: Opera)
		target.onmousedown=function(){return false}
	target.style.cursor = "default"
}
function includeInDiv(divName,url){
	var div=e(divName);
	ajax(url,null, true,function(result){
		alert(result);
		div.innerHTML=result;	
	});	
}


function noSessionTimeout(page){
	var callF=function(){
		ajax(page,null,false,function(res){
			setTimeout(callF,60000);
		});
	}
	setTimeout(callF,60000);
}

function replaceAll(argvalue, x, y) {

	  if ((x == y) || (parseInt(y.indexOf(x)) > -1)) {
	    errmessage = "replace function error: \n";
	    errmessage += "Second argument and third argument could be the same ";
	    errmessage += "or third argument contains second argument.\n";
	    errmessage += "This will create an infinite loop as it's replaced globally.";
	    alert(errmessage);
	    return false;
	  }
	    
	  while (argvalue.indexOf(x) != -1) {
	    var leading = argvalue.substring(0, argvalue.indexOf(x));
	    var trailing = argvalue.substring(argvalue.indexOf(x) + x.length, 
		argvalue.length);
	    argvalue = leading + y + trailing;
	  }

	  return argvalue;

	}

var ajaxqueue=[];
function ajax(url, parameters,ispost,callBack,async) {
	var ajaxele={};
	ajaxele.url=url;
	ajaxele.parameters=parameters;
	ajaxele.ispost=ispost;
	ajaxele.callBack=callBack;
	ajaxele.async=async;
	ajaxqueue.push(ajaxele);
	//console.debug(ajaxqueue.length);
	if(ajaxqueue.length==1)
		processQueue();
	
}


function ajax2(url,callBack){
	ajax(url,null,false,callBack,true);
}
function processQueue(){
	if(ajaxqueue.length==0){
		return;
	}
	var next=ajaxqueue.shift();
	ajaxOne(next.url,next.parameters,next.ispost,next.callBack,next.async);
}

var lastscript=[];
function ajaxXsite(url,callback,withquery){
	var idcall=""+Math.random();	
	idcall="G"+(idcall.substring(2));
	window[idcall]=function(res){callback(res);};
		
	//var query=G_makeurl(service,method,args,idcall);
	//console.debug(query);
	if(withquery==true)
		url+="?function="+idcall;
	else
		url+="&function="+idcall;
	//console.debug(url);
	var scr=include(url);
	scr.id="sc"+idcall;
	lastscript.push(scr.id);
	if(lastscript.length>6){
		var toremove=lastscript.shift();
		removeById(toremove);
	}
	
}






function ajaxOne(url, parameters,ispost,callBack,async) {
	
	  if(async==null)
			async=true;
	 	  
      var http_request = null;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
            	//alert(e);
            }
         }
      }
      if (http_request==null) {
         //alert('Cannot create XMLHTTP instance');
         return null;
      }
      var process=function() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;            
			
			
			if(callBack!=null){
				//eval('var obj='+result);
				callBack(result);
				processQueue();
			}
         } else {
            //alert('There was a problem with the request.');
         }
      }
   }
      
      http_request.onreadystatechange = process;
      if(!ispost){
          if(parameters!=null)
        	  url=url +"?"+ parameters;
	      http_request.open('GET', url, async);
	      
	      http_request.send(null);
      }else{
    	 //alert("post");
    	 
 		http_request.open('POST', url, async);
 		//Send the proper header infomation along with the request
 		
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
		var parLen=0;
		if(parameters!=null)
			parLen=parameters.length;
		
		http_request.setRequestHeader("Content-length", parLen);
		http_request.setRequestHeader("Connection", "close");
 		 		  	      
	    http_request.send(parameters);
	    
	    return http_request;
      }
   }

function send(url, parameters,ispost,callBack) {
	ajax(url,parameters,ispost,function(result){
		eval('var obj='+result);
		callBack(result);	
	});	
}


function ajaxWithFrame( url, callBack){
	//alert("ajaxWithFrame");
	var body=getBody();
	var frame=document.createElement("iframe");
	frame.onload=function(){callBack(frame.innerHTML)};
	frame.style="display:none";
	body.appendChild(frame);
	frame.src=url;	
	
}


function testSessionExpired(testurl){
	var test=function(){
	ajax2(testurl,function(res){
		if(res!="ok"){
			alert("Votre session a expiré. Merci de vous reconnecter.");
			document.location="/";
		}			
	});
	setTimeout(test,5000);
	}
	setTimeout(test,5000);	
}


function toThis(/*obj*/ obj,/* function */ f){
		return function(){
			return f.apply(obj,arguments);
		}
	}
	
function copy(obj){
		var res=new Object();
		for( o in obj){
			res[o]=obj[o];
		}
		return res;
	}
	
function e(id){
	return document.getElementById(id);
}
function ed(id){
	return document.getElementById(id);
}
function removeAll0(domNode){
	var items=domNode.childNodes;
	alert(items);
	//console.debug(items);
	for(i=0;i<items.length;i++){
		domNode.removeChild(items[i]);
	}	
}
function removeAll(cell){
	if ( cell.hasChildNodes() )
	{
	    while ( cell.childNodes.length >= 1 )
	    {
	        cell.removeChild( cell.firstChild );       
	    } 
	}
}


//use the form field to call an action
function ajaxWithForm(formName,action,callBack) {
	var form=document.forms[formName];
	var actsave=form.getAttribute("action");
	
	form.setAttribute("action",action);
	sendForm(form,function(res){
		callBack(res);
		form.setAttribute("action",actsave);
	});
	form.setAttribute("action",actsave);
}

function setFormField(input,value){
	
	var child=ed(input);
	if(child==null)
		throw "field "+input+" not found in the document";
	var tagname=child.tagName.toLowerCase();
	if (tagname == "input") {		
        if (child.type == "text" || child.type == "hidden" || child.type == "password") {
        	
           child.value=value;
        }
        if (child.type == "checkbox") {
        	child.checked=(value=="on");           
        }
        if (child.type == "radio") {
        	//child.checked=(value=="on");
        	setCheckedValueRadio(input,value);
        }
     }else if (tagname == "select") {
    	 child.value=value;
     }else if (tagname == "textarea") {
    	 child.innerHTML=value;
     }        
}
function getFormField(input){
	
	var child=ed(input);
	if(child==null)
		throw "field "+input+" not found in the document";
	var tagname=child.tagName.toLowerCase();
	if (tagname == "input") {		
        if (child.type == "text" || child.type == "hidden") {
        	
           return child.value;
        }
        if (child.type == "checkbox") {
        	return child.checked=="on";           
        }
        if (child.type == "radio") {
        	//child.checked=(value=="on");
        	return getCheckedValueRadio(input);
        }
     }else if (tagname == "select") {
    	 return child.value;
     }else if (tagname == "textarea") {
    	 return child.innerHTML;
     }        
}

function getCheckedValueRadio(groupname) {
	var radioObj=cssQuery("input[name='"+groupname+"']");
	for(var i = 0; i < radioObj.length; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}


function onkeysleep(input,time,callback){
	simpleConnect(input,"onkeyup",function(){
		if(input.timout!=null)
			clearTimeout(input.timout);
		input.timout=setTimeout(callback,time);		
	});
}

function setCheckedValueRadio(groupname, newValue) {
	var radioObj=cssQuery("input[name='"+groupname+"']");	
	for(var i = 0; i < radioObj.length; i++) {		
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}


function preloadImages(imageFolder,images){
    var fonload=function(){
	     // create object
	     imageObj = new Image();
	
	     // start preloading
	     for(var i=1; i<arguments.length; i++) 
	     {
	    	 var image=arguments[i];
	          imageObj.src=imageFolder+"/"+image;
	     }
    }
    simpleConnect(window,"onload",fonload);
}




function getQueryFromObj(obj){
	 var getstr="";
	 var childNodes=cssQuery("input,select,textarea",obj);
	 var tags="";
	 for (i=0; i<childNodes.length; i++) {
		 var child=childNodes[i];
    	 var tag=child.tagName;
    	 tags+=tag+"\n";
    	 var value=child.value;
    	 value=encodeURIComponent(value);
    	 var tagname=tag.toLowerCase();
         if (tagname == "input") {
            if (child.type == "text" || child.type == "hidden") {
               getstr += child.name + "=" + value + "&";
            }
            if (child.type == "checkbox") {
               if (child.checked) {
                  getstr += child.name + "=" + value + "&";
               } else {
                  getstr += child.name + "=&";
               }
            }
            if (child.type == "radio") {
               if (child.checked) {
                  getstr += child.name + "=" + value + "&";
               }
            }
         }else if (tagname == "select") {
            var sel = child;
            getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
         }else if (tagname == "textarea") {
	            var area = child;
	            getstr += area.name + "=" + area.value + "&";
	     }        
      }
	 
	 return getstr;
}

function sendForm(form,callBack) {
	   var obj=form;
	   var url=obj.getAttribute("action");	  
	   var ispost=obj.getAttribute("method").toLowerCase()=="post";
	   var getstr=getQueryFromObj(obj);
	   
	   ajax(url, getstr,ispost,callBack);
}


function removeById(id){
	var ele=document.getElementById(id);
	return removeNode(ele);
}

function removeNode(ele){	
	if(ele==null)
		return null;
	var par=ele.parentNode;
	return par.removeChild(ele);
}
function removeChildren(node)
{
   if(node ==null)   
      return;
  

   var len = node.childNodes.length;

   for(var i = 0; i < len; i++)
   {
      node.removeChild(node.childNodes[i]);
   }
}

function addToFavorites(urlAddress,pageName) {
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(pageName, urlAddress,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( urlAddress, pageName);
	}	
}

function appendNode(parent,type){
	var ele=document.createElement(type);
	parent.appendChild(ele);
	return ele;
}
function getBody(){
	var body = document.getElementsByTagName("body");
	if(body.length>0){
		body=body[0];
	}else{
		body=document.lastChild;
	}
	return body;	
}

function imageComplete(img){
	//Gecko-based
	// browsers act like NS4 in that they report this incorrectly.
	
	if (!img.complete) {
	return false;
	}
	

	// However, they do have two very useful properties:
	//naturalWidth and
	// naturalHeight. These give the true size of the image. If it failed
	// to load, either of these should be zero.
	if (typeof img.naturalWidth	!= undefined && img.naturalWidth == 0) {
	return false;
	}
	return true;
}

function preload(callback){
	var i;
	var numOK=0;
	var numimage=arguments.length-1;
	for(i=1;i<arguments.length;i++){
		var im=arguments[i];
		var img=new Image();
		
		img.src=im;
		if(callback!=null){
		if(imageComplete(img)){			
			numOK++;
			if(numOK==numimage){
				callback();
			}
		}else{			
			img.onload=function(){
				numOK++;
				if(numOK==numimage){
					callback();
				}
			
			}
		}
		}
	}
	
}
function no_accent(my_string) {
	var new_string = String (my_string);
	new_string = new_string.replace(RegExp("(\u0040|&#x40|&#064;|@|&commat;|\u0061|&#x61|&#097;|\u00C0|&#xC0|&#192;|À|&Agrave;|\u00C1|&#xC1|&#193;|Á|&Aacute;|\u00C2|&#xC2|&#194;|Â|&Acirc;|\u00C3|&#xC3|&#195;|Ã|&Atilde;|\u00C4|&#xC4|&#196;|Ä|&Auml;|\u00C5|&#xC5|&#197;|Å|&Aring;|\u00E0|&#xE0|&#224;|à|&agrave;|\u00E1|&#xE1|&#225;|á|&aacute;|\u00E2|&#xE2|&#226;|â|&acirc;|\u00E3|&#xE3|&#227;|ã|&atilde;|\u00E4|&#xE4|&#228;|ä|&auml;|\u00E5|&#xE5|&#229;|å|&aring;)","gi"),'a');
	new_string = new_string.replace(RegExp("(\u00C7|&#xC7|&#199;|Ç|&Ccedil;|\u00E7|&#xE7|&#231;|ç|&ccedil;)","gi"),'c');
	new_string = new_string.replace(RegExp("(\u00D0|&#xD0|&#208;|Ð|&ETH;)","gi"),'d');
	new_string = new_string.replace(RegExp("(\u0065|&#x65;|&#101;|\u00C8|&#xC8;|&#200;|È|&Egrave;|\u00C9|&#xC9;|&#201;|É|&Eacute;|\u00CA|&#xCA;|&#202;|Ê|&Ecirc;|\u00CB|&#xCB;|&#203;|Ë|&Euml;|\u00E8|&#xE8;|&#232;|è|&egrave;|\u00E9|&#xE9;|&#233;|é|&eacute;|\u00EA|&#xEA;|&#234;|ê|&ecirc;|\u00EB|&#xEB;|&#235;|ë|&euml;)","gi"),'e');
	new_string = new_string.replace(RegExp("(\u0069|&#x69|&#105;|\u00CC|&#xCC|&#204;|Ì|&Igrave;|\u00CD|&#xCD|&#205;|Í|&Iacute;|\u00CE|&#xCE|&#206;|Î|&Icirc;|\u00CF|&#xCF|&#207;|Ï|&Iuml;|\u00EC|&#xEC|&#236;|ì|&igrave;|\u00ED|&#xED|&#237;|í|&iacute;|\u00EE|&#xEE|&#238;|î|&icirc;|\u00EF|&#xEF|&#239;|ï|&iuml;)","gi"),'i');
	new_string = new_string.replace(RegExp("(\u006E|&#x6E|&#110;|\u00D1|&#xD1|&#209;|Ñ|&Ntilde;|\u00F1|&#xF1|&#241;|ñ|&ntilde;)","gi"),'n');
	new_string = new_string.replace(RegExp("(\u006F|&#x6F|&#111;|\u00D2|&#xD2|&#210;|Ò|&Ograve;|\u00D3|&#xD3|&#211;|Ó|&Oacute;|\u00D4|&#xD4|&#212;|Ô|&Ocirc;|\u00D5|&#xD5|&#213;|Õ|&Otilde;|\u00D6|&#xD6|&#214;|Ö|&Ouml;|\u00F2|&#xF2|&#242;|ò|&ograve;|\u00F3|&#xF3|&#243;|ó|&oacute;|\u00F4|&#xF4|&#244;|ô|&ocirc;|\u00F5|&#xF5|&#245;|õ|&otilde;|\u00F6|&#xF6|&#246;|ö|&ouml;|\u00F8|&#xF8|&#248;|ø|&oslash;)","gi"),'o');
	new_string = new_string.replace(RegExp("(\u0075|&#x75|&#117;|\u00D9|&#xD9|&#217;|Ù|&Ugrave;|\u00DA|&#xDA|&#218;|Ú|&Uacute;|\u00DB|&#xDB|&#219;|Û|&Ucirc;|\u00DC|&#xDC|&#220;|Ü|&Uuml;|\u00F9|&#xF9|&#249;|ù|&ugrave;|\u00FA|&#xFA|&#250;|ú|&uacute;|\u00FB|&#xFB|&#251;|û|&ucirc;|\u00FC|&#xFC|&#252;|ü|&uuml;)","gi"),'u');
	new_string = new_string.replace(RegExp("(\u0079|&#x79|&#121;|\u00DD|&#xDD|&#221;|Ý|&Yacute;|\u00FD|&#xFD|&#253;|ý|&yacute;|\u00FF|&#xFF|&#255;|ÿ|&yuml;)","gi"),'y');
	new_string = new_string.replace(RegExp("(\u00C6|&#xC6|&#198;|Æ|&AElig;|\u00E6|&#xE6|&#230;|æ|&aelig;)","gi"),'ae');
	new_string = new_string.replace(RegExp("(\u008C|&#x8C|&#140;|Œ|&OElig;|\u009C|&#x9C|&#156;|œ|&oelig;)","gi"),'oe');
	return new_string;
	} 

function include(fileName,onload) {	
	script = document.createElement("script");
	script.type = "text/javascript";
	if(onload!=null)
		script.onload=onload;
	script.src = fileName;
	
	document.getElementsByTagName("head")[0].appendChild(script);
	return script;
	
}

function includeAll(files,onload){
	var ok=0;
	var toload=files.length;
	for(k in files){
		var file=files[k];
		include(file,function(){
			ok++;
			if(ok==toload && onload){
				onload();				
			}
		});
	}
}


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

//modified version of http://www.webmasterworld.com/forum91/4686.htm
//myField accepts an object reference, myValue accepts the text string to add
function insertAtCursor(myField, myValue) {
  //IE support
  if (document.selection) {
      myField.focus();

      //in effect we are creating a text range with zero
      //length at the cursor location and replacing it
      //with myValue
      sel = document.selection.createRange();
      sel.text = myValue;

  //Mozilla/Firefox/Netscape 7+ support
  } else if (myField.selectionStart || myField.selectionStart == '0') {

      myField.focus();
      //Here we get the start and end points of the
      //selection. Then we create substrings up to the
      //start of the selection and from the end point
      //of the selection to the end of the field value.
      //Then we concatenate the first substring, myValue,
      //and the second substring to get the new value.
      var startPos = myField.selectionStart;
      var endPos = myField.selectionEnd;
      myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
      myField.setSelectionRange(endPos+myValue.length, endPos+myValue.length);
  } else {
      myField.value += myValue;
  }
}


/*function getHTML(ele){
	document
		
}*/
function includeCss(fileName,onload){
	  var fileref=document.createElement("link");
	  fileref.setAttribute("rel", "stylesheet");
	  fileref.setAttribute("type", "text/css");
	  fileref.setAttribute("href", fileName);
	  if(onload)
		  fileref.onload=onload;
	  document.getElementsByTagName("head")[0].appendChild(fileref);
}

function includeMore(scripts){
	
}

function testUrl(url,callback,timeout){
	if(timeout==null)
		timeout=1000;
	var img=new Image();
	var cleared=false;
	var tim=setTimeout(function(){cleared=true;callback(false);},timeout);
	img.onload=function(){
		clearTimeout(tim);
		if(!cleared)
			callback(true);
	}
	img.src=url;
}
//use <img onerror="correctImageErrors(this)">
function correctImageErrors(image){
	var src=""+image.src;
	setTimeout(function(){		
		if(image.tried==null)
			image.tried=1;
		if(image.tried<4){
			image.onerror=function(){correctImageErrors(image)};
			image.src=src;
		}			
	},500);
}

function installWeel(div,handle){
	var onWeel=function(event){
		var delta = 0;
	    if (!event) /* For IE. */
	            event = window.event;
	    if (event.wheelDelta) { /* IE/Opera. */
	            delta = event.wheelDelta/120;
	            /** In Opera 9, delta differs in sign as compared to IE.
	             */
	            if (window.opera)
	                    delta = -delta;
	    } else if (event.detail) { /** Mozilla case. */
	            /** In Mozilla, sign of delta is different than in IE.
	             * Also, delta is multiple of 3.
	             */
	            delta = -event.detail/3;
	    }
	    /** If delta is nonzero, handle it.
	     * Basically, delta is now positive if wheel was scrolled up,
	     * and negative, if wheel was scrolled down.
	     */
	    if (delta)
	            handle(delta);
	    /** Prevent default actions caused by mouse wheel.
	     * That might be ugly, but we handle scrolls somehow
	     * anyway, so don't bother here..
	     */
	    if (event.preventDefault)
	            event.preventDefault();
	    event.returnValue = false;
	}
		if(window.addEventListener)
			div.addEventListener('DOMMouseScroll', onWeel, false);
		div.onmousewheel = onWeel;

}




function nopx(str){
	return str.replace("px","");
}
function transparency(div,opa){
	div.style.filter="alpha(opacity="+Math.floor(opa*100)+")";
	div.style.opacity=opa;
	div.style["-moz-opacity"]=opa;
	div.style["-khtml-opacity"]=opa;
}

function screenX(/* event */ e){
	if(!e.screenX) e=window.event;
	return e.screenX;
}
function screenY(/* event */ e){
	if(!e.screenY) e=window.event;
	return e.screenY;
}

function parseQuery(str,sep){
	if(sep==null)
		sep="?";
	if(str==null)
		str=document.location.href;
	var res={url:null,query:null};
	var sp=str.split(sep);
	if(sp.length==1){
		res.url=str;
		res.query=null;
		return res;		
	}

	var search=sp[1];
	res.url=sp[0];
	res.query={};
	sp=search.split("&");
	for(k in sp){
		var tab=sp[k].split("=");
		var name=tab[0];
		var value=tab[1];
		res.query[name]=value;
	}
	
	return res;	
}
function popupStr(code){
	if(!TINY)
		alert(code);
	TINY.box.show(code,0,0,0,1);
}
function popupDiv(div){	
	popupStr(ed(div).innerHTML);
}
function array_contains(arr,ele){
	for(k in arr){
		var obj=arr[k];
		if(obj==ele)
			return true;
	}
	return false;
}
function array_merge(arr1,arr2){
	for(k in arr1){
		var val=arr1[k];
		if(!array_contains(arr2,val))
			arr2.push(val);
	}
	return arr2;
}
function array_remove(arr,ele){
	for(k in arr){
		var obj=arr[k];
		if(obj==ele){
			arr.splice(k,1);
			return obj;
		}
	}
	return null;
}


function buildQuery(q){
	if(q.query==null)
		return q.url;
	var res=q.url;
	res+="?";
	for(key in q.query){
		res+=key+"="+q.query[key]+"&";
	}
	res=res.substring(0,res.length-1);
	return res;
}

function getWindowSize(){
	if (parseInt(navigator.appVersion)>3) {
		 if (navigator.appName=="Netscape") {
		  winW = window.innerWidth;
		  winH = window.innerHeight;
		 }
		 if (navigator.appName.indexOf("Microsoft")!=-1) {
			
		  winW = document.body.offsetWidth;
		  winH = document.body.offsetHeight;
		 }
	}
	return {width:winW,height:winH};
}


function getScrollY(){
	if(isIE()){
		var CScrollY = document.body.scrollTop +
        document.documentElement.scrollTop;
		return CScrollY;
	}else{
		return window.pageYOffset;
	}
		
}

function array2json(arr) {
    var parts = [];
    var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');

    for(var key in arr) {
    	var value = arr[key];
        if(typeof value == "object") { //Custom handling for arrays
            if(is_list) parts.push(array2json(value)); /* :RECURSION: */
            else parts[key] = array2json(value); /* :RECURSION: */
        } else {
            var str = "";
            if(!is_list) str = '"' + key + '":';

            //Custom handling for multiple data types
            if(typeof value == "number") str += value; //Numbers
            else if(value === false) str += 'false'; //The booleans
            else if(value === true) str += 'true';
            else str += '"' + value + '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)

            parts.push(str);
        }
    }
    var json = parts.join(",");
    
    if(is_list) return '[' + json + ']';//Return numerical JSON
    return '{' + json + '}';//Return associative JSON
}


function getWindowDims() {
	  var CWidth, CHeight, CScrollX, CScrollY;

	  if (typeof window.innerWidth != 'undefined'){//NS
	    CWidth = self.innerWidth;
	    CHeight = self.innerHeight;
	    CScrollX = window.pageXOffset;
	    CScrollY = window.pageYOffset;
	  } else if (isIE()) {//IE <6
	    CWidth = document.documentElement.clientWidth;
	    CHeight = document.documentElement.clientHeight;
	    if (CWidth==0) {
	      CWidth = document.body.clientWidth;
	      CHeight = document.body.clientHeight;
	    }
	    CScrollX = document.body.scrollLeft +
	               document.documentElement.scrollLeft;
	    CScrollY = document.body.scrollTop +
	               document.documentElement.scrollTop;
	  } else if (false) {//IE normal
	    CWidth = document.body.clientWidth;
	    CHeight = document.body.clientHeight;
	    CScrollX = document.body.scrollLeft;
	    CScrollY = document.body.scrollTop;
	  }
	  var canvas={};
	  canvas.left    = CScrollX;
	  canvas.right   = CWidth + CScrollX;
	  canvas.top     = CScrollY;
	  canvas.bottom  = CHeight + CScrollY;
	  canvas.xMiddle = Math.round(CWidth/2) + CScrollX;
	  canvas.yMiddle = Math.round(CHeight/2) + CScrollY;
	  canvas.width=canvas.right-canvas.left;
	  canvas.height=canvas.top-canvas.bottom;
	  return canvas;
	}

function findInObj(obj,field){
	for(fi in obj){
		var obi=obj[fi];
		
		if(fi==field){
			return obi;
		}else{
			if(typeof obi=="object"){				
				var res=findInObj(obi,field);
				if(res!=null)
					return res;
			}
		}			
	}
	return null;
}

function getKeyCode(e){
	var code;
	if (!e)
		e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	return code;
}

function forbidSelection(element){
	element.onselectstart = function () { return false; } // ie
	element.onmousedown = function () { return false; } // mozilla
}
function getTarget(e){
	var targ;
	if (!e)
		e = window.event;
	if (e.target)
		targ = e.target;
	else if (e.srcElement)
		targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;

}

/*function getWindowSize(){
	var viewportwidth;
	var viewportheight;
	
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	
	if (typeof window.innerWidth != 'undefined')
	{
	     viewportwidth = window.innerWidth,
	     viewportheight = window.innerHeight
	}
	
	//IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	
	else if (typeof document.documentElement != 'undefined'
	    && typeof document.documentElement.clientWidth !=
	    'undefined' && document.documentElement.clientWidth != 0)
	{
	      viewportwidth = document.documentElement.clientWidth,
	      viewportheight = document.documentElement.clientHeight
	}
	
	// older versions of IE
	
	else
	{
	      viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
	      viewportheight = document.getElementsByTagName('body')[0].clientHeight
	}
	return {width:viewportwidth,height:viewportheight};
}*/




function isIE(){
	var browser=navigator.appName;
	var b_version=navigator.appVersion;
	var version=parseFloat(b_version);	
	if(browser.indexOf("Explorer")>0)
		return true;
	return false;
}
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function setCookie(nom,valeur,jours) {
    var expDate = new Date()
    expDate.setTime(expDate.getTime() + (jours * 24 * 3600 * 1000))
    document.cookie = nom + "=" + escape(valeur) + ";expires=" + expDate.toGMTString()
}
function getIEVersionNumber() {
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");
    
    if (MSIEOffset == -1) {
        return 0;
    } else {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
    }
}

function version(){
	if(isIE())
		return getIEVersionNumber();
	var b_version=navigator.appVersion;
	var version=parseFloat(b_version);
	return version;
}

function connect0(source,event,func,mode){
	if(mode==null)
		mode="after";
		
	var oldFunc=null;
	if(source[event]!=null){
		if(source._events!=null){
			if(source._events[event]==null)
				source._events[event]=new Array();
			if(mode=='after'){
				source._events[event].push(func);
			}else{
				source._events[event].splice(0,0,func);
			}
			return;
		}else{
			oldFunc=source[event];		
		}
	}
	source[event]=function(e){
		var list=source._events[event];
		
			//console.debug(list);
		for(ev in list){
			var func=list[ev];
			func(e);		
		}
	}
	source._events=new Object();
	source._events[event]=new Array();
	if(oldFunc!=null)//add the current event
		source._events[event].push(oldFunc);
		
	if(mode=='after' || source._events[event].length==0){
		source._events[event].push(func);
	}else{
		source._events[event].splice(0,0,func);
	}
	//console.debug(source._events[event]);
}

function disconnect0(source,event,func){
	if(source._events==null){
		return;//never connected;
	}
	var i;
	var list=source._events[event];
	if(list==null || list.length==0)
		return;
	for(i=0;i<list.length;i++){
		var f=list[i];
		if(f == func){
			list.splice(i,1);
			return;
		}
	}
}

function simpleConnect(source,event,func,mode){
	if(mode==null)
		mode='after';
	if(source==null)
		source=document;
	if(source[event]==null){
		source[event]=func;	
	}else{
		var old=source[event];
		//console.debug(old);
		if(mode=='after')
			source[event]=function(e){old(e);return func(e);};
		else
			source[event]=function(e){func(e);return old(e);};
	}
}

/*
function simpleConnect(source,event,func){
	source[event]=func;
}*/


function simpleDisconnect(source,event){
	source[event]=null;
}

//to load a script in ajax mode
ScriptLoader = { request: null,
		 loaded: {},
		 load: function() {
		  for (var i = 0, len = arguments.length; i < len; i++) {
		   var filename = arguments[i];
		   if (!this.loaded[filename]) {
		   	 if (!this.request) {
		   	  if (window.XMLHttpRequest)
		   	  	 this.request = new XMLHttpRequest;
		   	  else if (window.ActiveXObject) {
		   	 	 try { this.request = new ActiveXObject('MSXML2.XMLHTTP');
		   	 	 } catch (e) {
		   	 	  this.request = new ActiveXObject('Microsoft.XMLHTTP'); }
		   	 	  }
		   	  }
		   	  if (this.request) {
		   	   this.request.open('GET', filename, false);
		   	   this.request.send(null);
		   	   if (this.request.status == 200) {
		   	   	this.globalEval(this.request.responseText);
		   	   	this.loaded[filename] = true; }
		   	   	 }
		   	   	 } } },
		  globalEval: function(code) {
		   if (window.execScript)
		   	 window.execScript(code, 'javascript');
		    else alert(code); }
		  };




function merge(div1,div2,delay,callback){
	var nbsecond=100;//a framerate of 100
	var nb=delay/nbsecond;
	var dtr=1/nb;
	div1.thetransparency=1;
	div2.thetransparency=0;
	var more=function(){
		div1.thetransparency-=dtr;
		div2.thetransparency+=dtr;
		transparency(div1,div1.thetransparency);
		transparency(div2,div2.thetransparency);
		if(div1.thetransparency>0){
			setTimeout(more,nbsecond);
		}else{
			callback();
		}
	}
	setTimeout(more,nbsecond);
}

function magicresize(im,maxwidth,maxheight){
	  var image=new Image();  
	  image.onload=function(){
		  //console.debug(im.offsetWidth+"x"+im.offsetHeight);
	    if(this.width<this.height){
	      //im.style.width="auto";->dont work because not centered since margin-left work only with fixed sizes!
	      var he=maxheight;//im.offsetHeight;	      
	      var wi=he*this.width/this.height;
	      //alert(wi+" "+he);
	      im.style.width=wi+"px";
	      im.style.height=he+"px";
	      im.style.marginLeft=((he-wi)/2)+"px";
	      
	    }else if(this.width>this.height){
	    	//alert(this.width+" "+this.height);
	      //im.style.height="auto";//im.className="minishop_image_horizontal";
	      //im.style.marginTop="auto";
	      
	      var wi=maxwidth;//im.offsetWidth;         
	      var he=wi*this.height/this.width;
	      //alert("top:"+wi+" "+he);
	      im.style.height=he+"px";
	      im.style.width=wi+"px";
	      im.style.marginTop=((wi-he)/2)+"px";
	      im.style.marginBottom=((wi-he)/2)+"px";
	    	//im.style.width="110px";
		    //im.style.height="110px";
	    }else{
	    	var wi=maxwidth;//im.offsetWidth;
	    	var he=maxheight;//im.offsetHeight;
	    	im.style.height=he+"px";
		    im.style.width=wi+"px";

		    im.style.marginTop=0;
		    im.style.marginLeft=0;
	    }
	    im.style.visibility="visible";
	  }
	 
	  image.src=im.src;
	}



// Returns a new array with duplicate values removed
function unique(arr) {
	var a = [];
    var l = arr.length;
    
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (arr[i] === arr[j])
          j = ++i;
      }
      a.push(arr[i]);
    }
    return a;
};

// Computes the difference between 2 arrays
function arrayDiff(arr_1, arr_2){
	return arr_1.filter(function(i){
		return !(arr_2.indexOf(i) > -1);
		}
	);
}
  
function getKeywordCategories(jsonMenu){
	var result = new Array();
	var keywords = new Array();
	var categories = new Array();
	
	for(var i=0; i<jsonMenu.length; i++){
		var keyword = jsonMenu[i].keyword;
		keywords[i] = keyword;
	}
	keywords = unique(keywords);
	
	for(var i=0; i<keywords.length; i++){
		var cats = new Array();
		for(var j=0; j<jsonMenu.length; j++){
			if(keywords[i] == jsonMenu[j].keyword){
				cats.push(jsonMenu[j].category);
			}
		}
		cats = unique(cats);
		var resultItem = {
				keyword:keywords[i],
				categories:cats
		};
		result.push(resultItem);
	}
	return result;
}
