/* ************************************************
# file    : lib.css.js
# build   : 17
# date	  : 2010-06-13
# def     : css and xhtml librairy
# Copyright Bugpics, dev.bugpics.fr, 2010
************************************************ */

/*
-------------------------------------------------------- */
var pathCssImg = pathBugpics + '/css/img/';

var browserIE6 = false;

var Keys = { TAB: 9, ENTER: 13, ESCAPE: 27, PAGE_UP: 33, PAGE_DOWN: 34, END: 35, HOME: 36, LEFT: 37,
		UP: 38, RIGHT: 39, DOWN: 40
};

/* DOM CSS Functions
-------------------------------------------------------- */

/* Element
-------------------------------------------------------- */
if (!window.ElementJS) {
	ElementJS = new Object();	
}

ElementJS = {
		interval: 25, // seconds
		
		getBrowserWidth: function(){
			var d = document.documentElement;
			var w = window.innerWidth || self.innerWidth || (d&&d.clientWidth) || document.body.clientWidth;
			return w;
		},
		
		getBrowserHeight: function(){
			var d = document.documentElement;
			var h = window.innerHeight || self.innerHeight || (d&&d.clientHeight) || document.body.clientHeight;
			return h;
		},
		
		getLeft: function(element) {
			var offsetLeft = 0;
			while(element != null) {
				offsetLeft += element.offsetLeft;
				element = element.offsetParent;
			}
			return offsetLeft;
		},
		
		getTop: function(element) {
			var offsetTop = 0;
			while(element != null) {
				offsetTop += element.offsetTop;
				element = element.offsetParent;
			}
			return offsetTop;
		},
			
		getChildElements: function(element, tagName) {
			var result = new Array();
			var name = tagName.toLowerCase();
			for (var i=0; i<element.childNodes.length; i++) {
				var child = element.childNodes[i];
				if (child.nodeType == 1) {
					if (name == "*" || child.nodeName.toLowerCase() == name) {
						result.push(child);
					}
				}
			}
			return result;
		},

		create: function(type,id,content,style) {	
			var result = document.createElement(type.toLowerCase());
			result.setAttribute('id',id);
			if (content) result.innerHTML = content;
			if (content) result.setAttribute('style',style);
		
			return result;
		},

		append: function(parent, type, id, content, style) {	
			var result = ElementJS.create(type, id, content, style);
			if (!parent || parent == '' || parent == 'body')
				document.body.appendChild(result);
			else
				document.getElementById(parent).appendChild(result);
			
			return result;
		},
		
		opacity: function(element, opacity) {
			element.style.opacity = opacity/100;
			element.style.filter = "alpha(opacity=" +opacity+ ")";
			return;	
		},	

		fade: function(element_id, opacityStart, opacityEnd, time, reload) {
			reload = reload || false;
			if (typeof(functionEnd) == "function") finishFunction = functionEnd;
			if (!reload) time = parseInt(time*1000/this.interval)*this.interval;
			var nbInterval = parseInt(time/this.interval);
			var element = document.getElementById(element_id);			
			if (!element) return;
			ElementJS.opacity(element,opacityStart);
	
			opacityStart = parseInt(opacityStart - (opacityStart-opacityEnd)/nbInterval);			
			time -= this.interval;
			if (time > 0)
				setTimeout("ElementJS.fade(\""+element_id+"\","+opacityStart+","+opacityEnd+","+time+",true)", this.interval);
			else {
				if (opacityStart < 5) document.body.removeChild(element);
			}
		}				
};

/* Event
-------------------------------------------------------- */
if (!window.Event) {
	Event = new Object();	
}

Event = {
	event: function(event) {
		// W3C or IE
		return (event || window.event);
	},

	target: function(event) {
		return (event) ? event.target : window.event.srcElement;
	},

	preventDefault: function(event) {
		var event = event || window.event;
		// W3C
		if (event.preventDefault) {
			event.preventDefault();
		}
		// IE
		else {
			event.returnValue = false;
		}
	},

	stopPropagation: function(event) {
		var event = event || window.event;
		if (event.stopPropagation) {
			event.stopPropagation();
		}
		else {
			event.cancelBubble = true;
		}
	}
};

