if (typeof js == "undefined"){
	js = {};
}

js.enkiv3 = new function(){
	
	toutou.config.rootUrl = "/GBjs/"; 
	toutou.require("toutou.event.manager");
	toutou.require("toutou.html.dom");
	toutou.require("toutou.html.layout");
	toutou.require("toutou.js.ajax");
	toutou.require("toutou.js.closure");
	toutou.require("toutou.utils.forms");
	
	this.popoverId = "popover";
	this.ballonPrefix = "ballon";
	this.popoverBgId = "popoverbg";
	this.bgopacity = 50;
	this.bgcolor = "#fff";
	this.dispatcherURL = 'php/php_dispatcher.php';
	this.popoverCssClass = 'popover_success';
	
	/**
	 * Sets of a function after a certain interval of inactivity
	 */
	this.timedKeyEvent = function(inputElementId, module, method, _window) 
	{
		var inputElement = _window.tt$(inputElementId);
		if (inputElement == null) throw new Error("Invalid element id "+inputElementId);
		
		//inputElement.timerId is my timer if
		if (inputElement.timerId>0)
		{
			clearTimeout(inputElement.timerId);
		}
		inputElement.timerId = setTimeout(toutou.js.closure.bind(js.enkiv3,function(){this.checkFormField(inputElementId, module, method, _window)}),250);
	}
	
	/**
	* Checks whether the field's value belonging to form is correct.
	* Sends an ajax request and check for any error property set to 0, if 0 is set then this function tries to remove the ballon if it exists,
	* otherwise if error is set to 1 it displays the ballon if it doesnt already exist    
	*/
	this.checkFormField = function(fieldId, module, method, _window){
		var fieldElement = _window.tt$(fieldId); 
		if(fieldElement == null) throw new Error("Invalid DomElement given");
		//Unset any timer ids
		fieldElement.timerId=0;
		var value = '';
		switch (fieldElement.tagName.toLowerCase()){
			case 'textarea':
			case 'input':
				value = fieldElement.value;
				break;
			case 'select':
				var options = fieldElement.options;
				value = options[fieldElement.selectedIndex].value;	
				break;	
			default:
				return;			
		}
		var options = {
			method : "post",
			postBody : "args="+value+";"+fieldId+"&module="+module+"&method="+method
		}
		var requestResponse = toutou.js.ajax.request(this.dispatcherURL, options);
		var response = eval("("+requestResponse+")");
		if (response['error'] == 0) {
			this.removeFormErrorBallon(fieldElement, _window);
		}
		else {
			this.displayFormErrorBallon(fieldElement, response.content, _window);
		}
	}
	
	/**
	* Submits the form. Uses an ajax request to determine whether all the values are correct. 
	* Whenever one value is incorrect, it displays the error ballon
	* @param url the url of the server page which will answer to the ajax request
	*/
	this.submitForm = function(formId, module, method, _window){
		var formElement = _window.tt$(formId);
		if(formElement == null) throw new Error("Invalid form element");
		var formSerialized = toutou.utils.forms.serializeForm(formElement);
		var options = {
			method : "post",
			postBody : "module="+module+"&method="+method+"&"+formSerialized
		}
		var requestResponse = toutou.js.ajax.request(this.dispatcherURL, options);
		this.handleFormResponse(formId, requestResponse, _window);
		return false;
	}
	
	/**
	* Submits the form. Uses an ajax request to determine whether all the values are correct. 
	* Whenever one value is incorrect, it displays the error ballon
	* @param requestResponse the response returned by the server
	*/
	this.handleFormResponse = function(formId, requestResponse, _window){
		var formElement = _window.tt$(formId);
		var response = eval("("+requestResponse+")");
		for(prop in response['fields']){
			var fieldElement = _window.tt$(prop.toUpperCase());
			if(fieldElement == null) throw new Error("Field element : "+prop+" is null"); 
			if(response['fields'][prop]['error'] == 0){
				this.removeFormErrorBallon(fieldElement, _window);
			}
			else {
				this.removeFormErrorBallon(fieldElement, _window);
				this.displayFormErrorBallon(fieldElement, response['fields'][prop]['content'], _window);
			}
		}
		if(response['error'] == 0){
			formElement.reset();
			// Display the final message
			this.displayFormSuccessPopOver(response['content'], _window);
		}
		return false;
	}
	
	/**
	* Toggles the visivility of an element. If the element doesnt exist an error is raised. In any other case, if the element is visible, then it is *
	* rendered as unvisible and on the contrary if the element is hidden, it is changed to visible
	*/
	this.toggleElementVisibility = function(elementId, _window){
		var el = _window.tt$(elementId);
		if (el == null) throw new Error("Invalid element "+elementId);
		_window.toutou.html.dom.extend(el);
		if (el.tt_isVisible() == true){
			el.tt_setVisibility(false);
			el.style.display = 'none';
		}
		else {
			el.tt_setVisibility(true);
			el.style.display = 'block';
		}
	}
	
	/**
	* Forces the element to render its visibility.
	* If the visible param is set to true then it compells the element to be visible
	* if it is set to false, the element will be set hidden
	*/
	this.forceElementVisibility = function(elementId, visible){
		var el = tt$(elementId);
		if (el == null) throw new Error("Invalid element "+elementId);
		toutou.html.dom.extend(el);
		el.tt_setVisibility(visible);
		var displayProperty = visible == true ? 'block' : 'none';
		el.style.display = displayProperty;
	}
	
	/**
	* Displays a pop over with its content
	*/
	this.displayFormSuccessPopOver = function(content, _window){
		if(_window.tt$(this.popoverBgId) != null) return;
		var bg = _window.document.createElement('div');
		var popover = _window.document.createElement('div');
		popover.setAttribute('class', this.popoverCssClass);
		popover.setAttribute('className', this.popoverCssClass);
		_window.toutou.html.dom.extend(bg);
		_window.toutou.html.dom.extend(popover);
		// Define an id
		bg.setAttribute('id', this.popoverBgId);
		popover.setAttribute('id', this.popoverId);
		
		// Set popover content
		popover.innerHTML = content;
		// Add nodes to body element
		_window.document.body.appendChild(bg);
		_window.document.body.appendChild(popover);
		// Place elements and apply styles to them
		var windowSize = _window.toutou.html.layout.getWindowSize();
		var pageSize = _window.toutou.html.layout.getPageSize();
		var bgWidth = windowSize.width > pageSize.width ? windowSize.width : pageSize.width;
		var bgHeight = windowSize.height > pageSize.height ? windowSize.height : pageSize.height; 
		var bgSize = {
			width : bgWidth,
			height : bgHeight
		} 
		// Bg properties
		bg.tt_setContentSize(bgSize);
		bg.style.position = "absolute";
		bg.tt_setBorderPosition({left:0, top:0});
		bg.style.backgroundColor = this.bgcolor;
		bg.style.zIndex = 99;
		bg.tt_setOpacity(this.bgopacity);
		bg.style.cursor = "pointer";
		
		// Popover properties
		popover.style.cursor = "pointer";
		popover.style.border = "none";
		popover.style.zIndex = 100;
		popover.style.position = "absolute";
		var popoverSize = popover.tt_getContentSize(); 
		if(popoverSize.width <= 0 || popoverSize.height <= 0){
			popoverSize = {
				width : popover.offsetWidth,
				height : popover.offsetHeight
			}
		}
		// Bg and Popover event listener
		bg.onclick = _window.toutou.js.closure.bind(this, function(){
			this.togglePopoverVisibility(_window);
		});
		popover.onclick = _window.toutou.js.closure.bind(this, function(){
			this.togglePopoverVisibility(_window);
		});
		
		
		var popoverLeft = bgWidth/2 - popoverSize.width / 2;
		var popoverTop = bgHeight/2 - popoverSize.height /2;
		var position = {
			left : popoverLeft,
			top : popoverTop
		}
		popover.tt_setBorderPosition(position);
	}
	
	
	/**
	* Toggles the visibility of the popover by setting the appropriate css value for its background and for itself
	*/
	this.togglePopoverVisibility = function(_window){
		if(_window.tt$(this.popoverBgId) == null || _window.tt$(this.popoverId) == null) return;
		this.toggleElementVisibility(this.popoverBgId, _window);
		this.toggleElementVisibility(this.popoverId, _window);
	}
	
	
	/**
	* Remove the error ballon from the DOM.
	* @param formElement
	* @param fieldElement
	*/
	this.removeFormErrorBallon = function(fieldElement, _window){
		var child = _window.tt$(this.ballonPrefix+fieldElement.getAttribute('id'));
		if (child == null) return;
		var fieldContainer = fieldElement.parentNode;
		fieldContainer.setAttribute("class", "true");
		// line below is for IE browser
		fieldContainer.setAttribute("className", "true");
		fieldContainer.removeChild(child);
	}
	
	/**
	* Displays a html ballon before inside formElement and before its child fieldElement
	* @param childElement the reference of child used to set up the ballon before it
	* @param ballonContent the content of the ballon 
	*/
	this.displayFormErrorBallon = function(childElement, ballonContent, _window){
		if(_window.tt$(this.ballonPrefix+childElement.getAttribute('id')) != null) return;
		var ballon = _window.document.createElement("span");
		ballon.setAttribute("id", this.ballonPrefix+childElement.getAttribute('id'));
		ballon.setAttribute("class", "error");
		// line below is for IE browser
		ballon.setAttribute("className", "error");
		ballon.innerHTML = ballonContent;
		var	fieldContainer = childElement.parentNode;
		fieldContainer.setAttribute("class", "false");
		// line below is for IE browser
		fieldContainer.setAttribute("className", "false");
		fieldContainer.appendChild(ballon);
	}
	
	
	
}


