



function getRessource(key){
	key = key.clean();
	var myRequest = new Request({url:"/templates/default/html/skaaz/ajax/getRessource.jsp" ,data: "key="+encodeURIComponent(key),method: 'get',async: false});
	myRequest.send();
	return (myRequest.response.text.trim());
}

function Commons(){}
Commons = {
	toggleLogPopup: function(){
    	if($('login-container').getStyle('display') == "block")
    		$('login-container').setStyle('display','none');
    	else
    		$('login-container').setStyle('display','block');
	},
	
	toggleFlagDropDown: function(){
		if($('flag-select').getStyle('display') == "block")
    		$('flag-select').setStyle('display','none');
    	else
    		$('flag-select').setStyle('display','block');
	}
}


function Dev(){}
Dev = {
	DEBUG: 0,
	INFO: 1,
	WARN: 2,
	SEVERE: 3,
	
	log: function(obj, severity){
		
		string = "[DEV LOG]" + obj;
		   	if(window.console){
		   		if(typeof obj == "string"){
		   			if(severity == null || severity == Dev.DEBUG)
		   				console.log(obj);
		   			else if(severity == Dev.INFO)
		   				console.info(obj);
		   			else if(severity == Dev.WARN)
		   				console.warn(obj);
		   			else if(severity == Dev.SEVERE)
		   				console.error(obj);
		   		}
		   		else{
		   			console.dir(obj);
		   		}
		   	}
		   	if (window.opera) opera.postError(obj);
		   	//else alert(obj);
	   	
	 }
}

function Utils(){}
/**
* TODO: delete duplicated function (mootools)
*/
Utils = {
	getWindowHeight: function() {
    	return Window.getHeight();
	},
	
	trim: function(str){
		return str.trim();
	},
	
	checkMail: function(mail){
		var reg = new RegExp('^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,4}$','i');
		return reg.test(mail);
	}
}


//load loading picture
if(window.addEvent){
	window.addEvent('domready', function(){
		new Asset.image('/templates/default/html/pictures/common/spinner.gif');
	});
}

/**
* Custom loading item
* @param el Element to hide while loading
*/
 
CurrentLoaders = new Array();
 
function myLoader(el){
	this.background = null;
	this.loader = null;
	this.element = el;
	this.LOADING_PIC_SRC = "/templates/default/html/pictures/common/spinner.gif";
	this.LOADING_PIC_MAXHEIGHT = 48;
	this.LOADING_PIC_MAXWIDTH = 49;
	if(this.element != null)
		this.init();
}

myLoader.killAll = function(){
	CurrentLoaders.each(function(loader){loader.destroy();})
}

myLoader.prototype = {

	init: function(){
		CurrentLoaders.push(this);
		
		this.background = document.createElement("div");
		this.background.className = "custom-loading";
		
		this.loader = document.createElement('img');
		this.loader.setAttribute("alt","loading...");
		this.loader.setAttribute("src",this.LOADING_PIC_SRC);
		
		this.background.appendChild(this.loader);
		
		var pos = this.element.getPosition();
		
		
		var height = this.LOADING_PIC_MAXHEIGHT;
		var width = this.LOADING_PIC_MAXWIDTH;
		
		var size = this.element.getSize();
		if(this.LOADING_PIC_MAXHEIGHT > size.y)
			height = size.y;
		
		if(this.LOADING_PIC_MAXWIDTH > size.x)
			width = size.x;
		
		
		//TODO: calcul par proportion
		if(height < width)
			this.loader.height = height;
		else 
			this.loader.height = width;
			
		this.background.style.position = "absolute";
		this.background.style.left = pos.x + "px";
		this.background.style.top = pos.y + "px";
		
		this.background.style.height = size.y + 2 + "px";
		this.background.style.width = size.x + 2 +  "px";
		
		this.background.style.background = "white";
		this.background.style.opacity = "0.6";
		this.background.style.filter = "alpha(opacity=60)";
		this.background.style.zIndex = "2000";
		
		var mt = (size.y - height) / 2;
		if(mt < 0)
			mt = 0;
		
		this.loader.style.marginTop = mt + "px";
			
		this.load();
		
	},
	
	load: function(){
		//$('content-wide').appendChild(this.background);
		document.body.appendChild(this.background);
	},
	
	destroy: function(){
		if(this.background != null)
			document.body.removeChild(this.background);
		CurrentLoaders.erase(this);
	}

}