/* Custom alert box
-------------------------------------------------------- */
if(document.getElementById) {
	window.alert = function(txt) {
		var params = {
			title : "Alerte",
			icon: 2,
			center: 1,
			content: txt
		};
		cssBox.show(params);
	};
}

/* Css box
-------------------------------------------------------- */
if (!window.cssBox) {
	cssBox = new Object();
}

cssBox = {
	divHideSelect: null,
	divOverlay: null,
	divWindow: null,
	divForm: null,
	functionSubmit: null,
	functionCancel: null,
	values: null,

	show: function(params) {

		try {
			var clearBox = new Array("cssBoxHideSelect", "cssBoxOverlay", "cssBoxWindow");
			for (id in clearBox) {
				var element = document.getElementById(id);
				if (element) document.body.removeChild(element);
			}
			
			var box = this;
			this.functionCancel = null;
			this.functionSubmit = null;
			this.values = null;
			
			params = (params) ? params : new Object;
			// Div definition
			// Detect IE6
			if (typeof document.body.style.maxHeight === "undefined") browserIE6 = true;
			
			if (browserIE6) {
				//iframe to hide select elements in ie6
				this.divHideSelect = ElementJS.append('','iframe','cssBoxHideSelect');
				this.divOverlay = ElementJS.append('','div','cssBoxOverlay');
				this.divWindow = ElementJS.append('','div','cssBoxWindow');
			}
			else {
				this.divOverlay = ElementJS.append('','div','cssBoxOverlay');
				this.divWindow = ElementJS.append('','div','cssBoxWindow');
			}		
			
			// Form : Contruct content
			if (params.form) {
				var submitText = (params.submitText) ? params.submitText : "Submit";
				var cancelText = (params.cancelText) ? params.cancelText : "Cancel";
				
				if (parseInt(params.maxtabindex) == 0) params.maxtabindex = 20;
				var reset = "";
				if (params.reset) reset = "<span class='cssBoxButtonSpan'>Reset</span><input type='reset' class='cssBoxButton reset' value='' tabindex='"+(params.maxtabindex+2)+"'/>";
				params.content = "<form action='#' id='"+params.form+"'>"+params.content+
					"<div id='cssBoxButtons'><span class='cssBoxButtonSpan'>"+cancelText+"</span><input id='cssBoxCancelButton' type='button' class='cssBoxButton cancel' value='' tabindex='"+(params.maxtabindex+1)+"'/>" +
					reset +
					"<span class='cssBoxButtonSpan'>"+submitText+"</span><input id='cssBoxSubmitButton' type='button' class='cssBoxButton submit' value='' tabindex='"+(params.maxtabindex+3)+"'/></div>"
					+ "</form>";
				if (typeof(params.submitFunction) == "function") this.functionSubmit = params.submitFunction;				
			}
			else {
				if (params.validFunction) {
					params.content = params.content + "<div id='cssBoxButtons'><span class='cssBoxButtonSpan'>Valid</span>" +
					"<input type='button' id='cssValidButton' class='cssBoxButton submit' value=''/></div>";
					this.functionSubmit = params.validFunction;
				}
			}
			
			// Construct window
			var title = params.title;
			if (params.icon) {
				if (parseInt(params.icon) > 0) {
					switch(params.icon)	{
					case 4:
						params.icon = pathCssImg+'cssBox_new.png';
						break;
					case 3:
						params.icon = pathCssImg+'cssBox_edit.png';
						break;
					case 2:
						params.icon = pathCssImg+'cssBox_error.png';
						break;
					default:
						params.icon = pathCssImg+'cssBox_info.png';
						break;
					}					
				}
				title = "<img src='"+ params.icon +"' alt=''/> "+title;
			}
			this.divWindow.innerHTML = "<div id='cssBoxTitle'><div id='cssBoxClose'> </div><div class='cssBoxButtonSpan right'>Exit</div>"
			+title+"</div><div id='cssBoxCaption'>"+params.content+"</div>";
			var divClose = document.getElementById("cssBoxClose");
			
			if(params.center) document.getElementById('cssBoxCaption').style.textAlign = 'center';
				
			// Opacity
			if (!browserIE6) ElementJS.opacity(this.divOverlay,50);
			
			// Size and position
			if (!params.width) params.width = 400;
			if (!params.height) params.height = 100;
			
			this.divWindow.style.width = params.width+"px";
			this.divWindow.style.height = params.height+"px";
			
			if (browserIE6) {
				this.divWindow.style.position = "absolute";
				this.divWindow.style.top = document.documentElement.scrollTop + 200;			
				this.divWindow.style.left = 200;
			}
			else {
				this.divWindow.style.marginLeft = "-"+parseInt(params.width/2)+"px";
				this.divWindow.style.marginTop = "-"+parseInt(params.height/2+50)+"px";
			}
			
			// Functions
			if (typeof(params.cancelFunction) == "function") this.functionCancel = params.cancelFunction;
			
			// Behaviour
			divClose.onclick = function() {
				box.remove();
			};
			this.divOverlay.onclick = function() {
				box.remove();
			};
			document.onkeydown = function(aEvent) {
				box.onkeydown(aEvent);
			};
			if (params.form) {
				this.divForm = document.getElementById(params.form);
				document.getElementById("cssBoxSubmitButton").onclick = function(){
					box.actionForm(true);
				};
				document.getElementById("cssBoxCancelButton").onclick = function(){
					box.remove();
				};
			}
			else {
				if (params.validFunction) {
					document.getElementById("cssValidButton").onclick = function(){
						box.actionForm(false);
					};
				}
			}
			
			// Show box
			this.divWindow.style.display = "block";
			
			if (params.time) setTimeout("cssBox.remove()",parseInt(params.time)*1000);		
		}
		catch (e) {
				//
		}
	},

	onkeydown: function(aEvent) {
		var event = Event.event(aEvent);
		switch (event.keyCode) {
		case Keys.ESCAPE:
			cssBox.remove();
			break;
		default:
		}
	},	
	
	remove: function(submit) {
	
		submit = (submit === true) ? true : false;
		
		if (document.getElementById("cssBoxWindow") !== null) {
			document.body.removeChild(this.divWindow);
			if (browserIE6) {
				document.body.removeChild(this.divOverlay);
				document.body.removeChild(this.divHideSelect);
			}
			else
				ElementJS.fade("cssBoxOverlay",50,0,0.15);
			
			if (this.functionCancel !== null && !submit) this.functionCancel();
		}
	},

	actionForm: function(form) {
		if (form) {
			this.values = this.divForm.elements;
			this.divForm = null;
		}
		if (this.functionSubmit !== null) this.functionSubmit();		
		this.remove(true);
	},
	
	formValues: function() {	
		var results = new Array();
		var form = this.values;
		this.values = null;

		if (form) {
			for (var field in form) {
				if (form[field]) {
					switch(form[field].type) {
					case 'checkbox':
						if (form[field].checked) results[form[field].name] = 1;
						else results[form[field].name] = 0;
						break;
					case 'radio':
						if (form[field].checked) results[form[field].name] = form[field].value;
						break;
					default:
						results[form[field].name] = form[field].value;
						break;
					}
				}
			}
		}	

		return results;
	}
};