js.enkiv3.actuEventsHandler = new function(){
	
	this.NB_NEWS_TO_DISPLAY = 3;
	
	this.addPageNumberButtonEvent = function(){
		// Adding listeners to each news
		var nbEl = this.NB_NEWS_TO_DISPLAY;
		for(var i = 0; i < nbEl; i++){
			var news = tt$('news_'+i);
			var pageNumber = tt$('pnews_'+i);
			if (news == null || pageNumber == null) throw new Error("Bad element either news or pnews expected "+i);
			// Event handler
			pageNumber.onclick = function(){
				for(var i = 0; i < nbEl; i++){
					var currentNews = tt$('news_'+i);
					var currentPage = tt$('pnews_'+i);
					currentNews.setAttribute("class", "home_actu_off");
					currentPage.setAttribute("class", "actu_home_paging_off");
					currentNews.setAttribute("className", "home_actu_off");
					currentPage.setAttribute("className", "actu_home_paging_off");
				}
				var idNumberPart = this.id.substr(this.id.indexOf('_')+1, this.id.length);
				var news = tt$('news_'+idNumberPart);
				news.setAttribute("class", "home_actu_on");
				news.setAttribute("className", "home_actu_on");
				this.setAttribute("class", "actu_home_paging_on");
				this.setAttribute("className", "actu_home_paging_on");
				return false;
			};
		}
		
		
	}
}