/**
* Generate a custom alert box message
* @param text content of the alertBox (could be xHTML)
*/
function myAlert(text, options){
	this.HEIGHT = 400;
	this.options = options || {};
	
	if(options && options.width != null)
		this.WIDTH = this.options.width;
	else
		this.WIDTH = 400;
	this.cont = null;
	this.back = null;
	this.text = text;
	this.globalCont = null;
	this.buttonTxt = "OK";
	this.onDestroy = null;
	
	this.flashObjects = null;
	this.flashEmbed = null;
	
	this.scrollLeft = 0;
	this.scrollTop = 0;
	
	this.oldPositionMethod = null;
	this.oldTopPos = null;
	
	if($('content-skinny') != null)
		this.globalCont = $('content-skinny');
	else if($('content-wide') != null)
			this.globalCont = $('content-wide');
		else
			this.globalCont = document.body;
	
	if(text == null || text=="")
		return false;
			
	this.create();
}

myAlert.prototype = {
	create: function(){
		
		var winHeight = Window.getHeight();
		
		if(this.cont != null)
			this.destroy();
		
		this.cont = document.createElement('div');
		this.cont.className = "genericAlertContainer";
		//this.cont.id = "genericAlertContainer";
    	this.cont.style.height = this.HEIGHT + "px";
   		this.cont.style.width = this.WIDTH + "px";
    	this.cont.style.position = "absolute";
    	this.cont.style.zIndex = "99999999";
    	
    	var content = document.createElement('div');
    	
    	content.innerHTML = this.text;
    	this.cont.appendChild(content);
    	
    	var button = document.createElement('a');
    	button.className = "alert-close";
    	button.appendChild(document.createTextNode("x"));
    	var me = this;
    	
    	button.onclick = function(){
    		me.destroy();
    	}
    	
    	button.onkeypress = function(e){
    		if (!e) var e = window.event;
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			if(code == 13)
    			me.destroy();
    	}
    	
    	this.cont.appendChild(button);
        
    	var top = (winHeight / 2) - (this.HEIGHT / 2);
        top = top + document.documentElement.scrollTop;
    	
    	
    	var left = (this.globalCont.offsetWidth)/2;
    	left -= (this.cont.offsetWidth) / 2;
    	left -= this.WIDTH / 2;
    	
    	if(this.globalCont != document.body)
    	{
	    	var bck = document.createElement('div');
	    	bck.className = "genericAlertBack";
	    	this.back = bck;
	    	this.globalCont.appendChild(bck);
    	
		   	/*Needed for IE*/
		   	bck.style.height = this.globalCont.offsetHeight + "px";
		   	bck.style.width = this.globalCont.offsetWidth + "px";
		   	bck.style.position = "absolute";
		   	bck.style.top = "0";
		   	bck.style.left = "0";
		   	/***/
    	}
    	
    	this.cont.style.left = left + "px";
    	this.cont.style.top = top + "px";
    	this.globalCont.appendChild(this.cont);
    	
    	button.focus();
    	
	    if(this.globalCont.style.position != null && this.globalCont.style.position != ""){
	    	this.oldPositionMethod = this.globalCont.style.position;
	    	if(this.globalCont.style.top != null && this.globalCont.style.top != "")
	    		this.oldTopPos = this.globalCont.style.top;	
	    }
	    
	    this.scrollLeft = document.documentElement.scrollLeft;
	    this.scrollTop = document.documentElement.scrollTop;
	    
	    this.globalCont.style.position = "relative";
	    this.globalCont.style.top = "-" + document.documentElement.scrollTop + "px";
	    
	    document.body.style.height = winHeight + "px";
	    document.body.style.overflow = "hidden";
	    this.cont.style.height = "auto";
	    
	    this.hideFlash();
	},

	/**
	 * set all flash to wmode transparent -- UPDATE: just impossible without reloading all flash...
	 * just hide flash objects while rendering alertbox
	 * Prevent the (no wmode) flash z-index bug
	*/	
	hideFlash: function(){
	    this.flashObjects = document.getElementsByTagName("object");
		this.flashEmbed = document.getElementsByTagName("embed");
		
		if(this.flashObjects != null && this.flashObjects.length > 0)
		for(var i = 0; i < this.flashObjects.length; i++){
			var par = this.flashObjects[i].parentNode;
			par.style.visibility = "hidden";
		}
		
		if(this.flashEmbed != null && this.flashEmbed.length > 0)
		for(var i = 0; i < this.flashEmbed.length; i++){
			var par = this.flashEmbed[i].parentNode;
			par.style.visibility = "hidden";
		}
				
		return false;
	},
	
	showFlash: function(){
		
		if(this.flashObjects != null && this.flashObjects.length > 0)
		for(var i = 0; i < this.flashObjects.length; i++){
			var par = this.flashObjects[i].parentNode;
			par.style.visibility = "visible";
		}
		
		if(this.flashEmbed != null && this.flashEmbed.length > 0)
		for(var i = 0; i < this.flashEmbed.length; i++){
			var par = this.flashEmbed[i].parentNode;
			par.style.visibility = "visible";
		}
		return false;
	},
	
	cancelEvent: function(e){
		e.preventDefault();
		return false;
	},
	
	destroy: function(){
		if(this.oldPositionMethod != null){
			this.globalCont.style.position = this.oldPositionMethod;
			this.globalCont.style.top = this.oldTopPos;
		}
		else{
			this.globalCont.style.position = "";
			this.globalCont.style.top = "";
			window.scrollTo(this.scrollLeft,this.scrollTop);
		}
		
		document.body.style.height = "auto";
		document.body.style.overflow = "visible";
		
		try{
			this.globalCont.removeChild(this.cont);
			this.globalCont.removeChild(this.back);
		}
		catch(e){
			Dev.log(e.message, Dev.WARN);
		}
		
		this.showFlash();
		
		if (this.onDestroy)
			setTimeout(function(){this.onDestroy();}.bind(this), 10);
	}
	
}