//Ajax functions
//------------------------------------------------------------------

if (!window.Ajax) {
	Ajax = new Object();	
}

Ajax = {
	requete: null,
	animation: null,
	process: null,
	
	request: function(file, send, processFunction, animateFunction, method){
	
		if (typeof(processFunction) == "function") 
			this.process = processFunction;
		else
			this.process = null;
		
		this.requete = this.getRequete();
		
		if (this.requete != null && file != "") {
			try {
				var send = (send) ? send : "";
				var method = (method) ? method : "POST";
				var current = this;
				
				if (typeof(animateFunction) == "function") 
					this.animation = animateFunction;
				else 
					this.animation = null;
				
				this.requete.open(method, file, true);
				this.requete.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				this.requete.onreadystatechange = function() {
					if (current.requete.readyState == 4 && current.requete.status == 200) {
						if (current.requete.responseText) {
							if (current.process) 
								current.process(current.requete.responseText);
						}
						if (current.animation) current.animation(0);
					}
				};
				this.requete.send(send);
				
				if (this.animation) this.animation(1);
			} 
			catch (exc) {
				if (this.animation) this.animation(0);
			}
		}
	},
		
	getRequete: function(){
		var result = this.requete;
		if (result == null) {
			if (window.XMLHttpRequest) {
				result = new XMLHttpRequest();
			}
			else 
				if (window.ActiveXObject) {
					result = new ActiveXObject("Microsoft.XMLHTTP");
				}
		}
		return result;
	}
};

