var debug = false;
/** globals functions **/

/**
 * test if browser is Internet Exploder
 *
 */
var IE = function(){
	if(document.all && !window.opera){
		return true;
	}
	return false;
}

/**
 * get element by ID
 *
 * @param eid (string) the element ID
 */
function _gid(eid){
	return document.getElementById(eid);
}

/**
 * get window width
 *
 */
function windowWidth(){
	if(IE()){
		return document.body.clientWidth;
	}
	else{
		return window.innerWidth;
	}
}

/**
 * get window height
 *
 */
function windowHeight(){
	if(IE()){
		return document.body.clientHeight;
	}
	else{
		return window.innerHeight;
	}
}

/**
 * get cursor position on X axis
 *
 * @param e (object) mouse event
 */
function getMouseX(e){
		if(IE()){
			return event.clientX + document.body.scrollLeft;
		}
		else{
			return e.clientX + window.pageXOffset;
		}
}

/**
 * get cursor position on Y axis
 *
 * @param e (object) mouse event
 */
function getMouseY(e){
		if(IE()){
			return event.clientY + document.body.scrollTop;
		}
		else{
			return e.clientY + window.pageYOffset;
		}
}

/**
 * get clicked button number
 *
 * @param e (object) mouse event
 */
function getMouseButton(e){
	if(IE()){
		switch(event.button){
			case 1:
				if(debugMode){
					jsterm.innerHTML = 'Mouse button 1';
				}
				return 1;
				break;
			case 2:
				if(debugMode){
					jsterm.innerHTML = 'Mouse button 3';
				}
				return 3;
				break;
			case 4:
				if(debugMode){
					jsterm.innerHTML = 'Mouse button 2';
				}
				return 2;
				break;
			default:
				if(debugMode){
					jsterm.innerHTML = 'Mouse button ' + event.button;
				}
				return event.button;
				break;
		}
	}
	else{
		if(debugMode){
			jsterm.innerHTML = 'Mouse button ' + e.which;
		}
		return e.which;
	}
}

/**
 * get event type
 *
 * @param e (object) event
 */
function getEventType(e){
	if(IE()){
		return event.type;
	}
	else{
		return e.type;
	}
}

/**
 * get event target
 *
 * @param e (object) event
 */
function getEventTarget(e){
	if(IE()){
		return event.srcElement;
	}
	else{
		return e.target;
	}
}

/**
 * get keyboard key number
 *
 * @param e (object) keyboard event
 */
function getKeynum(e){
	if(window.event){
		return e.keyCode;
	}
	else if(e.which){
		return e.which;
	}
}

/**
 * get keyboard key name
 *
 * @param e (object) keyboard event
 */
function getKeyname(code){
	return String.fromCharCode(code);
}

/**
 * page scroll to element position
 *
 * @param eid (string) the element ID
 */
function scrollToId(eid) {
	el = _gid(eid);
	var x = el.x ? el.x : el.offsetLeft
	var y = el.y ? el.y : el.offsetTop;
	document.documentElement.scrollTo(x, y-20);
}

/**
 * page scroll to child element position
 *
 * @param pid (string) the parent element ID
 * @param cid (string) the child element ID
 */
function scrollToChild(pid,cid) {
	var p = _gid(pid);
	var c = _gid(cid);
	p.scrollLeft = c.x ? c.x : c.offsetLeft
	p.scrollTop = c.y ? c.y : c.offsetTop;
}

/**
 * hide block element
 *
 * @param el (object) the element
 */
function hide(el){
	el.style.display = 'none';
}

/**
 * show block element
 *
 * @param el (object) the element
 */
function show(el){
	el.style.display = 'block';
}

/**
 * show block element
 *
 * @param el (object) the element
 */
function toggle(eid){
	if(el.style.display == 'block'){
		hide(el);
	}
	else{
		show(el);
	}
}

/**
 * focus on element
 *
 * @param el (object) the element
 */
function focusElement(el) {
    el.focus();
    el.select();
}

/**
 * set element opacity
 *
 * @param el (object) the element
 * @param val (double) opacity value from 0(transparent) to 1(opaque)
 */
function setOpacity(el,val){
	if(IE()){
		el.style.filter="alpha(opacity="+(val*100)+")";
	}
	else{
		el.style.opacity = val;
	}
}