/**
* Replace a <select></select> by a custom javascript one
* TODO: create generics CSS for this selectbox
* @param el element to replace
*/
function mySelect(el){
	this.container = null;
	this.list = null;
	this.input = null;
	this.arrowPicSrc = "/templates/default/html/pictures/hompyV2/hompyV2_dropdown.gif";
	this.oldSelect = el;
	this.callback = null;
	
	if(el == null)
		return;
	
	this.listpos = this.oldSelect.getPosition();
	
	this.listShowed = false;
	this.create();
}


mySelect.prototype = {
	create: function(){
		var w = this.oldSelect.offsetWidth;
		this.container = new Element('a', {
										'class': 'mySelectCont',
									    'href': '#',
									    'styles': {
									        'width': w + "px"
									    }
									});
	
		this.selectedContainer = new Element('a', {
											    'class': 'selectedCont',
											    'href': '#'
											});
			
		this.arrowCont = new Element('a', {
									    'class': 'arrowCont',
									    'href': '#'
									});
								
		this.arrow = new Element('img', {
									    'class': 'arrowCont',
									    'src': this.arrowPicSrc,
									    'styles': { 'display': "block" }
									});
		
		this.list = new Element('div', {'class': 'mySelect-list'});
		this.container.setStyle('width',this.oldSelect.offsetWidth + "px");
		this.arrowCont.appendChild(this.arrow);
		this.container.appendChild(this.arrowCont);
		this.container.appendChild(this.selectedContainer);
		
		var me = this;
		this.container.addEvent('click', function(evt){
					me.toogle();
					var e = new Event(evt);
					e.stopPropagation();
					e.preventDefault();	
					return false;
				});
	
		this.selectedContainer.addEvent('click', function(evt){
			me.toogle();
			var e = new Event(evt);
			e.stopPropagation();
			e.preventDefault();	
			return false;
		});
		this.arrowCont.addEvent('click', function(evt){
			me.toogle();
			var e = new Event(evt);
			e.stopPropagation();
			e.preventDefault();
			return false;
		});
		
		this.input = document.createElement('input');
		this.input.setAttribute("type", "hidden");
		this.input.name = this.oldSelect.name;
		this.input.id = this.oldSelect.id;
		
		this.container.appendChild(this.input);
		this.buildLines();
		this.replace();
		return false;
	},
	
	buildLines: function(){
		
		var opt = this.oldSelect.getElementsByTagName('option');
		if(opt != null && opt.length > 0){
			var me = this;
			for(var i = 0; i < opt.length; i++){
				var line = document.createElement('a');
				var val = opt[i].value;
				line.value = val;
				line.innerHTML = opt[i].innerHTML;
				line.href="#";
				line.className = "line";
				line.onclick = function(){
					me.select(this);
					return false;
				}
				if(i == 0 || (opt[i].getAttribute("selected") != null &&  opt[i].getAttribute("selected") == 'true') ){
					if(this.selectedContainer.hasChildNodes()){
						for(var k = 0; k < this.selectedContainer.childNodes.length; k++){
							this.selectedContainer.removeChild(this.selectedContainer.childNodes[k]);			
						}
					}
		
					if(line.hasChildNodes()){
						for(var j = 0; j < line.childNodes.length; j++){
							var childClone = line.childNodes[j].cloneNode(true);
							this.selectedContainer.appendChild(childClone);
						}
					}
					this.input.value = line.value;
				}
				this.list.appendChild(line);
			}
		}
	},
	
	replace: function(){
		this.oldSelect.parentNode.replaceChild(this.container,this.oldSelect);
		this.listpos = this.container.getPosition();
		return false;
	},
	
	select: function(line){
		if(this.selectedContainer.hasChildNodes()){
			for(var i = 0; i < this.selectedContainer.childNodes.length; i++){
				this.selectedContainer.removeChild(this.selectedContainer.childNodes[i]);			
			}
		}
		
		var clone = line.cloneNode(true);
		if(clone.hasChildNodes()){
			for(var i = 0; i < clone.childNodes.length; i++){
				this.selectedContainer.appendChild(clone.childNodes[i]);			
			}
		}
		
		this.input.value = line.value;
		this.toogle();
	}, 
	
	toogle: function(){	
		var me = this;
		if(!this.listShowed){
			document.getElementsByTagName('body')[0].appendChild(this.list);
			this.list.style.position = "absolute";
			this.listPos = this.container.getPosition(); 
			this.list.style.top = this.listPos.y  + 25 + "px";
			this.list.style.left = this.listPos.x + 2 + "px";
			this.list.style.width = this.container.offsetWidth - 2 + "px";
			this.callback = function () {
				me.toogle.call(me);
			};
			$(document.body).addEvent('click', this.callback);
		}
		else{
			this.list.parentNode.removeChild(this.list);
			if(this.callback != null){
				document.body.removeEvent('click', this.callback);
				this.callback = null;
			}
		}
		this.listShowed = ! this.listShowed;
	},
	
	destroy: function(){
		if(this.container.parentNode != null)
			this.container.parentNode.removeChild(this.container);
		if(this.listShowed)
			this.list.parentNode.removeChild(this.list);
	}
}
	
