// ----------------------------------------------------------------
// Classe MooTableau  	-  		Mike GILBLAS  		- 	 19/05/2009 
// ----------------------------------------------------------------
// 		Conversion d'une table html avec tbody scrollable
// ----------------------------------------------------------------
// Usage : 
// -------
// - inclure tableau.js / tableau.css dans la page
// - instancier MooTableau sur une table (elt). 
// 		new MooTableau(elt, options);
// Options : 
// ---------
// - height : Hauteur du tableau en pixel
// - width :  Largeur du tableau en pixel
// - headerHeight: Hauteur du header (22 px par défaut)
// - normalColor: Couleur ligne (#CCC par défaut)
// - highlightColor: Couleur ligne sous la souris (#36A par défaut)
// - resizable: colonnes redimensionnables (false par défaut)
// - sortable: colonnes triables (false par défaut)
// ----------------------------------------------------------------
var MooTableau = new Class({
	Implements: [Events, Options],

	// Options
	options: {
		width: '100%',
		height: 352,
		headerHeight: 22,
		normalColor: '#CCC',
		highlightColor: '#36A',
		resizable: false,
		sortable: true,
		fontSize: 10
	},
	
	// Constructeur
	initialize: function(element, options){
		this.setOptions(options);
		this.MooTableau = null;
		this.headers = [];
		this.rows = [];
		this.cells = [];
		this.data = [];
		this.triIndex = 0;
		this.triSens = 1;
		if (element.get('tag') == 'table') {
			if (!element.hasClass('MooTableau')) element.addClass('MooTableau');
			this.initTable(element);
			if (this.options.sortable) this.fillData();
		} else alert('Paramètre élément incorrect (tag != "table")');
    },
	
	// Initialisation du tableau
	initTable: function(elt){
		elt.set('cellPadding', 0); elt.set('cellSpacing', 0);
		var tabHead = elt.clone().inject(elt, 'before');			// Création par copie du header
		tabHead.getElement('tbody').dispose();
		tabHead.setStyle('width', '100%');
		tabHead.getElement('tr').setStyle('height', this.options.headerHeight);
		elt.getElement('thead').dispose();							// Transfo du tableau en contenu scrollable
		elt.setStyle('width', '100%');
		var divCont = new Element('div');
		divCont.wraps(elt);
		divCont.setStyles({position: 'relative', height: (this.options.height - this.options.headerHeight - 1), width: '100%', 
						overflowX: 'hidden', overflowY: 'scroll', background: '#333', borderTop: '1px solid #333'});
		var divMain = new Element('div');							// Regroupement des headers & du contenu
		divMain.wraps(tabHead); divMain.wraps(divCont);
		divMain.setStyles({position: 'relative', height: this.options.height, width: this.options.width, border: '1px solid #333'});
		
		// Init propriétés de l'objet
		this.MooTableau = divMain;
		this.headers = tabHead.getElements('th');
		this.rows = elt.getElements('tr');
		this.cells = elt.getElements('td');
		this.resizeTable(this.options.width, this.options.height);
		var objMT = this;
		divCont.getElements('tr').setStyle('height', this.options.headerHeight);
		divCont.getElements('td').setStyle('vertical-align', 'middle');
		
		// Effets au survol d'une ligne
		divCont.getElements('tr').addEvent('mouseenter', function(e) {
			this.get('tween', {duration: 500}).start('background-color', objMT.options.highlightColor);
		});
		divCont.getElements('tr').addEvent('mouseout', function(e) {
			this.get('tween', {duration: 500}).start('background-color', objMT.options.normalColor);
		});
		
		// Scroll du contenu
		divCont.addEvent('mousewheel', function(e) {
			e.stop();
			new Fx.Scroll(this).set(0, Math.floor((this.getScroll().y + (e.wheel < 0 ? 50 : -50)) / 
						this.getElement('tr').getSize().y) * this.getElement('tr').getSize().y);
		});
		
		// Redimensionnement des headers
		if (this.options.resizable) {
			tabHead.getElements('th').addEvent('mousemove', function(e) {
				if (this != this.getParent().getElement('th:last-child')) {
					var pourcent = (e.client.x - this.getPosition().x) / this.getSize().x * 100;
					if (pourcent > 90) { this.setStyle('cursor', 'e-resize'); this.retrieve('drag').attach(); } 
					else { this.setStyle('cursor', 'auto'); this.retrieve('drag').detach(); }
				}
			});
			tabHead.getElements('th').each(function(header, key) {
				if (header != header.getParent().getElement('th:last-child')) {
					header.store('drag', header.makeResizable({modifiers: {x: 'width'}, limit: {x: [30, 650], y: [objMT.options.headerHeight, objMT.options.headerHeight]}, 
						onComplete: function(header, e) { objMT.synchroColumns(); },
						onStart: function(header) { header.setProperty('oriWidth', header.getSize().x); },
						onDrag: function(header, e) { 
							var delta = header.getSize().x - header.getProperty('oriWidth') - 2;
							header.getNext('th').setStyle('width', header.getNext('th').getSize().x + delta);
						}
					}));
					header.retrieve('drag').detach();
				}
			});
		}
		
		// Tri des lignes via click des headers
		if (this.options.sortable) {
			tabHead.getElements('th').setStyle('cursor', 'pointer');
			tabHead.getElements('th').setStyle('text-decoration', 'none');
			tabHead.getElements('th').addEvent('click', function(e) {
				e.stop();
				if (objMT.triIndex != this.getProperty('index')) {
					if ($('imgtri')) $('imgtri').destroy();
					var imgtri = new Element('img', {id: 'imgtri', src: '/tableau/tri_asc.gif', height: 11, width: 7});
					this.grab(imgtri, 'top');
					imgtri.setStyles({verticalAlign: 'bottom', marginRight: 6});
					objMT.triIndex = this.getProperty('index');
					objMT.triSens = 1;
					objMT.sortData();
				} else {
					objMT.triSens = (objMT.triSens == 1 ? -1 : 1);
					$('imgtri').set('src', '/tableau/tri_' + (objMT.triSens == 1 ? 'a' : 'de') + 'sc.gif');
				}
				objMT.sortCols();
			});
		}
	},
	
	fillData: function() {
		var nbLigne = this.MooTableau.getElement('tbody').getElements('tr').count;
		var nbColonne = this.MooTableau.getElements('th').count;
		this.MooTableau.getElements('th').each(function(elt, key) {
			elt.setProperty('index', key + 1);
		});
		this.data = new Array(nbLigne);
		var objMT = this;
		this.MooTableau.getElement('tbody').getElements('tr').each(function(elt, key) {
			elt.addClass('MTL' + key);
			tempArray = ['MTL' + key];
			elt.getElements('td').each(function(objcel, keycel) {
				valeur = objcel.get('text').toLowerCase();
				if (valeur.match(/^[£$]/) || valeur.match(/^[\d\.]+$/)) {
					valeur = parseFloat(valeur).toFixed(10);
					while (valeur.length < 25) valeur = '0' + valeur;
//					if (keycel == 2) alert(valeur);
				} else if (valeur.match(/^\d\d[\/-]\d\d[\/-]\d?\d?\d\d$/) || 
						   valeur.match(/^\d?\d[\/.]\d?\d[\/.]\d\d\d\d$/)) { 
					var tmpdat = valeur.split("/");
					if (tmpdat[1]<10) tmpdat[1] = "0" + tmpdat[1];
					if (tmpdat[0]<10) tmpdat[0] = "0" + tmpdat[0];
					valeur = tmpdat[2] + tmpdat[1] + tmpdat[0];
				} else if (valeur.match(/^\d\d[\/-]\d\d[\/-]\d?\d?\d\d \d\d:\d\d:\d\d$/)) { 
					valeur = valeur.replace(':', '/');
					valeur = valeur.replace(' ', '/');
					var tmpdat = valeur.split("/");
					if (tmpdat[5]<10) tmpdat[5] = "0" + tmpdat[5];
					if (tmpdat[4]<10) tmpdat[4] = "0" + tmpdat[4];
					if (tmpdat[3]<10) tmpdat[3] = "0" + tmpdat[3];
					if (tmpdat[1]<10) tmpdat[1] = "0" + tmpdat[1];
					if (tmpdat[0]<10) tmpdat[0] = "0" + tmpdat[0];
					valeur = tmpdat[2] + tmpdat[1] + tmpdat[0] + tmpdat[3] + tmpdat[4] + tmpdat[5];
				}
				tempArray.push([valeur]);
			});
			objMT.data[key] = tempArray;
		});
	},

	sortData: function() {
		for (var ind1 = this.data.length - 1; ind1 >= 0; ind1--) {
			var temp;
			for (var ind2 = this.data.length - 1; ind2 >= 0; ind2--) {
				if (this.data[ind2][this.triIndex] < this.data[ind1][this.triIndex]) {
					temp = this.data[ind2];
					this.data[ind2] = this.data[ind1];
					this.data[ind1] = temp;
				}
		   }
		}
	},

	sortCols: function() {
		for (var cpt = 0; cpt < this.data.length - 1; cpt++)
			this.MooTableau.getElement('.' + this.data[cpt+1][0]).inject(
						this.MooTableau.getElement('.' + this.data[cpt][0]), (this.triSens>0?'after':'before'));
	},

	resizeTable: function(width, height) {
		this.MooTableau.getElement('thead').getParent().setStyle('width', '100%');
		this.MooTableau.getElement('thead').getParent().setStyle('height', this.options.headerHeight);
		this.MooTableau.getElement('th:last-child').setStyles({paddingRight: '18px', borderRight: 'none'});
		this.MooTableau.getElement('tbody').getParent().setStyle('width', width - 17);
		this.MooTableau.getElement('tbody').getParent().getParent().setStyle('height', height - this.options.headerHeight - 1);
		this.MooTableau.getElement('thead').getParent().getParent().setStyle('height', height);
		divMain = this.MooTableau;
/*		var cptcol = 0;
		this.MooTableau.getElements('th').each(function(header, key) {		// Redimensionnement des headers au contenu
			cptcol++;
			header.setProperty('nthChild', cptcol);
			if (divMain.getElement('td:nth-child(' + cptcol + ')')) {
				largeur = divMain.getElement('td:nth-child(' + cptcol + ')').getSize().x - 2;
				header.setStyle('width', largeur);
			}
		}); */
		this.synchroColumns();
	}, 
	
	synchroColumns: function() {
		this.MooTableau.getElements('th').setStyle('font-size', this.options.fontSize);
		this.MooTableau.getElements('td').setStyle('font-size', this.options.fontSize);
/*		this.MooTableau.getElements('th').each(function(header, key) {		// Redimensionnement des headers au contenu
			if (divMain.getElement('td:nth-child(' + header.getProperty('nthChild') + ')')) {
				divMain.getElement('td:nth-child(' + header.getProperty('nthChild') + ')').setStyle('width', header.getSize().x);
			}
		}); */
		var cptcol = 0;
		this.MooTableau.getElements('th').each(function(header, key) {		// Redimensionnement des headers au contenu
			cptcol++;
			if (divMain.getElement('td:nth-child(' + cptcol + ')')) {
				largeur = divMain.getElement('td:nth-child(' + cptcol + ')').getSize().x - 2;
				header.setStyle('width', largeur);
			}
		}); 
	}
});

window.addEvent('domready', function() {
	$$('.MooTableau').each(function(elt){
		new MooTableau(elt);
	});
});