/* Popup List
-------------------------------------------------------- */

/* Popup object
-------------------------------------------------------- */
function PopupList(source, selectOptionFunction, fixed) {
	
	fixed = (fixed === true) ? true : false;
	this.list = document.createElement("div");
	document.body.appendChild(this.list);
	this.index = -1;
	this.source = source;
	this.selectOption = selectOptionFunction;
	
	this.setLayout(fixed);
	this.hide();
	this.setBehaviour();
}

PopupList.prototype.constructor = PopupList;

PopupList.prototype = {
	// Init popup
	setLayout: function(fixed) {
		this.list.style.background = "window";
		this.list.style.border = "solid 1px WindowText";
		this.list.style.padding = "2px";
		this.list.style.zIndex = "104";
		var left = (ElementJS.getLeft(this.source) + 5) + "px";
		var top = (ElementJS.getTop(this.source) + this.source.offsetHeight + 6) + "px";

		if (fixed === true) {
			this.list.style.position = "fixed";
			this.list.style.top = 0;
			this.list.style.left = 0;
			this.list.style.marginLeft = left;
			this.list.style.marginTop = top;
		}
		else {
			this.list.style.position = "absolute";
			this.list.style.left = left;
			this.list.style.top = top;			
		}	
	},
	// Clear options
	clear: function() {
		this.list.style.display = "none";
		this.list.innerHTML = "";
		this.index = -1;
	},
	// Display
	display: function() {
		if(this.list.childNodes.length > 0) {
			this.list.style.display = "block";
		}
	},
	// Hide
	hide: function() {
		this.list.style.display = "none";
	},
	// Visible
	isVisible: function() {
		return this.list.style.display != "none";
	},
	// Options
	setOptions: function(values) {
		this.clear();
		if (values.length > 0) {
			var div;
			
			for (var i=0; i<values.length; i++) {
				div = document.createElement("div");
				div.innerHTML = values[i];
				this.list.appendChild(div);
				
				div.setAttribute("index",i);
				div.className = "option";
			}
			this.display();
		}
	},
	// Behavior
	setBehaviour: function() {
		var current = this;
		this.list.onmouseover = function(event) {
			var target = Event.target(event);
			if (target.className == "option") {
				current.go(target.getAttribute("index"));
				Event.stopPropagation(event);
			}
		};
		this.list.onmouseout = function(event) {
			current.go(-1);
		};
		this.list.onclick = function(event) {
			current.source.value = Event.target(event).innerHTML;
			current.select();
			current.clear();
			current.source.focus();
		};
	},
	// Active
	go: function(index) {
		var divs = this.list.childNodes;
		// Deselect active option
		if (-1 < this.index && this.index < divs.length) {
			divs[this.index].style.background = "Window";
			divs[this.index].style.color = "WindowText";
			divs[this.index].style.cursor = "default";
		}
		// update index
		if (-1 < index && index < divs.length) {
			this.index = index;
		}
		else if (index <= -1) {
			this.index = -1;
		}
		else {
			this.index = divs.length - 1;
		}
		// over
		if (this.index != -1) {
			divs[this.index].style.background = "Highlight";
			divs[this.index].style.color = "HighlightText";
			divs[this.index].style.cursor = "pointer";
		}
	},
	
	// Value
	getValue: function() {
		return (0 <= this.index && this.index < this.list.childNodes.length) ? this.list.childNodes[this.index].innerHTML : "";
	},
	
	// Length
	getLength: function() {
		return this.list.childNodes.length;
	},
	
	select: function() {
		if (typeof(this.selectOption) == "function") {
			this.selectOption(this.source.id);
		}
	}
};

