
jQuery.behaviors = (function() {
	var behaviors = [];
	return {
		register: function(behavior) { if (typeof behavior == 'function') behaviors.push(behavior); },
		apply:    function(node) {
			if (!node) node = document.body;
			for (var i = 0, iMax = behaviors.length; i < iMax; i++) behaviors[i](node);
		}
	}
})();



jQuery.behaviors.register(function(node) {
	// Pas de formulaire ? Pas la peine de continuer
	var jForm = jQuery("form", node);
	if (!jForm.length) return;
	
	jQuery(":input", jForm).change(App.Forms.checkFieldValidity);
	
	//traitement du blur uniquement si le champs est vide
	jQuery(".inputText", jForm).blur(function(e) {
		if (e.target.value.match(/^\s*$/) !== null)
			App.Forms.checkFieldValidity(e);
	});
	jForm.submit(App.Forms.checkFormValidity);
	
	// Gestion des popup depuis un lien
	jQuery("a.jqPopup", node).click(function(event) {
		jqPopup(event.currentTarget);
		event.stopPropagation();
		return false;
	});
	
	// Permet a un élément interne de provoquer le rechargement
	jQuery('.jqPopupReplace', node).each(function() {
		var jThis = jQuery(this);
		if (this.nodeName == 'FORM') {
			jThis.submit(jqPopupReplace);
		}
		else if (this.nodeName == 'A') {
			jThis.click(jqPopupReplace);
		}
	});
	
	jQuery('a.countableAjaxStand', node).click(function() {
		var id = jQuery(this).attr('id');
		jQuery.get(Dispatch.get15_04, { sid: id}, function(data){});
	});
	
	jQuery('a.countableAjaxOffre', node).click(function() {
		id = jQuery(this).attr('id');
		jQuery.get(Dispatch.get15_05, { pid: id}, function(data){});
	});
});

jQuery(document).ready(function() {
	jQuery.behaviors.apply();
	var lightBox = jQuery('a[rel=lightbox]');
	if (lightBox.length > 0) {
		jQuery('a[rel=lightbox]').lightBox();
	}
	/** pour lancer le lightbox sur une image seule */
	jQuery('.lightboxSimple').click(function(event){
		jQuery(this).lightBox();
		event.stopPropagation();
		jQuery(this).trigger('click');
		return false;
	});
});

