/*
----------------------------------------
MAIN RUNNER
----------------------------------------
*/
function main_runner(speed){
	main_runner.storage = new Array();
	main_runner.speed = speed;
}

main_runner.add = function(f){
	main_runner.storage[main_runner.storage.length] = f;
	if(main_runner.storage.length == 1) this.timerID = window.setInterval("main_runner.control()",main_runner.speed);
}

var count = 0;
main_runner.remove = function(f){
	for(var i=0;this.storage[i];i++){
		if(f == this.storage[i]){
			this.storage = this.storage.slice(0,i).concat(this.storage.slice(i+1));
			//break;
		}
	}
	if(this.storage.length == 0){
		window.clearInterval(this.timerID);
		this.timerID=null;
		dislay_message("msg","");
	}
	
}
main_runner.control = function(){
	var now = new Date().getTime();
	dislay_message("msg",this.storage.length + " : " +this.storage[0] + " : " + now);
	for(var i=0; this.storage[i]; i++){
		if(typeof this.storage[i] == "function") {
			this.storage[i]();
		} else {
			eval(this.storage[i]);
		}
	}
	
}

function ap(){}

/*
----------------------------------------
STYLES
----------------------------------------
*/
ap.css = function(){}

ap.css.setStyleByID = function(i,p,v){ /* e: obj.el -> html Element; p: css Property; v: css Value */
	var n = document.getElementById(i);
	n.style[p] = v;
}

ap.css.setStyle = function(e,p,v){ /* e: obj.el -> html Element; p: css Property; v: css Value */
	e.el.style[p] = v;
}

ap.css.getStyleById = function (i, p) { /* i: id; p: css Property */
	var n = document.getElementById(i);
	var s = eval("n.style." + p);
	if((s != "") && (s != null)) { // inline
		return s; 
	}
	if(n.currentStyle) { // currentStyle
		var s = eval("n.currentStyle." + p);
		if((s != "") && (s != null)) {
			return s;
		}
	}
	var sheets = document.styleSheets;
	if(sheets.length > 0) { // styleSheets
		for(var x = 0; x < sheets.length; x++) {
			var rules = sheets[x].cssRules;
			if(rules.length > 0) {
				// check each rule
				for(var y = 0; y < rules.length; y++) {
					var z = rules[y].style;
					if(((z[p] != "") && (z[p] != null)) || (rules[y].selectorText == i)) {
						return z[p];
					}
				}
			}
		}
	}
	return null;
}

ap.css.setStyleByTag = function(t, p, v) { /* t: tag; p: css Property; v: css Value */
	var elements = document.getElementsByTagName(t);
	for(var i = 0; i < elements.length; i++) {
		elements.item(i).style[p] = v;
	}
}

ap.css.toogleClassByID = function(id, c1, c2){ /* id; class 1; class 2; */
	if (el = document.getElementById(id)) {
		if (el.className == c1) el.className = c2;
			else el.className = c1;
			return true;
	}
	return false;
}

ap.css.changeClassByID = function(id, c){ /* id; class 1; */
	if (el = document.getElementById(id)) {
		el.className= c;
		return true;
	}
	return false;
}

ap.css.replaceClassByClass = function(c1,c2){ /* class 1; class 2;*/
	ela = this.getElementsByClassName(c1);
	for (var i = 0; i < ela.length; i++) {
		ela[i].className= c2;
	}
}

ap.css.getElementsByClassName = function(c) {
	var child = document.body.getElementsByTagName('*');
	var ela = new Array(); // element array
	for (var i = 0; i < child.length; i++) { 
		if (child[i].className.match(new RegExp("(^|\\s)" + c + "(\\s|$)"))) {
			ela.push(child[i]);
		}	
	}
	return ela;
}


/*
----------------------------------------
HTML
----------------------------------------
*/

ap.html = function(){}

ap.html.addHtmlIn = function(obj,html) {
	if(obj.constructor != Object) {
		obj = document.getElementById(obj);
	}
	/* make child */
	var p = document.createElement('p');
	p.id = 'innerHTML' + obj.childNodes.length;
	p.innerHTML = html;
	obj.appendChild(p);
}

ap.html.replaceHtmlIn = function(obj,html) {
	if(obj.constructor != Object) {
		obj = document.getElementById(obj);
	}
	/* make child */
	obj.innerHTML = html;
}

function ap_getHTMLData(obj){
	var arr = new Array();
	if(obj.constructor != Object) {
		obj = document.getElementById(obj);
	}
	for (var i=0; i< obj.childNodes.length; i++) {
		if (obj.childNodes[i].nodeType != 1) {
			continue;
		}
		arr[ obj.childNodes[i].id ] = obj.childNodes[i];
	}
	return arr;
}


