var core = new function(){

	this.ajaxConf = {type: 'post', dataType: 'html'};
	this.overlayCss = {zIndex: '999', opacity: '0.75', backgroundColor: '#ffffff', backgroundRepeat: 'no-repeat', backgroundPosition: 'center center'};
	this.thickboxConf = {width: 600, height: 400};
	
	/**
	 * @params conf.url
	 * @params conf.content
	 * @params conf.contentId
	 * @params conf.data
	 * @params conf.success
	 */
	this.thickbox = function(conf){
		conf = this._getConf(this.thickboxConf, conf);
		
		var aStr = '<a href="';
		var div = null;
		var a = null;

		if($('#TB_ajaxContent').length){
			$('#TB_ajaxContent').empty();
		}
		
		var wh = 'width='+conf.width+'&height='+conf.height;
		if(typeof(conf.url) != 'undefined'){
			conf.url = this._getUrlWithoutPageWG(conf.url);
			aStr += conf.url+(conf.url.indexOf('?') == -1 ? '?' : '&')+wh;
		}
		else{
			// génération du div qui sera accessible par thickbox
			var contentId = '_'+String(Math.random()).replace('0.', '');
			
			if(typeof(conf.content) != 'undefined'){
				div = $('<div id="'+contentId+'">'+conf.content+'</div>');
				$('body').append(div);
			}
			else if(typeof(conf.contentId) != 'undefined'){
				div = $('#'+conf.contentId).clone().attr('id', contentId);
				$('body').append(div);
			}
			
			if(div){
				aStr += '#TB_inline?'+wh+'&inlineId='+contentId;
			}
		}
		
		if(typeof(conf.data) == 'object'){
			aStr += '&'+$.param(conf.data);
		}
		
		// injection du lien dans le dom
		var id = '_'+String(Math.random()).replace('0.', '');
		a = $(aStr+'" id="'+id+'">test</a>');
		$('body').append(a);
		
		// appels du plugins thickbox
		if(typeof(tb_init) != 'undefined'){
			tb_init('a#'+id);
		}
		a.click();
		
		if(typeof(conf.success) != 'undefined'){
			var time = function(){
				if($('#TB_load').length){
					setTimeout(time, 50);
					return;
				}
				conf.success();				
			};
			time();
		}
		
		// supression des éléments créés
		a.remove();
		if(div){
			div.remove();
		}
	};

	/**
	 * @params location
	 * @params conf.data
	 */
	this.location = function(location, conf){
		if(typeof(location)=='undefined' || !location){
			location = String(window.location);
		}
		var alreadyParams = true;
		if(typeof(conf.data) != 'undefined'){
			if(location.indexOf('?')==-1){
				alreadyParams = false;
				location += '?';
			}
			for(var i in conf.data){
				location += (alreadyParams ? '&' : '')+i+'='+conf.data[i];
				alreadyParams = true;
			}
		}
		window.location = location;
	};

	/**
	 * @params conf.selector
	 * @params conf.url
	 * @params conf.success
	 * @params conf.find
	 */
	this.ajax = function(conf){
		// configuration
		conf = this._getConf(this.ajaxConf, conf);
		
		if(typeof(conf.url) != 'string') return;
		
		// sélecteur jQuery cible
		var jqSel = null;
		if(typeof(conf.selector) != 'undefined'){
			if(typeof(conf.selector) == 'string'){
				jqSel = $(conf.selector);
			}
			else{
				jqSel = conf.selector;
			}
		}
		
		// récupération de l'URL pour la requête
		conf.url = this._getUrlWithoutPageWG(conf.url);
		
		// gestion de l'overlay
		if(jqSel && jqSel.length){
			var overlay = jqSel.children(':eq(0)');
			if(!overlay.hasClass('core_overlay')){
				overlay = $('<div class="core_overlay"></div>');
				overlay.css($.extend({}, this.overlayCss));
				jqSel.css({
					'position': 'relative',
					'z-index': 1
				}).prepend(overlay);
				overlay.height(jqSel.height());
			}
			overlay.show();
		}
		
		var func = null;
		if(typeof(conf.success) != 'undefined'){
			func = conf.success;
		}
		
		// en cas de succès
		conf.success = function(content){
			// détection du json
			if(content.length >= 2 && content.charAt(0)=='{' && content.charAt(content.length-1)=='}'){
				content = window['eval']('('+content+')');
			}
			
			if(jqSel && jqSel.length){
				overlay.hide();
				var html = content;
				
				// s'il s'agit d'un json
				if(typeof(html) == 'object' && typeof(html.content) != 'undefined'){
					html = content.content;
				}
				
				// s'il s'agit de contenu injectable dans le HTML
				if(html && typeof(html) != 'object'){
					// s'il s'agit de balises HTML
					if(typeof(conf.find) == 'string'){
						var find = $('<div>'+html+'</div>').find(conf.find);
						if(find.length){
							html = find.html();
						}
					}
					jqSel.html(html);
				}
			}
			if(func){
				func(content);
			}
		};
		
		// envoi de la requête ajax
		$.ajax(conf);
	};

	/**
	 * @params formElement
	 * @params conf.data
	 * @params conf.thickbox
	 */
	this.submitForm = function(formElement, conf){
		var form = $(formElement);
		
		var formInfos = {
			url: form.attr('action'),
			type: 'post',
			data: form.serializeArray()
		};

		// formInfos.data est un tableau : le $.extend ne fonctionne donc pas
		if(typeof(conf) == 'object' && typeof(conf.data) == 'object'){
			for(var i in conf.data){
				formInfos.data.push({name: i, value: conf.data[i]});
			}
			conf.data = formInfos.data;
			delete formInfos.data;
		}
		
		conf = this._getConf(formInfos, conf);

		if(typeof(conf.thickbox) != 'undefined' && conf.thickbox){
			this.thickbox(conf);
		}
		else{
			conf.selector = form;
			this.ajax(conf);
		}
		return false;
	};

	this._getConf = function(defaults, conf){
		if(typeof(conf) != 'object'){
			conf = {};
		}
		return $.extend({}, defaults, conf);
	};
	
	this._getUrlWithoutPageWG = function(url){
		var posLast = url.lastIndexOf('/');
		var posPrevLast = url.substr(0, posLast).lastIndexOf('/')+1;

		var part1 = url.substr(0, posPrevLast);
		var part2 = url.substr(posPrevLast, posLast-posPrevLast);
		var part3 = url.substr(posLast);

		var tmp = part2.split(',');
		if(tmp.length == 3){
			tmp.shift();
		}
		part2 = tmp.join(',');
		
		return part1+part2+part3;
	};
	
	$('head').append('<style type="text/css">.core_overlay { position: absolute; top: 0px; left: 0px; width: 100%; height: 100% }</style>');
	
};

//var isAuthenticated = null;
//
//var setIsConnected = function(){
//	isAuthenticated = true;
//	$('.de_evenements textarea, .de_evenements input').unbind();
//};
//
//var initConnexion = function(success){
//	var form = $('#TB_window .de_connexion form');
//	if(!form.length)  return false;
//	
//	if(!$.isFunction(success)){
//		success = initConnexion;
//	}
//	var connexionSubmit = function(){
//		var conf = {
//			thickbox: true,
//			success: success
//		};
//		return core.submitForm(this, conf);
//	}
//	form.unbind().submit(connexionSubmit);
//	form.find('input:eq(0)').focus();
//	
//	return true;
//};
//
//var thickboxClose = function(complete){
//	var time = function(){
//		tb_remove();
//		if($.isFunction(complete)){
//			complete();
//		}
//	};
//	setTimeout(time, 1000);
//};
