Ext.ns('Ext.lrp');

Ext.QuickTips.init();
Ext.lrp.imgPath = 'squelettes/lrpManager/style/images/';



/**
 * OVERRIDE
 */
Ext.form.Field.prototype.msgTarget = 'side';
Ext.grid.ColumnModel.prototype.defaultSortable = true;
Ext.override(Ext.grid.GridPanel, {
	loadMask: true,
	viewConfig: {
		emptyText: 'Aucune donnée à afficher.'
	}
});
Ext.override(Ext.grid.DateColumn, {
	format: 'd F Y',
	header: 'Date'
});
Ext.override(Ext.Window, {
	buttonAlign: 'center',
	closeAction: 'close',
	constrainHeader: true,
	modal: true
});
Ext.apply(Ext.form.VTypes, {
	password : function(val, field) {
		if (field.initialPassField) {
			var pwd = Ext.getCmp(field.initialPassField);
			return (val == pwd.getValue());
		}
		return true;
	},
	passwordText : 'Les mots de passe ne correspondent pas.'
});



/**
 * CONNEXION AU SERVEUR
 */
Ext.lrp.request = function(config) {
	config.method = 'POST';
	config.url = 'squelettes/lrpManager/action.php?service=' + config.service + '&action=' + config.action;
	
	var msg	= Ext.isDefined(config.waitMsg) ? config.waitMsg : 'Veuillez patienter';
	Ext.Msg.wait(msg, 'Please Wait...');
	
	var hideMsg = function() {
		Ext.Msg.updateProgress(1);
		Ext.Msg.hide();
	};
	
	if (!Ext.isDefined(config.success)) {
		config.success = Ext.emptyFn;
	}
	config.success = hideMsg.createSequence(config.success);
	
	if (!Ext.isDefined(config.failure)) {
		config.failure = function(response) {
			var result = Ext.decode(response.responseText);
			Ext.Msg.show({
				title: 'Echec',
				minWidth: 250,
				msg: result.msg,
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.ERROR
			});
		}
	}
	config.failure = hideMsg.createSequence(config.failure);
	
	config.callback = function(options, success, response) {
		var result = Ext.decode(response.responseText, true);
		if (result.expired === true) {
			Ext.lrp.expiredSession();
		}
	}
	
	Ext.Ajax.request(config);
};
Ext.lrp.submit = function(config) {
	config.method = 'POST';
	config.url = 'squelettes/lrpManager/action.php?service=' + config.service + '&action=' + config.action;
	
	if (!Ext.isDefined(config.waitMsg)) {
		config.waitMsg = 'Veuillez patienter';
	}
	
	if (!Ext.isDefined(config.failure)) {
		config.failure = function(form, action) {
			var result = action.result;
			if (result.expired === true) {
				return Ext.lrp.expiredSession();
			}
			Ext.Msg.show({
				title: 'Echec',
				minWidth: 250,
				msg: result.msg,
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.ERROR
			});
		}
	}
	
	if (Ext.isString(config.form)) {
		Ext.getCmp(config.form).getForm().submit(config);
	}
	else if (Ext.isObject(config.form)) {
		config.form.getForm().submit(config);
	}
};
Ext.lrp.url = function(myparams) {
	var params = [];
	
	for (var i in myparams.params) {
		params.push(i + '=' + myparams.params[i]);
	}
	
	var url = 'squelettes/lrpManager/action.php?service=' + myparams.service + '&action=' + myparams.action;
	if (params.length > 0) {
		url += '&' + params.join('&');
	}
	return url;
};
Ext.lrp.location = function(myparams) {
	self.location = Ext.lrp.url(myparams);
};
Ext.lrp.expiredSession = function() {
	Ext.lrp.LoadMask("Votre session est expirée. Veuillez vous authentifier.");
	self.location=self.location.href.replace('#', '');
};



/**
 * STORE
 */
Ext.lrp.Store = Ext.extend(Ext.data.Store, {
	
	constructor: function(config) {
		config.url = 'squelettes/lrpManager/action.php?service=' + config.service + '&action=' + config.action;
		
		config.root = config.root || 'dataRoot';
		config.totalProperty = config.totalProperty || 'dataCount';
		
		config.listeners = config.listeners || {};
		
		Ext.apply(config.listeners, {
			exception: function (proxy, type, action, options, response) {
				var result = Ext.decode(response.responseText);
				if (result.expired == true) {
					Ext.lrp.expiredSession();
				}
			}
		});
			
		Ext.lrp.Store.superclass.constructor.call(this, config);
	}

});
Ext.reg('lrp_store', Ext.lrp.Store);