var AuthMg = new Object();
AuthMg.logPopup = null;
AuthMg.ajax = null;
AuthMg.lock = false;
AuthMg = {
	login: function(login, password){
		var args = "login=" + encodeURIComponent(login) + "&password=" + encodeURIComponent(password);
		var u = new Request({url: "/login.do", data: args}).send();
	},
	
	logoff: function(){
		//nop
	},
	
	//TODO: kill all loaders !
	getLoginPopup: function(ajx){
		myLoader.killAll();
		if(AuthMg.lock){
			AuthMg.ajax.push(ajx);
			return;
		}
		
		AuthMg.lock = true;
		AuthMg.ajax = new Array();
		AuthMg.ajax.push(ajx);
		
		var myAjax = new Request({url: "/templates/default/html/skaaz/ajax/authNeededPopup.jsp", method: 'get', isSuccess: function(response){
			AuthMg.logPopup = new myAlert(response);
			AuthMg.logPopup.onDestroy = AuthMg.dispose;
		}}).send();
	},
	
	dispose: function(){
		AuthMg.lock = false;
		AuthMg.ajax = null;
	},
	
	request: function(args){
		Dev.log("Login requested ");
		Dev.log(args);
		var load = new myLoader($(AuthMg.logPopup.cont))
		var u = new Request({url: "/login.do", data: args, isSuccess: function(response){
			load.destroy();
			var res = null;
			try{
				Dev.log(response);
			 	res = Json.evaluate(response);
			 	
			}
			catch(e){
				Dev.log(e.message, Dev.WARN);
			}
			
			if(res == null || res.result != "SUCCESS")
			{
				Dev.log("login failed");
				$('loginPopup-error').setText("");
			}
			else
			{
				Dev.log("login sucess");
				AuthMg.logPopup.destroy();
				//"node was not found" weird error appends here
				for(var i = 0; i < AuthMg.ajax.length; i++)
					AuthMg.ajax[i].request();
				AuthMg.dispose();
			}
		}}).send();
	}
}