/*
----------------------------------------
SHADE
----------------------------------------
*/
function shade(id,a,d,e){ // id, gradien array, duration, css element,
	this.id = id;
	this.gradient = a;
	this.d = d;
	this.e = e;
	this.index = 0;
	this.styleElement = 'background';
	this.setStyleElement = function(e){
		this.styleElement = e;
	}
	this.callBack = false;
	this.addCallBack = function(f){
		this.callBack = f;
	}
	// function
	this.initObj = shade.initObj;
	if (!shade.storage) shade.storage = new Array();
	this.doShade = shade.doShade;
	//shade.remove(this.id);
	shade.add(this);
	shade.init();
	return this;
}

shade.init = function(){
	for(var i=0; shade.storage.length > i;i++){
		var thisObj = shade.storage[i];
		if(thisObj) thisObj.initObj();
	}
	main_runner.remove(shade.control);
	main_runner.add(shade.control);
}

shade.initObj = function(){
	this.el = document.getElementById(this.id);
}

shade.add = function(o){
	shade.storage[shade.storage.length] = o;
}

shade.remove = function(o){
	for(var i=0;this.storage[i];i++){
		if(o == this.storage[i].id){
			this.storage = this.storage.slice(0,i).concat(this.storage.slice(i+1));
		}
	}
	if(this.storage.length == 0){
		main_runner.remove(shade.control);
	}
}

shade.control = function(){
	var function_name = "shade.control";	
	for(var i=0; shade.storage.length > i;i++){
		var thisObj = shade.storage[i];
		if(thisObj) thisObj.doShade();
	}
}

shade.doShade = function(){
	if (this.index < this.gradient.length) {
		ap.css.setStyle(this,this.styleElement,this.gradient[this.index++]);
	} else if (this.callBack) {
		this.callBack(this.id);
		shade.remove(this.id);
	} else {
		shade.remove(this.id);
	}
}


/*
----------------------------------------
SCROLL
----------------------------------------
*/
function scroll(el,cont,dir,s){ // id, container, direction, (angle)
	this.id = el.id;
	this.index = 0;
	this.el = document.getElementById(this.id);
	this.cont = cont;
	this.dir = dir;
	this.s = (s) ? s : 5;
	
	this.setStyleElement = function(e){
		this.styleElement = e;
	}
	
	this.callBack = false;
	
	this.addCallBack = function(f){
		this.callBack = f;
	}
	
	this.initObj = scroll.initObj;
	if (!scroll.storage) scroll.storage = new Array();
	this.doScroll = scroll.doScroll;
	scroll.remove(this.id);
	scroll.add(this);
	scroll.init();
	return this;
}

scroll.init = function(){
	for(var i=0; scroll.storage.length > i;i++){
		var thisObj = scroll.storage[i];
		if(thisObj) thisObj.initObj();
	}
	main_runner.remove(scroll.control);
	main_runner.add(scroll.control);

}

scroll.initObj = function(){
	this.el = document.getElementById(this.id);
}

scroll.add = function(o){
	scroll.storage[scroll.storage.length] = o;
}

scroll.remove = function(id){
	for(var i=0;this.storage[i];i++){
		if(id == this.storage[i].id){
			this.storage = this.storage.slice(0,i).concat(this.storage.slice(i+1));
		}
	}
	if(this.storage.length == 0){
		main_runner.remove(scroll.control);
	}
}

scroll.control = function(){
	var function_name = "scroll.control";
	for(var i=0; scroll.storage.length > i;i++){
		var thisObj = scroll.storage[i];
		if(thisObj) thisObj.doScroll();
	}
}

scroll.doScroll = function(){
	var dis = (this.dir != 'up') ? - this.s : this.s;
	
	var btPos = this.el.offsetHeight + parseInt(this.el.style.top.replace('px',''));
	var tpPos = parseInt(this.el.style.top.replace('px',''));
	
	if ( btPos > this.cont.offsetHeight && this.dir == 'up') {
		this.el.style.top = (parseInt(this.el.style.top.replace('px','')) - dis) + 'px';
	} else if ( tpPos < 0 && this.dir != 'up') {
		this.el.style.top = (parseInt(this.el.style.top.replace('px','')) - dis) + 'px';
	} else if (this.callBack) {
		this.callBack(this.id);
		scroll.remove(this.id);
	} else {	
		scroll.remove(this.id);
	}
	
}

function getScrollY(){
	var y=0;
	if(document.documentElement&&document.documentElement.scrollTop)
		y=document.documentElement.scrollTop;
	else if(document.body&&document.body.scrollTop)
		y=document.body.scrollTop;
	else if(window.pageYOffset)
		y=window.pageYOffset;
	else if(window.scrollY)
		y=window.scrollY;
	return parseInt(y);
}