/* Suggest object
-------------------------------------------------------- */
function HttpSuggest(idField, getValuesUrl, selectOptionFunction, positionFixed, maxSuggestNumber) {
	positionFixed = (positionFixed === true) ? true : false;	
	this.url = getValuesUrl;
	if (this.url.indexOf("?") == -1) {
		this.url += "?";
	}
	else {
		this.url += "&";
	}
	this.request = new XMLHttpRequest();
	
	this.source = document.getElementById(idField);
	this.id = idField;

	this.maxSuggestNumber = (maxSuggestNumber) ? maxSuggestNumber : 10;
	this.popup = new PopupList(this.source, selectOptionFunction, positionFixed);
	this.inputValue = "";
	this.setBehaviour();
}

HttpSuggest.prototype.constructor = HttpSuggest;

HttpSuggest.prototype = {		
	setBehaviour: function() {
		// cancel browser function
		this.source.setAttribute("autocomplete","off");
		var suggest = this;

		this.source.onkeyup = function(aEvent) {
			suggest.onkeyup(aEvent);
		};
		this.source.onkeydown = function(aEvent) {
			suggest.onkeydown(aEvent);
		};
		this.source.onblur = function(aEvent) {
			if (suggest.popup.index == -1) {
				suggest.popup.hide();
			}
		};	
	},

	onkeydown: function(aEvent) {
		var event = Event.event(aEvent);
		switch (event.keyCode) {
		case Keys.ESCAPE:
			this.popup.hide();
			break;
		case Keys.ENTER:
			if (this.popup.isVisible()) {
				Event.preventDefault(event);
				this.popup.select();
				this.popup.clear();
			}
			break;
		case Keys.TAB:
			this.popup.clear();
			break;
		case Keys.DOWN:
			this.goAndGet(this.popup.index+1);
			break;
		case Keys.UP:
			this.goAndGet(this.popup.index-1);
			break;
		case Keys.PAGE_UP:
			this.goAndGet((this.popup.getLength() > 0) ? 0 : -1);
			break;
		case Keys.PAGE_DOWN:
			this.goAndGet(this.popup.getLength()-1);
			break;
		default:
			//
		}
	},
	
	goAndGet: function(index) {
		this.popup.go(index);
		if (-1 < this.popup.index) {
			this.source.value = this.popup.getValue();
		}
		else {
			this.source.value = this.inputValue;
		}
	},
	
	onkeyup: function(aEvent) {
		switch (Event.event(aEvent).keyCode) {
		case Keys.DOWN: case Keys.UP: case Keys.PAGE_UP: case Keys.HOME: case Keys.PAGE_DOWN:
		case Keys.END: case Keys.ENTER: case Keys.ESCAPE:
			break;
		default:
			this.inputValue = this.source.value;
			this.setOptions();
		}
	},
	
	setOptions: function() {
		try { this.request.abort(); }
		catch(exc) {}
		
		try {
			var url = this.url + "search=" + encodeURIComponent(this.source.value) + "&size="+this.maxSuggestNumber;
			this.request = new XMLHttpRequest();
			this.request.open("GET",url,true);
			
			var suggest = this;
			this.request.onreadystatechange = function() {
				try {
					if (suggest.request.readyState == 4 && suggest.request.status == 200) {
						if (suggest.request.responseText != "") {
							var values = suggest.request.responseText.split("\n");
							suggest.popup.setOptions(values);
						}
					}
				}
				catch(exc) {}
			};
			this.request.send(null);
		}
		catch (exc) { }
	}
};