/**
* Custom loading item, message version
* @param message
*/
function myMessager(messageText){
	this.background = null;
	this.loader = null;
	this.message = null;
	this.messageText = messageText;
	this.LOADING_PIC_SRC = "/templates/default/html/pictures/common/spinner.gif";
	this.LOADING_PIC_MAXHEIGHT = 48;
	this.LOADING_PIC_MAXWIDTH = 49;
	
	this.init();
}

myMessager.prototype = {

	init: function(){
		this.background = document.createElement("div");
		this.background.className = "custom-loading";
		
		this.loader = document.createElement('img');
		this.loader.setAttribute("alt","loading...");
		this.loader.setAttribute("src",this.LOADING_PIC_SRC);
		this.loader.setAttribute("align","middle");
		
		this.background.appendChild(this.loader);
		this.message = document.createTextNode("  "+this.messageText);
		this.background.appendChild(this.message);
		
		
		
		var height = this.LOADING_PIC_MAXHEIGHT;
		var width = this.LOADING_PIC_MAXWIDTH;
		
		this.background.style.position = "fixed";
		this.background.style.right = "2px";
		this.background.style.bottom = "2px";
		this.background.style.height = "50px";
		//this.background.style.width = "180px";
		
		this.background.style.background = "#dff4ff";
		this.background.style.opacity = "0.6";
		this.background.style.filter = "alpha(opacity=60)";
		this.background.style.zIndex = "2000";
		
				
		this.load();
		
	},
	
	load: function(){
		//$('content-wide').appendChild(this.background);
		document.body.appendChild(this.background);
	},
	
	destroy: function(){
		if(this.background != null)
			document.body.removeChild(this.background);
	}

}