/*
----------------------------------------
GET ELEMENT POSITION
----------------------------------------
*/
function findRelativePosTo(obj,referer) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj.offsetParent && obj.offsetParent.id != referer.id) {
			obj = obj.offsetParent;
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

/*
----------------------------------------
SLIDER
----------------------------------------
*/
function slider(id,x,y,d){
	this.id = id;
	this.duration = d;
	this.x = x;
	this.y = y;
	this.checkPos = slider.checkPos;
	this.initObj = slider.initObj;
	if (!slider.storage) slider.storage = new Array();
	slider.remove(this.id);
	slider.add(this);
	slider.init();
	return this;
}

slider.init = function(){
	for(var i=0; slider.storage.length > i;i++){
		var thisObj = slider.storage[i];
		if(thisObj) thisObj.initObj();
	}
	main_runner.remove(slider.control);
	main_runner.add(slider.control);
}

slider.initObj = function(){
	this.el = document.getElementById(this.id);
	this.xp = parseInt(this.el.style.left.replace('px',''))|| 0;
	this.yp = parseInt(this.el.style.top.replace('px','')) || 0;
	this.ww = parseInt(this.el.style.width.replace('px','')) || "auto";
	this.hh = parseInt(this.el.style.height.replace('px','')) || "auto";
	//dislay_message("msg2","this.el: " + this.el + " this.xp: " + this.xp + " this.yp: " + this.yp);
}

slider.reInit = function(){
	this.initTime = new Date().getTime();
}

slider.checkPos = function(){	
	if(!this.el) return;
	this.yy = parseInt(this.el.style.top.replace('px',''));
	this.yd = getScrollY() + this.yp;
	this.yd = (this.yd + this.y > this.yp) ? this.yd + this.y : this.yp;
	if (this.yd != this.yy) {
		//var last = this.now;
		//this.now = new Date().getTime();
		var speed = parseInt(this.duration / main_runner.speed);
		var delta = (this.yd - this.yy);
		var mv = (delta < 0) ? -4 : 4 ;
		mv = (Math.abs(delta) >= 8) ? mv : delta;
		this.ny = (Math.abs((delta/speed)) >= 4) ? (this.yy + parseInt((delta/speed))) : this.yy + mv;
		this.el.style.top = this.ny + 'px';
	}
}

slider.add = function(o){
	slider.storage[slider.storage.length] = o;
}

slider.remove = function(o){
	for(var i=0;this.storage[i];i++){
		
		if(o == this.storage[i].id){
			this.storage[i].el.style.top = this.storage[i].yp;
			this.storage = this.storage.slice(0,i).concat(this.storage.slice(i+1));
		}
	}
	if(this.storage.length == 0){
		main_runner.remove(slider.control);
	}
}

slider.control = function(){
	var function_name = "slider.control";
	for(var i=0; slider.storage.length > i;i++){
		var thisObj = slider.storage[i];
		if(thisObj) thisObj.checkPos();
	}
}


/*
----------------------------------------
FORM
----------------------------------------
*/
function getFormData(htmlObj){
	var str = '';
	var thisObj = "";
	for (var i=0; i< htmlObj.childNodes.length; i++) {
	
		if (htmlObj.childNodes[i].nodeType != 1) {
			continue;
		}
		
		if (htmlObj.childNodes[i].nodeName == "INPUT") {
			if (htmlObj.childNodes[i].type == "text") {
				str += htmlObj.childNodes[i].name + "=" + htmlObj.childNodes[i].value + "&";
			}
			else if (htmlObj.childNodes[i].type == "checkbox") {
				if (htmlObj.childNodes[i].checked) {
					str += htmlObj.childNodes[i].name + "=" + htmlObj.childNodes[i].value + "&";
				} else {
					str += htmlObj.childNodes[i].name + "=&";
				}
			}
			else if (htmlObj.childNodes[i].type == "radio") {
				if (htmlObj.childNodes[i].checked) {
					str += htmlObj.childNodes[i].name + "=" + htmlObj.childNodes[i].value + "&";
				}
			}
			if (htmlObj.childNodes[i].type == "hidden") {
				str += htmlObj.childNodes[i].name + "=" + htmlObj.childNodes[i].value + "&";
			}
			
		}
		else if (htmlObj.childNodes[i].nodeName == "SELECT") {
			/* todo multi selection */
			var sel = htmlObj.childNodes[i];
			str += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
			
		}
		else if (htmlObj.childNodes[i].nodeName == "TEXTAREA") {
			str += htmlObj.childNodes[i].name + "=" + htmlObj.childNodes[i].value + "&";
		}
		else if(htmlObj.childNodes[i].nodeType == 1) { // htmlContainerList[htmlObj.childNodes[i].nodeName] >= 1
			str += getFormData(htmlObj.childNodes[i]);
		}
	}
	return str;	
}

function formArray(fid) {
	return "?"+getFormData(fid)+'-/-' + cvData.toJSONString();
}


/*
----------------------------------------
AJAX
----------------------------------------
*/
function apAjax_ResponseTest(responseText){
	if (responseText=='expired') {
		window.location = '../index-expired.php';
		return false;
	}
	return true;
}
function apAjax_loadedFunction(obj){
	apGui_status(obj.url +" is loaded ");
}
function loginBox(o) {
	
	YAHOO.apBox.close({},{callBack: function(){}});
	
	var obj = new Object();
	var content = document.createElement('form');
	content.id = 'loginRequest';
	content.name = 'loginRequest';
	
	var loginP = document.createElement('p');
	loginP.appendChild(document.createTextNode('Adresse email :'));
	
	var login = document.createElement('input');
	login.name = 'email';
	login.className = 'text';	
	loginP.appendChild(document.createElement('br'));
	loginP.appendChild(login);
	
	var passP = document.createElement('p');
	passP.appendChild(document.createTextNode('Mot de passe :'));
	
	var pass = document.createElement('input');
	pass.type = 'password';
	pass.name = 'password';
	pass.className = 'text';
	passP.appendChild(document.createElement('br'));
	passP.appendChild(pass);
	
	content.appendChild(loginP);
	content.appendChild(passP);
	
	YAHOO.util.Event.addListener(content, 'submit', function(e) {
			YAHOO.util.Event.stopEvent(e);
	});
	
	
	obj.submitCallBack = function() {
		
		var ajx = new apAjax();
		if (o.isLoaded) {
			ajx.isLoaded = o.isLoaded;
		}
		else {
			ajx.isLoaded = function(o) {
				YAHOO.apBox.close({},{callBack:function(){}});
				var obj = new Object();
				obj.msg = "Succès de l'identification.";
				obj.content = document.createTextNode('Vous êtes de nouveau connecté au service moncv.com');
				YAHOO.apBox.openNotifyBox(obj);
				
			}
		}
		
		ajx.data = "email="+login.value+"&password="+pass.value;
		ajx.url = pathToAjax + "login.php";
		apAjax_postData(ajx);
		
	}
	if (o.reason) obj.msg = o.reason;
	obj.content = content;
	
	YAHOO.apBox.openLoginBox(obj);
}
function apAjax_APIErrorManager(object) {
	
	this.errorFunctions = new Array();
	
	this.errorFunctions[302] = function(o) {
		
		loginBox(o);
	}
	
	this.errorFunctions[403] = function(o) {
		
		YAHOO.apBox.close({},{callBack: function(){}});
		
	}
	
	this.errorFunctions[404] = function(o) {
		
		YAHOO.apBox.close({},{callBack: function(){}});
		apToolTip('Une erreur est survenue.',o.status.reason);
		
	}
	
	this.setError = function(o) {
		if (o.statusCode && typeof(o.f) == 'function') {
			this.errorFunctions[o.statusCode] = o.f;
		}
	}
	
	this.error = function(o) {
		if (o.status.statusCode) {
			this.errorFunctions[o.status.statusCode](o);
		}
	}
	
	return this;
}

function apAjax_errorFunction(obj){
	alert("There was a problem retrieving the XML data from:\n" + obj.url +" (status: "+ obj.XMLobject.status +")" );
}

function apAjax(){
	this.settings = new Object();
	this.isIE = false;
	this.isLoaded = apAjax_loadedFunction;
	this.isError = apAjax_errorFunction;
	this.APIError = new apAjax_APIErrorManager();
	this.asyncFlag = true;
	this.userName = false;
	this.password = false;
	this.readyState_1 = function(){return;};
	this.readyState_2 = function(){return;};
	this.readyState_3 = function(){return;};
	return this;
}

function apAjax_loadXMLDoc(obj) {
	obj.XMLobject = false;
	try {
		if (window.XMLHttpRequest) {
        	obj.XMLobject = new XMLHttpRequest();
    	} else if (window.ActiveXObject) {
        	obj.isIE = true;
        	obj.XMLobject = new ActiveXObject("Microsoft.XMLHTTP");
    	}
    	if (obj.XMLobject) {
    		obj.XMLobject.onreadystatechange = function(){
    			XMLHttpRequest_readyState(obj);
    		}
			obj.XMLobject.open("GET", obj.url, true);
			if (obj.isIE) {
				obj.XMLobject.send();
			} else {
				obj.XMLobject.send(null);
			}
        }
	}
	catch(e){
		var msg = (typeof e == "string") ? e : ((e.message) ? e.message : "Unknown Error");
		alert("Unable to get XML data:\n" + msg);
		return;
	}
}

function apAjax_postData(obj) {
	obj.XMLobject = false;
	try {
		if (window.XMLHttpRequest) {
        	obj.XMLobject = new XMLHttpRequest();
    	} else if (window.ActiveXObject) {
        	obj.isIE = true;
        	obj.XMLobject = new ActiveXObject("Microsoft.XMLHTTP");
    	}
    	if (obj.XMLobject) {
    		obj.XMLobject.onreadystatechange = function(){
    			XMLHttpRequest_readyState(obj);
    		}
			if(!obj.userName) {
				obj.XMLobject.open("POST", obj.url, obj.asyncFlag);
			} else {
				obj.XMLobject.open("POST", obj.url, obj.asyncFlag, obj.userName, obj.password);
			}
			obj.XMLobject.setRequestHeader("Method", "POST " + obj.url + " HTTP/1.1");
			obj.XMLobject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			obj.XMLobject.send(obj.data);
        }
	}
	catch(e){
		var msg = (typeof e == "string") ? e : ((e.message) ? e.message : "Unknown Error");
		alert("Unable to get XML data:\n" + msg);
		return;
	}
}


function XMLHttpRequest_readyState(obj) {
/*
Object status integer:
0=uninitialized; 1=loading; 2=loaded; 3=interactive; 4=complete
*/
	switch (obj.XMLobject.readyState) {
		case 1:
			obj.readyState_1(obj);
		break;
		case 2:
			obj.readyState_2(obj);
		break;
		case 3:
			obj.readyState_3(obj);
		break;
		case 4:
			if (obj.XMLobject.status == 200) {
				var doc = obj.XMLobject.responseText;
				try {
					var jsonquery = doc.parseJSON();
					var status = jsonquery.status;
					//document.cookie = "inoveumSession=" + doc.sessionId + "; expires=0; path=/";
					if (status.statusCode == 200) {
						if (jsonquery.content) {
							obj.content = jsonquery.content;
						}
						obj.isLoaded(obj);
					}
					else {
						//doc.isLoaded = obj.isLoaded;
						obj.APIError.error(jsonquery);
					}
				}
				catch (e) {
					obj.isLoaded(doc);
				}
			} else {
				obj.isError(obj);
			}
	}
}

/*
----------------------------------------
GRAPHICS / COLORS
----------------------------------------
*/
ap.graphics = function() {}
ap.math = function() {}
ap.math.hexNum = "0123456789ABCDEF";

ap.math.hex2dec = function(hex) {
	var hex = hex.toUpperCase();
	var d = 0;
	for(var i = 0; i < hex.length; i++) {
		m = (i>0) ? i*16 : 1 ;
		d += ap.math.hexNum.indexOf(hex.charAt(i)) * m;
	}
	return d;
}

ap.math.dec2hex = function(d) {
	return d.toString(16);
}

ap.graphics.color = function() {}

ap.graphics.color.blend = function(a,b,p) { //1 = 50%
}

ap.graphics.color.hex2rgb = function(hex) {
	var rgb = new Array(3);
	if( hex.indexOf("#") == 0 ) { 
		hex = hex.substring(1); 
	}
	if( hex.length == 3 ) {
		rgb[0] = ap.math.hex2dec( hex.charAt(0) + hex.charAt(0) );
		rgb[1] = ap.math.hex2dec( hex.charAt(1) + hex.charAt(1) );
		rgb[2] = ap.math.hex2dec( hex.charAt(2) + hex.charAt(2) );
	} else {
		rgb[0] = ap.math.hex2dec( hex.substring(0, 2) );
		rgb[1] = ap.math.hex2dec( hex.substring(2, 4) );
		rgb[2] = ap.math.hex2dec( hex.substring(4) );
	}
	return rgb;
}

ap.graphics.color.rgb2hex = function(r, g, b) {
	
	return true;	
}


/*
----------------------------------------
LOCAL
----------------------------------------
*/
function slideMe(id){
	new slider(id,0,-200,1000);
}
function unSlideMe(id){
	slider.remove(id);
}
function shadeMe(id){
	var grad = Array("#FF0000","#FF1111","#FF2222","#FF3333","#FF4444","#FF5555","#FF6666","#FF7777","#FF8888","#FF9999","#FFAAAA","#FFBBBB","#FFCCCC","#FFDDDD","#FFEEEE","#FFFFFF");
	myShade = new shade(id,grad,300,'sdsds');
	return myShade;
}
function unShadeMe(id){
	shade.remove(id);
}
function hideMe(id){
	document.getElementById(id).style.display = "none";
}


/*
----------------------------------------
JSON
----------------------------------------
json.js 2006-04-28
This file adds these methods to JavaScript:

object.toJSONString()
	This method produces a JSON text from an object. The
	object must not contain any cyclical references.

array.toJSONString()
	This method produces a JSON text from an array. The
	array must not contain any cyclical references.

string.parseJSON()
	This method parses a JSON text to produce an object or
	array. It will return false if there is an error.
*/
/*(function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    Object.prototype.toJSONString = function () {
        return s.object(this);
    };

    Array.prototype.toJSONString = function () {
        return s.array(this);
    };
})();

String.prototype.parseJSON = function () {
    try {
        return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                this.replace(/"(\\.|[^"\\])*"/g, ''))) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};*/

/*(function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    Object.toJSONString = function(obj) {
        return s.object(obj);
    };
})();

String.prototype.parseJSON = function () {
    try {
        return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                this.replace(/"(\\.|[^"\\])*"/g, ''))) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};*/

/*
    json.js
    2008-03-14

    Public Domain

    No warranty expressed or implied. Use at your own risk.

    This file has been superceded by http://www.JSON.org/json2.js

    See http://www.JSON.org/js.html

    This file adds these methods to JavaScript:

        array.toJSONString(whitelist)
        boolean.toJSONString()
        date.toJSONString()
        number.toJSONString()
        object.toJSONString(whitelist)
        string.toJSONString()
            These methods produce a JSON text from a JavaScript value.
            It must not contain any cyclical references. Illegal values
            will be excluded.

            The default conversion for dates is to an ISO string. You can
            add a toJSONString method to any date object to get a different
            representation.

            The object and array methods can take an optional whitelist
            argument. A whitelist is an array of strings. If it is provided,
            keys in objects not found in the whitelist are excluded.

        string.parseJSON(filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = text.parseJSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard in 2008.

    This file will break programs with improper for..in loops. See
    http://yuiblog.com/blog/2006/09/26/for-in-intrigue/

    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    Use your own copy. It is extremely unwise to load untrusted third party
    code into your pages.
*/

/*jslint evil: true */

/*members "\b", "\t", "\n", "\f", "\r", "\"", "\\", apply, charCodeAt,
    floor, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes,
    getUTCMonth, getUTCSeconds, hasOwnProperty, join, length, parseJSON,
    prototype, push, replace, test, toJSONString, toString
*/

// Augment the basic prototypes if they have not already been augmented.

if (!Object.prototype.toJSONString) {

    Array.prototype.toJSONString = function (w) {
        var a = [],     // The array holding the partial texts.
            i,          // Loop counter.
            l = this.length,
            v;          // The value to be stringified.

// For each value in this array...

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {
            case 'object':

// Serialize a JavaScript object value. Treat objects thats lack the
// toJSONString method as null. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                if (v && typeof v.toJSONString === 'function') {
                    a.push(v.toJSONString(w));
                } else {
                    a.push('null');
                }
                break;

            case 'string':
            case 'number':
            case 'boolean':
                a.push(v.toJSONString());
                break;
            default:
                a.push('null');
            }
        }

// Join all of the member texts together and wrap them in brackets.

        return '[' + a.join(',') + ']';
    };


    Boolean.prototype.toJSONString = function () {
        return String(this);
    };


    Date.prototype.toJSONString = function () {

// Eventually, this method will be based on the date.toISOString method.

        function f(n) {

// Format integers to have at least two digits.

            return n < 10 ? '0' + n : n;
        }

        return '"' + this.getUTCFullYear()   + '-' +
                   f(this.getUTCMonth() + 1) + '-' +
                   f(this.getUTCDate())      + 'T' +
                   f(this.getUTCHours())     + ':' +
                   f(this.getUTCMinutes())   + ':' +
                   f(this.getUTCSeconds())   + 'Z"';
    };


    Number.prototype.toJSONString = function () {

// JSON numbers must be finite. Encode non-finite numbers as null.

        return isFinite(this) ? String(this) : 'null';
    };


    Object.prototype.toJSONString = function (w) {
        var a = [],     // The array holding the partial texts.
            k,          // The current key.
            i,          // The loop counter.
            v;          // The current value.

// If a whitelist (array of keys) is provided, use it assemble the components
// of the object.

        if (w) {
            for (i = 0; i < w.length; i += 1) {
                k = w[i];
                if (typeof k === 'string') {
                    v = this[k];
                    switch (typeof v) {
                    case 'object':

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                        if (v) {
                            if (typeof v.toJSONString === 'function') {
                                a.push(k.toJSONString() + ':' +
                                       v.toJSONString(w));
                            }
                        } else {
                            a.push(k.toJSONString() + ':null');
                        }
                        break;

                    case 'string':
                    case 'number':
                    case 'boolean':
                        a.push(k.toJSONString() + ':' + v.toJSONString());

// Values without a JSON representation are ignored.

                    }
                }
            }
        } else {

// Iterate through all of the keys in the object, ignoring the proto chain
// and keys that are not strings.

            for (k in this) {
                if (typeof k === 'string' &&
                        Object.prototype.hasOwnProperty.apply(this, [k])) {
                    v = this[k];
                    switch (typeof v) {
                    case 'object':

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                        if (v) {
                            if (typeof v.toJSONString === 'function') {
                                a.push(k.toJSONString() + ':' +
                                       v.toJSONString());
                            }
                        } else {
                            a.push(k.toJSONString() + ':null');
                        }
                        break;

                    case 'string':
                    case 'number':
                    case 'boolean':
                        a.push(k.toJSONString() + ':' + v.toJSONString());

// Values without a JSON representation are ignored.

                    }
                }
            }
        }

// Join all of the member texts together and wrap them in braces.

        return '{' + a.join(',') + '}';
    };


    (function (s) {

// Augment String.prototype. We do this in an immediate anonymous function to
// avoid defining global variables.

// m is a table of character substitutions.

        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };


        s.parseJSON = function (filter) {
            var j;

            function walk(k, v) {
                var i, n;
                if (v && typeof v === 'object') {
                    for (i in v) {
                        if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                            n = walk(i, v[i]);
                            if (n !== undefined) {
                                v[i] = n;
                            } else {
                                delete v[i];
                            }
                        }
                    }
                }
                return filter(k, v);
            }


// Parsing happens in three stages. In the first stage, we run the text against
// a regular expression which looks for non-JSON characters. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we will reject all
// unexpected characters.

// We split the first stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace all backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

			if (/^[\],:{}\s]*$/.test(this.replace(/\\["\\\/bfnrtu']/g, '@').
                    replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
                    replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

				j = eval('(' + this + ')');

// In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.

				return typeof filter === 'function' ? walk('', j) : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

			throw new SyntaxError('parseJSON');
        };


        s.toJSONString = function () {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.

            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/[\x00-\x1f\\"]/g, function (a) {
                    var c = m[a];
                    if (c) {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' + Math.floor(c / 16).toString(16) +
                                               (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
}

/*
----------------------------------------
DYNAMIC NODES
----------------------------------------
*/
function insertAfter(newx, x) {
	x.parentNode.insertBefore(newx, x.nextSibling);
}
function insertBefore(newx, x) {
	x.parentNode.insertBefore(newx, x);
}

function apDynCopyListById(id,newId){
	
	if (x = document.getElementById(id)) {
		var newx = x.cloneNode(true);
		newx.setAttribute('id', newId);
		insertAfter(newx, x);
		return true;
	}
	return false;
}

function apDynUpListById(id){
	if (x = document.getElementById(id)) {
		var newx = x.cloneNode(true);
		if (x.parentNode) {
			x.parentNode.insertBefore(newx, x.previousSibling);
			x.parentNode.removeChild(x);
			return true;
		}
	}
	return false;
}

function apDynDownListById(id) {
	
	if (x = document.getElementById(id)) {
		var newx = x.cloneNode(true);
		if (x.nextSibling) {
			x.parentNode.insertBefore(newx, x.nextSibling.nextSibling);
			x.parentNode.removeChild(x);
			return true;
		}
	}
	return false;
}

function apDynHideListById(id){
	
	if (x=document.getElementById(id)) {
	 x.parentNode.removeChild(x);
	 return true;
	}
	return false;
}

function apDynAddListById(div, o){
	if (x=document.getElementById(div)) {
		
		return x.appendChild(o);
	}
	return false;
	
}

/*
----------------------------------------
ARRAY
----------------------------------------
*/
function in_array(the_needle, the_haystack){
	var the_hay = the_haystack.toString();
	if(the_hay == '') 	return false;
	var the_pattern = new RegExp(the_needle, 'g');
	var matched = the_pattern.test(the_haystack);
	return matched;
}
function randomArray ( myArray ) {
  var i = myArray.length;
  if (i==0) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
   return myArray;
}
function array_search(val, arr) {
	var i = arr.length;
	while (i--)
		if (arr[i] && arr[i] === val) break;
	return i;
}
function array_insert(arr, pos, val) {
    before = arr.slice(0, pos);
    after = arr.slice(pos);
    before.push(val);
    for (var p in after) {
    	if (p == 'toJSONString') continue;
    	before.push(after[p]);
    }
    return before;
} 
function array_remove(arr, c) {
	var tmparr = new Array();
	for (var i=0; i<arr.length; i++) {
		if (i!=c) tmparr[tmparr.length] = arr[i];
	}
	return tmparr;
}
function array_add(arr, c, cont) {
	return array_insert(arr, c, cont);
}
/*
----------------------------------------
EVENTS
----------------------------------------
*/
function addEvent(obj, evType, fn, useCapture){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		alert("Handler could not be attached");
	}
}
function removeEvent(obj, evType, fn, useCapture){
	if (obj.removeEventListener){
		obj.removeEventListener(evType, fn, false);
		return true;
	} else if (obj.detachEvent){
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	} else {
		alert("Handler could not be detachEvent");
	}
}
function apGetTarget(e){
	var targ;	
	if (!e) var 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;
}
/*
----------------------------------------
DATE
----------------------------------------
*/
function date_us2fr(date) {
	if (!date) return false;
	var arrDate = date.split('-');
	return arrDate[2]+'/'+arrDate[1]+'/'+arrDate[0];

}
function date_fr2us(date) {
	if (!date) return false;
	var arrDate = date.split(new RegExp('[^0-9]'));
	return arrDate[2]+'-'+arrDate[1]+'-'+arrDate[0];
}
function IsoDate2jsDate(iso) {
	return iso.replace(/^(....).(..).(.{11}).*$/, "$1/$2/$3");
}

/*
----------------------------------------
ENCODE DECODE TRIM
----------------------------------------
*/

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

function ap_styleTextDecode(s){
	var str = new String(s);
	str = ap_TextDecode(str);
	str = str.replace(/\*(\/?[^\*]+)\*/g, "<strong>$1<\/strong>");
	str = str.replace(/_(\/?[^_]+)_/g, "<em>$1<\/em>");
	str = str.replace(/\n/g, "<br />");
	str = str.replace(/\r/g, "<br />");
	return str;
}
function ap_TextDecode(s){
	var str = new String(s);
	// empty -> .match(/^\s*$/)
	str = str.replace(/<\/?[^>]+>/g, '');
	str = str.replace(/\&/g, "&amp;");
	str = str.replace(/</g, "&lt;");
	str = str.replace(/>/g, "&gt;");
	str = str.replace(/\"/g, "&quot;");
	return str;
}
function ap_styleTextEncode(s){
	var str = new String(s);
	str = str.replace(/\<strong\>/g, "*");
	str = str.replace(/\<\/strong\>/g, "*");
	str = str.replace(/\<em\>/g, "_");
	str = str.replace(/\<\/em\>/g, "_");
	str = str.replace(/\<br \/>/g, "/\n");
	str = ap_TextDecode(str);
	return str;
}
/*
----------------------------------------
TEST DEBUG
----------------------------------------
*/
function print_r(theObj){
	if(theObj.constructor == Array ||theObj.constructor == Object) {
		document.write("<ul>")
		for(var p in theObj){
			if(theObj[p].constructor == Array||theObj[p].constructor == Object){
				document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
				document.write("<ul>");
				print_r(theObj[p]);
				document.write("</ul>");
			} else {
				document.write("<li>["+p+"] => "+theObj[p]+"</li>");
			}
		}
    	document.write("</ul>")
	}
}

function return_r(theObj){
	var html = "";
	if(theObj.constructor == Array ||theObj.constructor == Object) {
		html += "<ul>";
		
		for(var p in theObj){
			
			if(theObj[p].constructor == Array||theObj[p].constructor == Object){
				
				html += "<li>["+p+"] => "+ typeof(theObj) +"</li>";
				
				html += "<ul>";
				html += return_r(theObj[p]);
				html += "</ul>";
				
			} else {
				
				html += "<li>["+p+"] => "+ theObj[p] +"</li>";
				
			}
			
		}
		
    	html += "</ul>";
	}
	return html;
}
function echo_r(theObj){
	var html = "";
	if(theObj.constructor == Array || theObj.constructor == Object) {
		html += "#\n\r";
		
		for(var p in theObj){
			
			if(theObj[p].constructor == Array || theObj[p].constructor == Object){
				
				html += "\t\t["+p+"] => "+ typeof(theObj) +"\n\r";
				
				html += "\n\r--\n\r";
				html += return_r(theObj[p]);
				html += "\n\r--\n\r";
				
			} else {
				
				html += "\t\t["+p+"] => "+ theObj[p] +"\n\r";
				
			}
			
		}
		
    	html += "#\n\r";
	}
	return html;
}
function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }

  return elements;
}