/**
 * change element inner HTML
 *
 * @param tg (string) target element
 * @param c (string) HTML content
 */
function updateContent(tg,c){
	_gid(tg).innerHTML = c;
}

/**
 * Create an XMLHttpRequest object
 */
function initAjax(){
	if (window.XMLHttpRequest){
		return new XMLHttpRequest();     // Firefox, Safari, ...
	}
	else if (window.ActiveXObject){
		return new ActiveXObject('Microsoft.XMLHTTP');    // Internet Explorer 
	}
	else{
		return false;
	}
}

/**
 * Send an XMLHttpRequest
 *
 * @param p (string) the script url which will be called
 * @param xhr (object) XMLHttpRequest object
 */
function getAjax(p,xhr){
	xhr.open("GET",p,true);
	xhr.send(null);
}

/**
 * Perform an asynchronious request and send result to callback function
 *
 * @param url (string) the script url which will be called
 * @param callback (funtion) function executed on script response
 * @param args (object) parameters sent to callback function
 */
function remoteCall(url, callback, args){
	var re = /.+/;
	var xhr = initAjax();
	getAjax(url,xhr);
	xhr.onreadystatechange = function(){
/*		if(xhr.readyState == 1){
				
		}*/
		if(xhr.readyState == 4){
			var mText = xhr.responseText;
			//if(mText.match(re)){
				callback(mText, args);
			//}
			return true;
		}
	}
}

/**
 * Perform an asynchronious request and write result into HTML element
 *
 * @param pg (string) the script url which will be called
 * @param tg (string) the target element
 * @param spin (bool) display an animation in target element while loading
 * @param reg (bool) not used
 * @param noscroll (bool) scroll page to target element (default true)
 */
function getHTML(pg,tg,spin,reg,noscroll){
	var mBlock = _gid(tg);
	if(mBlock){
		if(spin == true){
			showSpinner(mBlock);
		}
		mBlock.style.cursor='wait';
		remoteCall(pg, function(r, args){
			_gid(args.target).innerHTML = r;
			if(!noscroll){
				scrollToId(args.target);
			}
			_gid(args.target).style.cursor='default';
		},{target:tg});
	}
}

/**
 * Perform an asynchronious request and evaluate result as javascript
 *
 * @param script (string) the script url which will be called
 */
function getJS(script){
	remoteCall(script, function(r){eval(r)});
}

/**
 * Perform an asynchronious request and evaluate result as json object
 *
 * @param script (string) the script url which will be called
 * @param obj (string) name of the object where we store result
 */
function getJSON(script, obj){
	remoteCall(script, function(r,args){
		eval(args+'='+r);
	}, obj);
}

/**
 * replace element content by a loading animation
 *
 * @param el (object) the element
 */
function showSpinner(el){
	el.innerHTML = '<img src="common/gfx/spinner.gif" class="spinner" />';
}