Utile = {
	trim: function (str, charlist) {
		var whitespace, l = 0, i = 0;
		str += '';
		if (!charlist) {
		    whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
		} else {
		    charlist += '';whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
		}
		l = str.length;
		for (i = 0; i < l; i++) {
		    if (whitespace.indexOf(str.charAt(i)) === -1) {
		        str = str.substring(i);
		        break;
		    }
		}
		l = str.length;
		for (i = l - 1; i >= 0; i--) {
		    if (whitespace.indexOf(str.charAt(i)) === -1) {
		        str = str.substring(0, i + 1);
		        break;
		    }
		}
		return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
	},
	
	/**
	 * Décode et renvoi un objet contenant les paramètres JS stockées dans la balise params d'un noeud
	 * @param Element element Le noeud Element d'où extraire les paramètres
	 * @param Object toExtend Un eventuel objet a étendre
	 * @return Object
	 */
	getParams: function(element, toExtend) {
		var paramString  = element.getAttribute('params');
		var returnObject = toExtend || {};
		if (paramString == null) return returnObject;
		
		try { eval('var params = {'+paramString+'}'); }
		catch (e) { var params = {}; }

		return jQuery.extend(returnObject, params);
	},	
	
	/**
	 * Renvoi un UID aléatoire et unique
	 * @return string
	 */
	randomUID: function() {
		 return (Math.random()*Math.pow(10, 16)).toString().replace(/^([\.])+.*$/, '$1')+'_'+(new Date().valueOf());
	},	
	
	/**
	 * Gère le redimensionnement automatique des dialogues
	 */
	dialogResize: function(body) {
		
		var jBody 		= jQuery(body),
			jBodyChilds = jBody.children(),
			options     = body.options;
		
		
		if (options.autoWidth || options.autoHeight) {
			
			var width  = body.preCalculedWidth  || -1,
				height = body.preCalculedHeight || -1,
				windowInnerWidth  = window.innerWidth  || document.documentElement.clientWidth,
				windowInnerHeight = window.innerHeight || document.documentElement.clientHeight,
				windowScrollTop   = jQuery(window).scrollTop(),
				windowScrollLeft  = jQuery(window).scrollLeft();
			
			if (width == -1 | height == -1) {
				jBodyChilds.each(function() {
					var jThis = jQuery(this);
					var position = jThis.position();
					width  = Math.max(width,  jThis.width()  + position.left);
					height = Math.max(height, jThis.height() + position.top);
				});
				body.preCalculedWidth  = width;
				body.preCalculedHeight = height;
			}
			
			if (options['maxWidth'])
				width  = Math.min(width, options.maxWidth);
			if (options['maxHeight'])
				height = Math.min(height, options.maxHeight);
			
			if (options['minWidth'])
				width  = Math.max(width, options.minWidth);
			if (options['minHeight'])
				height = Math.max(height, options.minHeight);
			
			// Pas plus grand que la fenêtre elle même , moins 20 pixels autours (20 à gauche et 20 à droite => 40)
			width  = Math.min(windowInnerWidth  - 40, width);
			height = Math.min(windowInnerHeight - 40, height);
			
			var left = (windowInnerWidth  - width)  / 2;
			var top  = (windowInnerHeight - height) / 2;
			if (width)  {
				body.parentNode.style.width  = width+'px';
				body.parentNode.style.left   =  (left + windowScrollLeft)+'px';
				if (jBodyChilds.length == 1) {
					jBodyChilds.get(0).style.width  = width+'px';
				}
			}
			
			if (height) {
				body.parentNode.style.height = height+'px';
				body.parentNode.style.top    = (top + windowScrollTop)+'px';
				if (jBodyChilds.length == 1) {
					jBodyChilds.get(0).style.height     = height+'px';
					jBodyChilds.get(0).dialogAutoHeight = true;
				}
			}
		}
	},	
	
	parseHTTPHeaders: function(string) {
		// Parse HTTP Headers as returned by the server
		var headerLines = string.split("\n"),
			headers = {};
		for (var i = 0; i < headerLines.length; i++) {
			var name = String(headerLines[i]).replace(/^([^:]+):.*$/, '$1');
			if (name == '') continue;
			headers[name] = headerLines[i].replace(/^[^:]+: ?(.*)$/, '$1').replace("\r", "");
		}
		return headers;
	}	
		
}