/* Slide objects
-------------------------------------------------------- */
function slideObjects(idScreen, idMenu, objectFct, slideTime, slideSpeed, slideWay, objectTag) {
	
	this.screen = document.getElementById(idScreen);
	this.menu = document.getElementById(idMenu);
	this.functions = objectFct;
	
	// Time in s
	this.time = (slideTime) ? parseInt(slideTime) : 0;
	this.speed = (slideSpeed) ? parseInt(slideSpeed) : 20;
	
	// slideWay : 0=r2l, 1=d2u, 3=l2r, 4=u2d
	switch (slideWay) {
		case 1:
			this.xadd = 0;
			this.yadd = -1;
			break;
		case 2:
			this.xadd = -1;
			this.yadd = 0;
			break;
		case 3:
			this.xadd = 0;
			this.yadd = 1;
			break;
		default:
			this.xadd = 1;
			this.yadd = 0;
	}	
	
	this.tag = (objectTag) ? objectTag : "img";

	this.initObjects();
	if (this.time) this.initTimer();
}

slideObjects.prototype.constructor = slideObjects;

slideObjects.prototype = {
	slideon: false,
	w: 0,
	h: 0,
	objects: new Array(),
	buttons: new Array(),
	nbObjects: 0,
	currentObject: 0,
	nextObject: 1,
	position: 0,
	maxPosition: 0,
	hashsettime: 1,
	
	initObjects: function() {
		var classe = this;
		this.objects = ElementJS.getChildElements(this.screen,this.tag);
		this.nbObjects = this.objects.length;
		var pos = 0;
			
		for (var i=0; i< this.nbObjects; i++) {
			this.objects[i].style.zindex = i+1;
			this.objects[i].style.position = "absolute";

			if (i > 0) {
				this.objects[i].style.display = "none";
				pos = 1;
			}
			else {
				this.w = this.objects[i].clientWidth;
				this.h = this.objects[i].clientHeight;
				this.objects[i].style.display = "";
				pos = 0;
			}
			
			this.objects[i].style.top = (pos*this.h*this.yadd)+"px";
			this.objects[i].style.left = (pos*this.w*this.xadd)+"px";
			this.objects[i].setAttribute("index",i);
			
			if (this.functions.objectClick) {
				this.objects[i].onclick = function(){
					classe.functions.objectClick(this.getAttribute("index"));
				};
			}
		}
		this.maxPosition = this.h*this.yadd + this.w*this.xadd;
		
		this.buttons = ElementJS.getChildElements(this.menu,"div");
		for (var i = 0; i < this.nbObjects; i++) {
			this.buttons[i].setAttribute("index",i);
			
			this.buttons[i].onclick = function() {
				classe.select(this.getAttribute("index"),0);
			};
		}
		
		this.functions.objectOn(this.objects[0],this.buttons[0]);		
	},
	
	initTimer: function() {
		this.setTime(1,this.time*1000/2);		
	},
	
	setTime: function(n,time) {
		this.hashsettime++;
		var classe = this;
		var hash = this.hashsettime;
		setTimeout(function(){ classe.select(n,hash); },time);			
	},

	select: function(n,hash) {
		var c = this.currentObject;
		if (this.slideon || n == c || (hash != 0 && hash != this.hashsettime)) return;

		this.slideon = true;
		if (n < 0) n = this.nbObjects-1;
		if (n >= this.nbObjects) n = 0;
		
		this.position = 0;
		this.nextObject = n;
		
		if (this.functions.objectOff) this.functions.objectOff(this.objects[c],this.buttons[c]);
		this.objects[n].style.display = "";
		this.slide();
	},

	slide: function() {
		var n = this.nextObject;
		var c = this.currentObject;
		
		var end = false;
		this.position += parseInt(this.maxPosition/1000*this.speed);
		
		if (this.position > this.maxPosition) {
			end = true;
			this.position = this.maxPosition;
		}
		this.objects[c].style.left = -this.position+"px";
		this.objects[n].style.left = (this.maxPosition-this.position)+"px";
		
		var classe = this;		
		if (!end) {
			setTimeout(function(){ classe.slide(); }, 20);
		}
		else {
					
			this.objects[c].style.display = "none";
			this.objects[c].style.left = (this.w*this.xadd)+"px";
			
			this.currentObject = n;
			if (this.functions.objectOn) this.functions.objectOn(this.objects[n],this.buttons[n]);
			n++;
			if (this.time) this.setTime(n,this.time*1000);
			this.slideon = false;
		}
	}
	
	
};