/** end globals functions **/
function opacify(block,clear){
	bg = _gid(block);
	if(clear === true){
		if(bg.style.opacity > 0){
			setOpacity(bg,parseFloat(bg.style.opacity) - 0.2);
			return setTimeout("opacify('"+block+"',true)",70);
		}
		else{
			bg.style.display='none';
		}
	}
	else{
		bg.style.display='block';
		if(bg.style.opacity < 1){
			setOpacity(bg,parseFloat(bg.style.opacity) + 0.2);
			return setTimeout("opacify('"+block+"')",70);
		}
	}
}
var jsterm = false;
var termHistory = new Array();
var positionInHistory = 0;
function showTerminal(){
	var append = false;
	if(!jsterm){
		jsterm = document.createElement('div');
		jsterm.setAttribute('id','jsconsole');
		var jstermout = document.createElement('code');
		jstermout.setAttribute('id','jsconsoleout');
		jstermout.className = 'shell';
		var jstermin = document.createElement('input');
		jstermin.setAttribute('id','jsconsolein');
		jstermin.setAttribute('type','text');
		jsterm.appendChild(jstermout);
		jsterm.innerHTML += '#&nbsp;';
		jsterm.appendChild(jstermin);
		jstermin.onkeypress = function(e){
			consoleKeyEvents(e);
		};
		setOpacity(jsterm,0.75);
		append = true;
	}
	if(jsterm.style.display == 'block'){
		jsterm.style.display = 'none';
	}
	else{
		jsterm.style.display = 'block';
	}
	if(append){
		document.documentElement.appendChild(jsterm);
	}
}
function consoleEval(str){
	var c_output = _gid('jsconsoleout');
	c_output.innerHTML += '#&nbsp;'+str+"<br />\n";
	try{
		var out = eval(str);
		if(out != undefined){
			c_output.innerHTML += out+"<br />\n";
		}
	}
	catch(e){
		c_output.innerHTML += e.message+"<br />\n";
	}
}
function clearConsole(){
	var c_output = _gid('jsconsoleout');
	c_output.innerHTML = '';
}
function consoleKeyEvents(e){
	var k = e.keyCode;
	var c_input = _gid('jsconsolein');
	if(k == 13){
		var c_input = _gid('jsconsolein');
		if(c_input.value == 'clear'){
			clearConsole();
		}
		else{
			consoleEval(c_input.value);
		}
		termHistory.push(c_input.value);
		positionInHistory = 0;
		c_input.value = '';
		scrollToChild('jsconsole','jsconsolein');
	}
	else if(k == 38 && termHistory.length >= 1){
		if(positionInHistory == 0){
			positionInHistory = termHistory.length;
		}
		positionInHistory--;
		c_input.value = termHistory[positionInHistory];
		return false;
	}
	else if(k == 40 && termHistory.length >= 1){
		positionInHistory++;
		if(positionInHistory == termHistory.length){
			positionInHistory = 0;
		}
		c_input.value = termHistory[positionInHistory];
		return false;
	}
}
function setFormAction(f,a){
	var myForm = _gid(f);
	myForm.action = a;
}
function setFieldValue(f,v){
	var myField = _gid(f);
	myField.value = v;
}
function setDictUrl(f){
	var url1 = '/fr/dict/';
	var url2 = '';
	if(f.name == 'lang'){
		url1 = '/'+f.value+'/dict/';
	}
	else{
		url2 = f.value+'.html';
	}
	setFormAction('myForm',url1+url2);
	setFieldValue('test', url1+url2);
}
function imgzap(b,l) {
	var choix=l.options[l.options.selectedIndex].value;
	img = _gid('preview');
	img.src=b+'/'+choix;
}
function chElementBgColor(e, cl, c) {
	if (!document.getElementsByTagName) return;
	var elms = document.getElementsByTagName(e);
	for (var i=0; i < elms.length; i++) {
		var elm = elms[i];
		if (elm.getAttribute("class") == cl || elm.getAttribute("className") == cl){
			elm.style.backgroundColor = c;
		}
	}
}
function chBgColor(i, c){
	var myElem = _gid(i);
	myElem.style.backgroundColor=c;
}
function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
			anchor.target = "_blank";
		if (anchor.getAttribute("form") && anchor.getAttribute("id") == "external")
			anchor.target = "_blank";
	}
}
function validateForm(form, nopass) {
	if (isNotEmpty(form.login)) {
		if (chkPass(form, nopass)) {
			if (isNotEmpty(form.nobot)) {
				if (isNotEmpty(form.firstname)) {
					if (isNotEmpty(form.lastname)) {
						if (isNotEmpty(form.mail)) {
							if (isEMailAddr(form.mail)) {
								return true;
							}
						}
					}
				}
			}
		}
	}
	return false;
}

function isNotEmpty(elem){
	var str = elem.value;
	var re = /.+/;
    if(!str.match(re)) {
        alert("Merci de remplir les champs obligatoires");
        warnElement(elem);
        return false;
    }
    elem.className = '';
    return true;
}

function isEMailAddr(elem) {
    var str = elem.value;
    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!str.match(re)) {
        alert("Merci de vérifier votre adresse courriel");
        warnElement(elem);
        return false;
    }
    elem.className = '';
    return true;
}

function isLen(elem, len, label) {
    var strlen = elem.value.length;
    if (strlen != len) {
        alert("Merci de respecter le format du champs "+label+".");
        warn(elem);
        return false;
    }
    elem.className = '';
    return true;
}