/**
* @return DOMElement Le conteneur des donnée
*/
jqPopup = function(elem, url, data, callback, options) {
	
	// Création de la div en utilisant DOM car un lag existe dans la synchro
	var body  = document.createElement("div"),
		jBody = jQuery(body);
	
	
	// Traitement des options
	if (!options) options = {};
	var jqThis = jQuery(elem),
		params = Utile.getParams(elem, {popupFrame: false, popupReloadOnClose: false});
	jQuery.extend(params, options);
	if (params['popupAutoResize']) {
		params.popupAutoHeight = true;
		params.popupAutoWidth  = true;
	}
	var options = {
		draggable:   params['popupDraggable']   !== undefined ? params.popupDraggable   : false,
		modal:       params['popupModal']       !== undefined ? params.popupModal       : true,
		resizable:   params['popupResizable']   !== undefined ? params.popupResizable   : true,
		autoOpen:    params['popupAutoOpen']    !== undefined ? params.popupAutoOpen    : true,
		position:    params['popupPosition']    !== undefined ? params.popupPosition    : 'center',
		autoHeight:  params['popupAutoHeight']  !== undefined ? params.popupAutoHeight  : false,
		autoWidth:   params['popupAutoWidth']   !== undefined ? params.popupAutoWidth   : false,
		dialogClass: params['popupDialogClass'] !== undefined ? params.popupDialogClass : 'jqDialogSimple',
		title:		 params['popupTitle']       !== undefined ? params.popupTitle       : '',
		close: function(event, ui) {
			jQuery(elem).dialog("destroy");
			var parentNode = body.parentNode;
			parentNode.removeChild(body);
			parentNode.parentNode.removeChild(parentNode);
		},
		open: function(dialogEvent) {
			jQuery(".ui-widget-overlay").click(function() {
				jQuery(dialogEvent.target).dialog("close");
				if (params.popupReloadOnClose) window.location = window.location;
			});
		}
	};
	
	if (params['popupWidth'])  options.width  = params.popupWidth;
	if (params['popupHeight']) options.height = params.popupHeight;
	if (!callback && params['popupCallback']) {
		callback = window[params['popupCallback']];
	}
	
	body.options = options;
	
	var tmpDivId = (elem.id || Utile.randomUID()) + '_popup',
		tmpDivFrameId = tmpDivId + '_ifrm';
	
	body.id = tmpDivId;
	
	if (!url && elem.nodeName == 'A') {
		url = elem.href.replace('#', ' #');
	}
	
	if (!data) data = null;
	if (params.popupFrame) {
		// Impossible de charger par POST. On envoi les données par GET
		if (data) {
			var serializedData = jQuery.param(data);
			url += url.search(/\?/) === false ? '?' : '&';
			url += serializedData;
		}
		
		jBody.append('<iframe src="'+url+'" style="width:100%;height:100%;border:0;frameborder:0;padding:0;margin:0" id="'+tmpDivFrameId+'" frameBorder="0"></iframe>');
		document.body.appendChild(body);
		jBody.dialog(options);
		if (jQuery.isFunction(callback)) {
			var popupIFrame = document.getElementById(tmpDivFrameId),
				popupWindow = popupIFrame.contentWindow,
				popupDocument = popupIFrame.contentDocument;
			jQuery(popupIFrame).load(callback);
		}
	}
	else {
		if (!data) data = {};
		data.fromJs = true;
		
		if (!jQuery.isFunction(callback)) callback = function(responseText, textStatus, XMLHttpRequest) {
			if (Utile) Utile.dialogResize(body);
			if (jQuery.behaviors) jQuery.behaviors.apply(body);
		}
		jBody.append('<div style="height:100%;background: white url(\'' + window.App.root + 'images/green-ajax-loader.gif\') no-repeat center center">&nbsp;</div>');
		jBody.dialog(options).load(url, data, callback);
	}
	
	// Dans le cas d'un redimensionnement de fenêtre
	jQuery(window).resize(function() {
		Utile.dialogResize(body);
	});
	
	//return body;
	
}

jqPopupReplace = function(event) {
	
	var target	= event.target,
		data	= null,
		url		= null,
		method  = 'GET';
	
	// On recherche la div qui contient les données
	var jBody = jQuery(target).parents('.ui-dialog-content.ui-widget-content');
	if (!jBody) return true;
	var body  = jBody.get(0);
	
	if (target.nodeName == 'FORM') {
		var form  = target,
			jForm = jQuery(target),
			formMethod = form.method.toUpperCase();
		
		data  = jForm.serialize();
		data += (data == '' ? '' : '&')+'fromJs=1';
		url   = form.action ;
		if (formMethod == 'POST') {
			data = Utile.deserialize(data);
		}
		else {
			url += (/\?/.test(url) ? '&' : '?') + data;
		}
	}
	else if (target.nodeName == 'A') {
		url = target.href;
	}
	var randVal = Math.random();
	url += '&rnd=' + randVal;

	jQuery.ajax({
		url: url,
		data: data,
		async: true,
		cache: false,
		type: 'POST',
		success: function(data, textStatus) {
			body.innerHTML = data;
			if (Utile) Utile.dialogResize(body);
			if (jQuery.behaviors) jQuery.behaviors.apply(body);		
		},
		complete: function (XMLHttpRequest, textStatus) {
			var headers = Utile.parseHTTPHeaders(XMLHttpRequest.getAllResponseHeaders());
			if (headers['X-REDIRECT']) {
				window.location.href = headers['X-REDIRECT'];
			}
		}
	});
	
	event.stopPropagation();
	return false; 
	
}
