/*
----------------------------------------
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_satus(obj.url +" is loaded ");
}

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.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) {
				obj.isLoaded(obj);
			} 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;
    }
};

/*
----------------------------------------
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) 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) {
	var arrDate = date.split('-');
	return arrDate[2]+'/'+arrDate[1]+'/'+arrDate[0];

}
function date_fr2us(date) {
	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;
}