Ext.lrp.JsonStore = Ext.extend(Ext.data.JsonStore, {
	
	constructor: function(config) {
		config.url = 'squelettes/lrpManager/action.php?service=' + config.service + '&action=' + config.action;
		
		config.root = config.root || 'dataRoot';
		config.totalProperty = config.totalProperty || 'dataCount';
		
		config.listeners = config.listeners || {};
		
		Ext.apply(config.listeners, {
			exception: function (proxy, type, action, options, response) {
				var result = Ext.decode(response.responseText);
				if (result.expired == true) {
					Ext.lrp.expiredSession();
				}
			}
		});
			
		Ext.lrp.JsonStore.superclass.constructor.call(this, config);
	},
	
	listeners: {
		exception: function (proxy, type, action, options, response) {
			var result = Ext.decode(response.responseText);
			if (result.expired == true) {
				Ext.lrp.expiredSession();
			}
		}
	}

});
Ext.reg('lrp_jsonstore', Ext.lrp.JsonStore);



/**
 * LOAD MESSAGE
 */
Ext.lrp.LoadMask = function (message, element) {
	if (!Ext.isDefined(element)) {
		element = Ext.getBody();
	}
	
	var myMask = new Ext.LoadMask(element, {
		msg: message,
		msgCls: 'mask',
		removeMask: true
	});
	myMask.show();
	return myMask;
};




/**
 * GRID KEY SEARCH
 */
Ext.lrp.gridKeySearch = Ext.extend(Ext.util.Observable, {
	timeout: 1500,
	
	constructor: function(config) {
        Ext.apply(this, config);
		
		Ext.lrp.gridKeySearch.superclass.constructor.call(this);
	},
	
	init: function(grid) {
		this.grid = grid;
		this.currentSearch = '';
		this.lastTimeIndex = false;
		
		this.grid.on('keydown', this.onKeyDown, this)
	},
	
	onKeyDown: function(e) {
		if (e.getKey() == 13 && Ext.isFunction(this.enterHandler)) {
			var selection = this.grid.getSelectionModel().getSelections();
			if (selection.length == 1) {
				this.enterHandler.call(this.scope || this, selection[0]);
			}
		}
		
		if (this.lastTimeIndex != false) {
			clearTimeout(this.lastTimeIndex);
		}
		this.lastTimeIndex = this.resetSearch.defer(this.timeout, this);
		
		if (e.isSpecialKey()) {
			return false;
		}
		
		var store = this.grid.getStore();
		this.currentSearch += String.fromCharCode(e.getKey()).toLowerCase();
		
		var index = store.find(this.dataIndex, this.currentSearch);
		if (index != -1) {
			this.grid.getSelectionModel().selectRow(index);
			this.grid.getView().focusRow(index);
		}
	},
	
	resetSearch: function() {
		this.currentSearch = '';
	}
	
});





/**
 * MANAGEMENT WINDOW
 */
Ext.lrp.ManagementWindow = Ext.extend(Ext.Window, {
	width: 450,
	resizable: false,
	layout: 'fit',
	closeWin: true,
	showMsg: true,
	
	initComponent: function() {
		var formHeight = this.height;
		this.height = 'auto';
		
		var formItems = this.items;
		
		this.form = new Ext.form.FormPanel({
			height: formHeight,
			fileUpload: this.fileUpload || false,
			border: false,
			labelWidth: 120,
			style: 'padding:10px;background-color:#FFFFFF;',
			items: formItems,
			keys: [{
				key: [10,13],
				fn: this.submitForm,
				scope: this
			}]
		});
		
		this.items = this.form;
		
		this.buttons = [{
			text: 'Valider',
			handler: this.submitForm,
			scope: this
		},{
			text: 'Annuler',
			handler: function() {
				this.destroy();
			},
			scope: this
		}];
		
		Ext.lrp.ManagementWindow.superclass.initComponent.call(this);
		
		this.on('show', this.focusFirstChild, this);
	},
	
	focusFirstChild: function() {
		var fields = this.form.items.items;
		Ext.each(fields, function(field) {
			if (
				Ext.isFunction(field.focus) &&
				field.getXType() != 'hidden' &&
				field.isVisible() == true &&
				field.disabled != true
			) {
				field.focus(false, 500);
				return false;
			}
		});
	},
	
	submitForm: function() {
		if (this.form.getForm().isValid()) {
			Ext.lrp.submit({
				form: this.form,
				service: this.service,
				action: this.action,
				params: this.params || {},
				success: this.onSuccess,
				scope: this
			});
		}
	},
	
	onSuccess: function(form, action) {
		if (this.closeWin) {
			this.destroy();
		}
		
		if (this.showMsg) {
			Ext.Msg.show({
				title: 'Confirmation',
				minWidth: 250,
				msg: action.result.msg,
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.INFO,
				fn: function (btn) {
					this.afterSuccess(form, action);
				},
				scope: this
			});
		}
		else {
			this.afterSuccess(form, action);
		}
	},
	
	afterSuccess: function(form, action) {
		if (Ext.isDefined(this.gridToReload)) {
			this.gridToReload.getStore().reload();
		}
		if (Ext.isFunction(this.callback)) {
			this.callback(form, action);
		}
	}
	
});
Ext.reg('managementwindow', Ext.lrp.ManagementWindow);
