function t41_Controller(url) {
	
	this._backendUrl = url || '/t41/xml';
	
	this._async = true;
	
	this.setBackendUrl = function(url) {
		
		this._backendUrl = url;
		this._ajaxInit();
	}
	
	this.getBackendUrl = function () {
		return this._backendUrl;
	}
	
	this.init = function() {
		
		jQuery.noConflict();
		this._ajaxInit();
	}

    this._errorFunc = function (t) {
        alert('Erreur : ' + t.message);
        return false;
    }
    
	this._successFunc = function(t) {
		return t.responseText;
    }
	
	this._ajaxInit = function() {
		
		jQuery.ajaxSetup({
			url: this._backendUrl
		,	global: false
		,	type: "POST"
		,	dataType: "json"
		});		
	}
	
	this.ajaxSetAsync = function(mode) {
			
		this._async = mode;
	}

	this._ajaxSetSuccessHandler = function(f) {
		this._successFunc = f;
	}

	this._ajaxSetErrorHandler = function(f) {
		this._errorFunc = f;
	}
	
	this.ajaxCall = function(func, controller, dataset) {

		_args = { data: dataset, error: this._errorFunc };
    	
    	if (this._async == true) {
    		
    		_args['success'] = this._successFunc;
    		jQuery.ajax(_args);
    		
    	} else {
    		
    		_args['async'] = false;
    		res = jQuery.ajax(_args);
    		
    		jsonRet = eval('(' + res.responseText + ')');
    	
    		if (typeof(jsonRet) != 'object') {
    			alert(typeof(jsonRet));
    			alert('ERREUR: ' + res.responseText);
    			return false;
    		}
    		
    		switch (jsonRet.status) {
    		
    		case 'OK':
    			return (returned == 2) ? jsonRet : res.responsetext;
    			break;
    			
    		case 'NOK':
    			alert('ERREUR : ' + jsonRet.message);
    			return false;
    			break;
    			
    		case 'ERR':
    			alert('PB SERVEUR : ' + jsonRet.message);
    			return false;
    			break;
    		}
    	}		
	}
}


function t41_init(baseUrl) {
	
	if (! baseUrl) baseUrl = "/t41/xml";
	
	/** Prevent conflicts with other Js Library **/
	jQuery.noConflict();
	
	/** AJAX Setup **/
	jQuery.ajaxSetup({
						url: baseUrl
					,	global: false
					,	type: "POST"
					,	dataType: "json"
					});
	
	
	const t41_env_loaded = true;
}

/**
 * Ajax request object based on jQuery
 * 
 * @param url
 * @return
 */
function t41_ajax(url, func, controller) {

	/**
	 * URL de destination
	 */
	this._url  = url || t41_Controller.getBackendUrl();
	
	this._func = func;
	
	this._controller = controller;
	
	this._async = true;
	/**
	 * Message d'attente
	 */
	this.waitMsg = 'Requ�te en cours - Veuillez patienter';

	/**
	 * Switch du panneau d'attente
	 */
	this.waitPanel = true;
	
	/**
	 * Fonction de callback � ex�cuter pour activer l'attente
	 */
	this.waitFunc = null;
	
	/**
	 * Data array sent with query
	 */
	this.data = new Array();

	
	this.setAsync = function (mode) {
		
		this._async = mode;
	}
	
	
	/**
	 * Fonction invoquee en cas d'erreur
	 */
    this.errorFunc = function (t) {
        alert('Erreur : ' + t.message);
        return false;
    }
    
    /**
     * Fonction invoqu�e en cas de succ�s
     * @return string
     */
	this.handlerFunc = function(t) {
		return t.responseText;
    }    
    
	
	/**
	 * 
	 */
	this.setErrorHandler = function(f) {
		this.errorFunc = f;
	}
	
	
	/**
	 * @param string key
	 * @param mixed val
	 */
	this.addData = function (key, val) {
		
		this.data[key] = val;
	}
	
	
	this.setSuccessHandler = function(f) {
		this.handlerFunc = f;
	}


    this.exec = function(returned) {
    	
    	/*
    	 * 1 = asis
    	 * 2 = json 
    	 */
    	returned = returned || 2;
    	
    	if (this.waitPanel == true) {
    		this._waitScreen();
    	}
    	
    	_args = { type: 'POST', url: this._url, data: this._prepareData(), error: this.errorFunc };
    	
    	if (this._async == true) {
    		
    		_args['success'] = this.handlerFunc;
    		jQuery.ajax(_args);
    		
    	} else {
    		
    		_args['async'] = false;
    		_args['dataType'] = 'json';
    		res = jQuery.ajax(_args);
    		
    		jsonRet = eval('(' + res.responseText + ')');
    	
    		if (typeof(jsonRet) != 'object') {
    			alert(typeof(jsonRet));
    			alert('ERREUR: ' + res.responseText);
    			return false;
    		}
    		
    		switch (jsonRet.status) {
    		
    		case 'OK':
    			return (returned == 2) ? jsonRet : res.responsetext;
    			break;
    			
    		case 'NOK':
    			alert('ERREUR : ' + jsonRet.message);
    			return false;
    			break;
    			
    		case 'ERR':
    			alert('PB SERVEUR : ' + jsonRet.message);
    			return false;
    			break;
    		}
    	}
    }

    
    this._waitScreen = function() {
    	
    	if (this.waitFunc) {
    		eval(this.waitFunc);
    	} else {
    	}
    }
    
    this._prepareData = function() {
    		
    	var post = '';
    	
    	if (this._func) post += 't41_func=' + escape(this._func);
    	if (this._controller) post += 't41_controller=' + escape(this._controller);
    	
    	for (var key in this.data) {
    		
    		if (typeof(this.data[key]) == 'function') continue;
    		
    		if (post) post += '&';
    		post += key + '=';
    		post += (typeof(this.data[key]) == 'object') ? JSON.encode(this.data[key]) : encodeURIComponent(this.data[key]);
    	}
    		
    	return post;
    }
}