function chkPass(form, nopass) {
    if(nopass == 0){
	if (!isNotEmpty(form.passwd)) {
		return false;
	}
	if (form.passwd.value != form.passwd2.value) {
		alert("Les mots de passe sont différents");
		form.passwd.value = '';
		form.passwd2.value = '';
		warnElement(form.passwd);
		return false;
	}
    }
    return true;
}

function warnElement(elem){
    elem.className = 'warning';
    focusElement(elem);
}

function hideblock(b){
	hide(_gid(b));
}
function showblock(b){
	show(_gid(b));
}
function toggleblock(b){
	var el = _gid(b);
	if(el.style.display == 'block'){
		setOpacity(el,1);
		opacify(b,true);
	}
	else{
		setOpacity(el,0);
		opacify(b);
	}
}
var sticky = false;
function toggleSticky(b){
	var mydiv = _gid(b);
	if(sticky == true){
		mydiv.style.top = (mydiv.style.top.substring(0,(mydiv.style.top.indexOf('px'))) - window.pageYOffset)+'px';
		mydiv.style.position='fixed';
		sticky=false;
	}
	else{
		mydiv.style.top = (mydiv.style.top.substring(0,(mydiv.style.top.indexOf('px'))) + window.pageYOffset)+'px';
		mydiv.style.position='absolute';
		sticky=true;
	}
	saveVar(b,'pos',mydiv.style.position);
}
function toggleContent(b,val1, val2){
	var mydiv = _gid(b);
	if(mydiv.innerHTML == val1){
		mydiv.innerHTML = val2;
	}
	else{
		mydiv.innerHTML = val1;
	}
}
function addtext(field, txt, repl) {
	if(repl){
		setFieldValue(field, txt);
	}
	else{
		var myField = _gid(field);
		if (typeof(document["selection"]) != "undefined") {
			myField.focus();
			sel = document.selection.createRange();
			sel.text = txt[0] + sel.text + txt[1];
		}
		else if (myField.selectionStart || myField.selectionStart == '0') {
			var startPos = myField.selectionStart;
			var endPos = myField.selectionEnd;
			setFieldValue(field, myField.value.substring(0, startPos) + txt[0] + myField.value.substring(startPos, endPos) + txt[1] + myField.value.substring(endPos, myField.value.length));
		}
		else{
			setFieldValue(field, myField.value + txt[0] + txt[1]);
		}
	}
}

function toClipboard(myField){
	focusElement(myField);
	if(IE()){
		Copied = myField.createTextRange();
		Copied.execCommand("Copy");
	}
	else if (window.netscape){
	
		// dit is belangrijk maar staat nergens duidelijk vermeld:
		// you have to sign the code to enable this, or see notes below 
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
		
		// maak een interface naar het clipboard
		var clip = Components.classes['@mozilla.org/widget/clipboard;1']
				.createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return;
		
		// maak een transferable
		var trans = Components.classes['@mozilla.org/widget/transferable;1']
				.createInstance(Components.interfaces.nsITransferable);
		if (!trans) return;
		
		// specificeer wat voor soort data we op willen halen; text in dit geval
		trans.addDataFlavor('text/unicode');
		
		// om de data uit de transferable te halen hebben we 2 nieuwe objecten 
		// nodig om het in op te slaan
		var str = new Object();
		var len = new Object();
		
		var str = Components.classes["@mozilla.org/supports-string;1"]
				.createInstance(Components.interfaces.nsISupportsString);
		
		var copytext=myField.value;
		
		str.data=copytext;
		
		trans.setTransferData("text/unicode",str,copytext.length*2);
		
		var clipid=Components.interfaces.nsIClipboard;
		
		if (!clip) return false;
		
		clip.setData(trans,null,clipid.kGlobalClipboard);
		
	}
}

function isEmpty(elem, re){
	var str = elem.value;
	var re = /.+/;
	if(str.match(re)) {
		return true;
	}
	return false;
}

function disableField(field, d) {
	var myField = _gid(field);
	myField.disabled = d;
}