js.enkiv3.formEventsHandler = new function(){
	
	/**
	* Adds an event to the select input. Whenever the value of the select changes, the function looks at the value and tests if the value retrieved
	* matches the param value. In this case, the function will invoke the appropriate listener which will apply an action
	* @param callbackMatch is a javascript code which is evaluated when selected value if the list matches value
	* @param callbackNotMatch is a javascript code which is evaluated when selected value if the list doesnt match value
	*/
	this.addFormSelectEvent = function(selectElementId, value, callbackMatch, callbackNotMatch, module, method, _window){
		var selectEl = _window.tt$(selectElementId);
		if(selectEl == null) throw new Error("Invalid element id : "+selectElementId);
		selectEl.onchange = _window.toutou.js.closure.bind(js.enkiv3, function(){
			var options = selectEl.options;
			var selectedOptionValue = options[selectEl.selectedIndex].value;
			this.checkFormField(selectElementId, module, method, _window);
			if(value == selectedOptionValue){
				eval(callbackMatch);
			}
			else {
				eval(callbackNotMatch);
			}
		});
	}
	
	this.addFormSubmitEvent = function(formId, submitId, module, method){
		var submitEl = tt$(submitId);
		var formEl = tt$(formId);
		if(submitEl == null || formEl == null) throw new Error("Invalid element id "+submitId+" or "+formId);
		formEl.onsubmit = function(){
			return false;
		}
		submitEl.onclick = function(){
			js.enkiv3.submitForm(formId, module, method, window);
		}
	}
	
	

	this.addFormKeyEvent = function(inputElementId, module, method, _window)
	{
		var inputElement = _window.tt$(inputElementId);
		if (inputElement == null) throw new Error("Invalid element id "+inputElementId);
		inputElement.onkeyup = toutou.js.closure.bind(js.enkiv3, function()
			{
				this.timedKeyEvent(inputElementId, module, method, _window);
			}
		);
	}
}