function t41_format(str, format, entities) {

	entities = (entities == null) ? true : false;

	switch (format) {
	
		case 'CURRENCY':
		    num = str.toString();
		    sep = num.split('.');
		    dec = (sep.length == 1) ? '00' : sep[1].substring(0, 2);
		    if (dec.length == 1) dec += '0';

		    return entities ? sep[0] + ',' + dec + '&nbsp;&euro;' : sep[0] + ',' + dec + ' \u20AC';
		    break;

		case 'DATE':
		    var part = str.split(" ");

		    var elem = part[0].split('-');
		    var str = elem[2] + '/' + elem[1] + '/' + elem[0];
		    return str;
		    break;
		    
		case 'DATEHOUR':
		    var part = str.split(" ");

		    var elem = part[0].split('-');
		    var str = elem[2] + '/' + elem[1] + '/' + elem[0];

		    if (part[1]) {
		        var elem = part[1].split(':');
		        str += ' ' + elem[0] + 'h' + elem[1];
		    }
		    return str;
		    break;
		    
		default:
		    return str;
		    break;
		}
}

/**
 * This class has been moved into its own file 'matcher.js' as t41_matcher2
 * @param dataPool
 * @return
 */
function t41_matcher(dataPool) {
	
	this.req = new t41_ajax('/t41/ajax/match');
	this.req.addData('datapool', dataPool);
	
	this.exec = function(relationKey, enable) {
		this.req.addData('relation', relationKey);
		this.req.addData('enable', enable);
		this.req.exec();
	}
	
	this.toggle = function(link, hidden) {
		
		element = document.getElementById(hidden);
		value = element.name;

		if (element.value == 'true') {
			jQuery(link).css('font-weight', 400);
			jQuery(link).css('color', 'grey');
			element.value = 'false';
		} else {
			jQuery(link).css('font-weight', 800);
			jQuery(link).css('color', 'black');
			element.value = 'true';
		}
		
		this.exec(element.name, element.value);
	}
	
}


function t41_agreement(checkObj, infoObj, submitObjId) {

	if (submitObjId) {
		submitObjId = '#' + submitObjId;
	} else {
		submitObjId = '#isSubmitted';
	}
	
	switch (checkObj.checked) {
	
		case true:
			jQuery(submitObjId).removeAttr('disabled');
			var date = new Date();
			var data = "{date:'" + date.toGMTString() + "',browser:'" + navigator.userAgent + "'}";
			jQuery('#' + infoObj).val(data);
			break;
	
		case false:
			jQuery(submitObjId).attr('disabled', 'disabled');
			jQuery('#' + infoObj).val('');
			
			break;
	}
}

function t41_dialog(id, options) {
	jQuery('#' + id).dialog(options);
}