var FakeScroll = new Class({
	
	options: {
		'step': 15,
		'speed': 2,
		'mouseScrollAxe': 'y',
		
		'leftButton':null,
		'rightButton':null,
		'topButton':null,
		'bottomButton':null
	},
	
	initialize: function(el, options){
		this.setOptions(options);
		this.direction = -1;
		this.element = $(el);
		
		this.elementSize = this.element.getSize();
		this.parentSize = this.element.getParent().getSize();
		
		this.initializeButtons();
		this.initializeMouse();
		
	},
	
	initializeButtons: function(){
		var me = this;
		if(this.options.leftButton != null){
			this.options.leftButton = $(this.options.leftButton);
			this.options.leftButton.addEvent('mousedown',function(){
				me.direction = 1;
				me.listenMouseRelease();
				me.scrollX();
			});
		}
		
		if(this.options.rightButton != null){
			this.options.rightButton = $(this.options.rightButton);
			this.options.rightButton.addEvent('mousedown',function(){
				me.direction = -1;
				me.listenMouseRelease();
				me.scrollX();
			});
		}	
		
		if(this.options.topButton != null){
			this.options.topButton = $(this.options.topButton);
			this.options.topButton.addEvent('mousedown',function(){
				me.direction = 1;
				me.listenMouseRelease();
				me.scrollY();
			});
		}
		
		if(this.options.bottomButton != null){
			this.options.bottomButton = $(this.options.bottomButton);
			this.options.bottomButton.addEvent('mousedown',function(){
				me.direction = -1;
				me.listenMouseRelease();
				me.scrollY();
			});
		}
	},
	
	listenMouseRelease: function(){
		var me = this;
		//this.stop = me.scrollStop.bindAsEventListener(me);
		this.stop = function(){
			me.scrollStop.call(me);
		}
		$(document.body).addEvent('mouseup', this.stop);
	},
	
	initializeMouse: function(){
		if (!['x', 'y'].contains(this.options.mouseScrollAxe)){
			his.options.mouseScrollAxe = 'x';
		}
		var me = this;
		this.element.getParent().addEvent('mousewheel',function(evt){
				var event = new Event(evt);
				event.preventDefault();
				if (event.wheel > 0) {
					me.direction = 1;
					me.scrollM();
				}
				else{
					me.direction = -1;
					me.scrollM();
				}
		});	
	},
	
	scrollM: function(){
		if(this.options.mouseScrollAxe == 'x')
			this.stepX();
		else
			this.stepY();
	},
	
	scrollStop: function(){
		this.clearTimer();
		var me = this;
		$(document.body).removeEvent('mouseup',this.stop);
	},
	
	scrollX: function(){
		this.stepX();
		this.timer = this.scrollX.delay(this.options.speed, this);
	},
	
	scrollY: function(){
		this.stepY();
		this.timer = this.scrollX.delay(this.options.speed, this);
	},
	
	stepX: function(){
		try{
			if(
				this.direction < 0 && this.element.getStyle('left').toInt() + this.elementSize.x < this.parentSize.x ||
				this.direction > 0 && this.element.getStyle('left').toInt() + this.options.step > 0
			){
				this.clearTimer();
				return;
			}
			this.element.setStyle('left',this.element.getStyle('left').toInt() + (this.direction * this.options.step) + 'px');
		}	
		catch(e){
			//nop
		}
	},
	
	stepY: function(){
		try{
			if(
				this.direction < 0 && this.element.getStyle('top').toInt() + this.elementSize.y < this.parentSize.y ||
				this.direction > 0 && this.element.getStyle('top').toInt() + this.options.step > 0
			){
				this.clearTimer();
				return;
			}
			this.element.setStyle('top',this.element.getStyle('top').toInt() + (this.direction * this.options.step) + 'px');
		}
		catch(e){
			//nop
		}
	},
	clearTimer: function(){
        $clear(this.timer);
    }
});
FakeScroll.implement(new Chain, new Events, new Options);


/*
Class: Json
	Simple Json parser and Stringyfier, See: <http://www.json.org/>
*/

var Json = {

	/*
	Property: toString
		Converts an object to a string, to be passed in server-side scripts as a parameter. Although its not normal usage for this class, this method can also be used to convert functions and arrays to strings.

	Arguments:
		obj - the object to convert to string

	Returns:
		A json string

	Example:
		(start code)
		Json.toString({apple: 'red', lemon: 'yellow'}); '{"apple":"red","lemon":"yellow"}'
		(end)
	*/

	toString: function(obj){
		switch($type(obj)){
			case 'string':
				return '"' + obj.replace(/(["\\])/g, '\$1') + '"';
			case 'array':
				return '[' + obj.map(Json.toString).join(',') + ']';
			case 'object':
				var string = [];
				for (var property in obj) string.push(Json.toString(property) + ':' + Json.toString(obj[property]));
				return '{' + string.join(',') + '}';
			case 'number':
				if (isFinite(obj)) break;
			case false:
				return 'null';
		}
		return String(obj);
	},

	/*
	Property: evaluate
		converts a json string to an javascript Object.

	Arguments:
		str - the string to evaluate. if its not a string, it returns false.
		secure - optionally, performs syntax check on json string. Defaults to false.

	Credits:
		Json test regexp is by Douglas Crockford <http://crockford.org>.

	Example:
		>var myObject = Json.evaluate('{"apple":"red","lemon":"yellow"}');
		>//myObject will become {apple: 'red', lemon: 'yellow'}
	*/

	evaluate: function(str, secure){
		return (($type(str) != 'string') || (secure && !str.test(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/))) ? null : eval('(' + str + ')');
	}

};