function add2Sidebar(){
	if (window.sidebar){
		window.sidebar.addPanel('B1Project.com - News', 'http://b1project.com/sidebar-fr.html','');
	}
}

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 or higher.
   {
   for(var i=0; i<document.images.length; i++)
      {
           var img = document.images[i]
           var imgName = img.src.toUpperCase()
           if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
              {
                  var imgID = (img.id) ? "id='" + img.id + "' " : ""
                  var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                  var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                  var imgStyle = "display:inline-block;" + img.style.cssText 
                  if (img.align == "left") imgStyle = "float:left;" + imgStyle
                  if (img.align == "right") imgStyle = "float:right;" + imgStyle
                  if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle                
                  var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
              + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
                  img.outerHTML = strNewHTML
                  i = i-1
              }
      }
   }

function countOnline(){
	remoteCall("/online2.php", function(r){
		updateContent('count_online',r);
		setTimeout("countOnline()",30000);
	});
}

function getWhoIsOnline(){
	remoteCall("/online.php", function(r){
		updateContent('online',r);
		setTimeout("countOnline()",30000);
	});
}

function dobeep() {
	if ((navigator.javaEnabled != null) && (navigator.javaEnabled())) {
		java.awt.Toolkit.getDefaultToolkit().beep();
	}
}

var lastmsgs = null;
function getNewIM(){
	var xhr = initAjax();
	var re = /.+/;
	getAjax("/im.php?do=check",xhr);
	xhr.onreadystatechange = function() {
		if( xhr.readyState == 4){
			var last_im_id = xhr.responseText;
			if(last_im_id != '*' && last_im_id != ''){
				getAjax("/im.php",xhr);
				xhr.onreadystatechange = function() {
				if( xhr.readyState == 4){
					var msgs = xhr.responseText;
						_gid('im_msgs_view').innerHTML = msgs;
						showblock('messenger');
						_gid('im_msgs_view').scrollTop=_gid('im_list').offsetHeight;
						if(window.netscape){
							dobeep();
						}
						externalLinks();
					}
				}
			}
			setTimeout("getNewIM()",20000);
		}
	}
}
function postIM(){
	var xhr = initAjax();
	xhr.open("POST","/im.php",true);
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.send("im_to_uid="+_gid('im_to_uid').value+"&im_msg="+escape(_gid('im_msg').value));
	xhr.onreadystatechange = function() {
		if( xhr.readyState == 4){
			var msgs = xhr.responseText;
			if(msgs != ''){
				if(msgs != lastmsgs){
					lastmsgs = msgs;
					_gid('im_msgs_view').innerHTML = msgs;
					setFieldValue('im_msg','');
					_gid('im_msgs_view').scrollTop=_gid('im_list').offsetHeight;
					externalLinks();
				}
			}
		}
	}
}

function saveVar(t,v,i){
	var xhr = initAjax();
	xhr.open("POST","/setpos.php",true);
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.send("target="+t+"&"+v+"="+i);
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4){
			return true;
		}
	}
}

var block = null;
var prevpos = null;
function initDrag(h,b){
	block = _gid(b);
	h.onmousedown=startDrag;
	block.onmouseup=function(){
		stopDrag(b);
	}
}

function startDrag(e){
	prevpos = block.style.position;
	block.style.position='absolute';
	document.onmousemove=function(e){
		if(IE()){
			block.style.left = (event.clientX-128)+'px';
			block.style.top = (event.clientY-4+document.body.scrollTop)+'px';
		}
		else{
			block.style.left = (e.clientX-128)+'px';
			block.style.top = (e.clientY-4+window.pageYOffset)+'px';
		}
	}
}

function stopDrag(b){
	document.onmousemove=null;
	if(!IE()){
		block.style.position='fixed';
		block.style.top = (block.style.top.substring(0,(block.style.top.indexOf('px'))) - window.pageYOffset)+'px';
	}
	saveVar(b,'xpos',block.style.left);
	saveVar(b,'ypos',block.style.top);
}

var link1;
var link2;
link1 = '<a href="#" onclick="setActiveStyleSheet(\'RatmanBW\');getElementById(\'styleswt\').innerHTML = link2;return false;"><span>Black &amp; White</span></a>';
link2 = '<a href="#" onclick="setActiveStyleSheet(\'Ratman\');getElementById(\'styleswt\').innerHTML = link1;return false;"><span>Color</span></a>';

function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

window.onload = function(e) {
  var cookie = readCookie("style");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
}

window.onunload = function(e) {
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);
}

var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
if(IE()){
	document.documentElement.onload = externalLinks();
}
else{
	window.onload = externalLinks();
}
