window.addEvent('domready', function(){
	window.workspace = new Workspace();

	window.workspaceColumns = new Hash();
	window.workspaceBlocks = new Hash();
	window.workspaceTables = new Hash();
	window.workspaceLinks = new Hash();
	window.workspaceGraphs = new Hash();
	window.workspaceAccordions = new Hash();
	window.workspaceCarousel = new Hash();
	window.workspaceCombos = new Hash();
	
	
	var accesrapide = $('accesrapide');
	if(accesrapide) new WorkspaceAccesRapide(accesrapide);

	new WorkspaceSearch({
		bloc:$('divRecherche'),
		query:$('search-query'),
		type:$('search-type'),
		categorie:$('search-categorie'),
		exchanges:$('search-exchanges')
	});

	setupHTMLComponents(document.body);
});


function setupHTMLComponents(container){
	container = $(container);
	
	container.getElements('table.btable').each(function(tableElement){
		new WorkspaceTable(tableElement, {onRowDropped:dropTableRow});
	});

	container.getElements('a.external,a.popup,a.help').each(function(anchorElement){
		new WorkspaceLink(anchorElement);
	});

	container.getElements('ul.carousel').each(function(carousel){
		new WorkspaceCarousel(
			$(carousel.id),
			$(carousel.id + '_slider')
		);		
	});

	container.getElements('div.flashgraph').each(function(graph){
		new WorkspaceFlashGraph(graph);
	});

	container.getElements('div.accordion').each(function(accordion){		
		var config = window.config.accordions[accordion.id] || {};
		
		new Accordion(accordion.getElements('div.toggler'), accordion.getElements('div.element'), $merge({
			opacity:false,
			show:false,
			display:false,
			alwaysHide:true,
			fixedHeight:119,

			onActive:function(toggler, element){
				toggler.addClass('selected');
												
				var graph = window.workspaceGraphs.get(element.getFirst().id);
				if(graph) {
					graph.show();
				}
			},

			onBackground:function(toggler, element){
				toggler.removeClass('selected');
			}
		}, config));
	});
	
	container.getElements('div.column').each(function(colElement){
		var column = new WorkspaceColumn(colElement, {
			onBlockMoved:saveDisposition,
			onBlockDropped:dropBlockInColumn
		});
	});
	
	
	//setupButtons(container);
	//setupFields(container);
	//setupComboboxes(container);
}

// buttons
function setupButtons(container) {
	// button
	container.getElements('input.button3').each(function(el){
		var s = new Element('span', {'class':'button3'});
		var ss = new Element('span');
		if(Browser.Engine.gecko){
			var lh = 12;
			s.setStyle('line-height', lh+'px');
			ss.setStyle('line-height', lh+'px');
		}
		s.wraps(ss.wraps(el));
	});
	
	container.getElements('a.submit').addEvent('click', function(e) {
		e = new Event(e).stop();
		$(e.target).getParent('form').submit();
	});
	//if(Browser.Engine.trident && Browser.Engine.version < 7)
	/*container.getElements('a.button').addEvents({
		'startdrag': function(e){ return false;}		
	});*/
}

// fields
function setupFields(container) {
	container.getElements('span.field input').addEvents({
		'focus':function(){this.getParent().addClass('focused');},		
		'blur':function(){this.getParent().removeClass('focused');}
	});
}

// combo
function setupComboboxes(container) {
    container.getElements('select.combo').each(function(el){
    	var options = {};
    	if(container.id == "wmb_contents") 
    		options.relativeTo = "wmb_window";    		
    	window.workspaceCombos.set(el.get('id'), new Combo(el, options));
    });
}

function destroyHTMLComponents(container){
	container.getElements('table.btable').each(function(table){
		window.workspaceTables.get(table.id).destroy();
		window.workspaceTables.erase(table.id);
	});

	container.getElements('div.carousel').each(function(carousel){
		window.workspaceCarousel.get(carousel.id).destroy();
		window.workspaceCarousel.erase(carousel.id);
	});

	container.getElements('div.flashgraph').each(function(graph){
		window.workspaceGraphs.get(graph.id).destroy();
		window.workspaceGraphs.erase(graph.id);
	});

	container.getElements('div.accordion').each(function(accordion){
		window.workspaceAccordions.get(accordion.id).destroy();
		window.workspaceAccordions.erase(accordion.id)
	});
}

//----------------------------------------------------------------------------
//
//								Element shortcuts
//
//----------------------------------------------------------------------------
Element.implement({
	isVisible: function() {
		return this.getStyle('display') != 'none';
	},
	toggle: function() {
		return this[this.isVisible() ? 'hide' : 'show']();
	},
	hide: function() {
		this.setStyle('display','none');
		return this;
	},
	show: function(display) {
		this.setStyle('display',(display || 'block'));
		return this;
	},
	showInline: function(display) {
		this.setStyle('display',(display || 'inline'));
		return this;
	},
  	swapClass: function(remove, add) {
    	return this.removeClass(remove).addClass(add);
  	},
	fxOpacityOk: function(){
		return !Browser.Engine.trident4;
	},
	findParent:function(tagParent){
		var parent = this.getParent();
		if(!parent) return false;

		if(parent.get('tag') == tagParent){
			return parent;
		}
		else if(parent.get('tag') != 'body'){
			return parent.findParent(tagParent);
		}
		else{
			return false;
		}
	},
	addClassOnOver: function(className) {
    	this.addEvents({
     		'mouseover': function(){this.addClass(className);},
     		'mouseout': function(){this.removeClass(className);}
    	});
	}
});

String.implement({
	extractParameters: function(){
		var hash = new Hash();

		var s = this;
		var hasParams = false;

		if(s.indexOf('?') > -1){
			s = s.substr(s.indexOf('?')+1);
			hasParams = true;
		}

		if(s.indexOf('#') > -1){
		 	s = s.substr(s.indexOf('#')+1);
		 	hasParams = true
		}
		
		if(hasParams || s.indexOf('&') > -1 || s.indexOf('=') > -1){
			s.split('&').each(function(s2){
				var index = s2.substr(0, s2.indexOf('=')).trim();
				if(index != '') hash.set(index, s2.substr(s2.indexOf('=')+1).trim());
			});
		
			return hash.getClean();
		}
		
		return false;		
	}
});


//----------------------------------------------------------------------------
//
//									REQUEST
//
//----------------------------------------------------------------------------
Request.Bourso = new Class({

	Extends: Request,

	initialize: function(options){
		options = $merge({
			onException:this.defaultOnException,
			onCancel:this.defaultOnCancel,
			onSuccess:this.defaultOnSuccess,
			onComplete:this.defaultOnComplete,
			onFailure:this.defaultOnFailure,
			encoding:'ISO-8859-1'
		}, options);
		
		this.parent(options);
	},
/*
	send: function(options){
		options = $merge({data:''}, options);
		
		var ajaxToken = $('ajaxToken');

		if(ajaxToken){
			switch($type(options.data)){
				case 'string':
					options.data += '&ajaxToken=' + ajaxToken.get('value');
					break;

				case 'object':
					options.data.ajaxToken = ajaxToken.get('value');
					options.data = Hash.toQueryString(options.data);
					break;

				case 'hash':
					options.data.set('ajaxToken', ajaxToken.get('value'));
					options.data = Hash.toQueryString(options.data);
				break;
			}
		}

		switch($type(options.data)){
			case 'string':
				options.data += '&' + this.options.data;
			break;

			case 'object':
			case 'hash':
				options.data = '&' + Hash.toQueryString(this.options.data);
			break;
		}
		
		this.parent(options);
	},
	
*/
	defaultOnFailure: function(xhr){
		window.workspace.showError('Une erreur est survenue.', 'Veuillez r\351essayer dans quelques instants.');
		this.hideOverlay();
	},

	defaultOnCancel: function(){
		this.hideOverlay();
	},
	
	defaultOnException:function(){
		window.workspace.showError('Une erreur est survenue.', 'Veuillez r\351essayer dans quelques instants.');
		this.hideOverlay();
	},

	defaultOnSuccess: function(){
	},

	defaultOnComplete: function(){
	},
	
	showOverlay:function(element){
		this.overlay = window.workspace.createOverlay(element).addClass('ajax-loading').show();
	},
	
	hideOverlay:function(){
		if(this.overlay) {			
			this.overlay.hide().dispose();
			delete this.overlay;
		}		
	}
});

Request.BoursoJSON = new Class({

	Extends: Request.Bourso,

	options: {
		secure: true,
		update:false
	},

	initialize: function(options){
		this.parent($merge({
			onRequest:this.start.bind(this),
			onSuccess:this.success.bind(this)
		}, options));
		this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'});
	},

	start:function(){
		if(this.options.update){
			this.showOverlay(this.options.update);
		}
	},

	success: function(text, xml){
		this.response.json = JSON.decode(text, this.options.secure);
		
		if(!this.response.json){
			window.workspace.showError('Une erreur est survenue.', 'Veuillez r\351essayer dans quelques instants.');
		}
		
		if(this.response.json.error){
			window.workspace.showErrorMessage(this.response.json.error);
		}

		if(this.response.json.debug){
			window.workspace.showDebugMessage(this.response.json.debug);
		}

		if(this.response.json.success){
			window.workspace.showSuccessMessage(this.response.json.success);
		}
		
		if(this.options.update){
			this.hideOverlay();
		}

		this.fireEvent('complete', [this.response.json.result, text]);
	}
});

Request.BoursoHTML = new Class({

	Extends: Request.Bourso,

	options: {
		update: false,
		evalScripts: true,
		filter: false,
		init:false
	},

	initialize: function(options){
		this.parent($merge({
			'onRequest':this.start,
			'onSuccess':this.end
		}, options));
	},

	processHTML: function(text){
		var match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
		text = (match) ? match[1] : text;
		
		var container = new Element('div');
		return container.set('html', text);
	},

	success: function(text){
		var options = this.options, response = this.response;

		response.html = text.stripScripts(function(script){
			response.javascript = script;
		});

		var temp = this.processHTML(response.html);

		response.tree = temp.childNodes;
		response.elements = temp.getElements('*');
		
		if (options.filter) response.tree = response.elements.filter(options.filter);
		if (options.update) $(options.update).empty().set('html', response.html);
				
		if (options.evalScripts){ 
			try{
				$exec(response.javascript);
			}catch(e){
				if(console) {
					console.log(e);
				}
			}
		}

		this.fireEvent('complete', [response.tree, response.elements, response.html, response.javascript]).fireEvent('success', [response.tree, response.elements, response.html, response.javascript]).callChain();
	},

	start:function(){
		if(this.options.update){
			this.showOverlay(this.options.update);
		}
	},

	end:function(){
		if(this.options.update){
			this.hideOverlay();
		}
	}
});

Element.Properties.load = {

	set: function(options){
		var load = this.retrieve('load');
		if (load) load.cancel();
		return this.eliminate('load').store('load:options', $extend({data: this, link: 'cancel', update: this, method: 'get'}, options));
	},

	get: function(options){
		if (options || ! this.retrieve('load')){
			if (options || !this.retrieve('load:options')) this.set('load', options);
			this.store('load', new Request.HTML(this.retrieve('load:options')));
		}
		return this.retrieve('load');
	}

};

Element.implement({
	load: function(){
		this.get('load').send(Array.link(arguments, {data: Object.type, url: String.type}));
		return this;
	}

});


//------------------------------------------------------------------------------
//
//										WORKSPACE
//
//------------------------------------------------------------------------------
var Workspace = new Class({
	
	idOverlay:0,
	
	initialize: function(){
		this.hoveredColumn = false;
		
		this.isStreaming = (typeof(isStreaming)!='undefined' && isStreaming);
		
		f = typeof(isStreaming)!='undefined' && isStreaming ? function _nostreaming() {nostreaming()} : this.toggleMyBourso.bind(this);
		
		$$('a.bourso-customization').addEvent('click', f);
	},
	
	createOverlay:function(element){
		this.idOverlay++;
				
		var overlay = new Element('div', {id:'workspace_overlay_' + this.idOverlay}).setStyles({'opacity':0.2, 'background-color':'black', 'display':'none', 'z-index':1500, 'position':'absolute'}).inject(document.body);
		if(element)	{
			var coord = element.getCoordinates();
			var scroll = element.getScroll();
			coord.top += scroll.y;
			coord.left += scroll.x;
			overlay.setStyles(coord);
		}
		
		return overlay;
	},
	
	getOverlay:function(id){
		id = id || this.idOverlay;
		return $('workspace_overlay_' + id); 
	},

	showOverlay:function(element){
		if(!this.overlay) this.overlay = this.createOverlay(element);
		return this.overlay.show();
	},

	hideOverlay:function(){
		if(this.overlay) this.overlay.removeProperty('class').hide();
	},

	showErrorMessage:function(msg){
		this.showError(msg)
	},

	showSuccessMessage:function(msg){
		this.showNotification(msg)
	},

	alert:function(msg, title){
		if(!this.roarAlert) this.roarAlert = new Roar({position:'lowerRight', duration:false, classColor:'ok'});
		this.roarAlert.alert((title)?title:'', msg);
	},

	showDebugMessage:function(msg){
		alert('DEBUG : ' + msg);
	},

	showNotification:function(msg, title){
		if(!this.roarNotification) this.roarNotification = new Roar({position:'lowerRight',classColor:'ok'});
		this.roarNotification.alert((title)?title:'', msg);
	},

	showError:function(msg, title){
		if(!this.roarError) this.roarError = new Roar({position:'lowerRight',classColor:'ko'});
		this.roarError.alert((title)?title:'', msg);
	},

	getPageID:function(){
		var page = window.location.pathname;
		return (page == '/')?'index':page.substring(1, page.lastIndexOf('.')).replace(/\//, '_');
	},

	toggleMyBourso:function(){
		if(!this.myBourso){
			this.openMyBourso();
		}
		else{
			this.closeMyBourso();
		}
	},

	openMyBourso:function(){
		if(!this.myBourso){
			this.myBourso = new WorkspaceMyBourso();
		}
		delta = 0;
		this.myBourso.load({
			'onLoad':function(myBourso){
				var myEffect = new Fx.Morph(myBourso.element, {duration: 'long'}).start({
		    		'height': [10, myBourso.element.getSize().y - delta]
				});
				myBourso.removeEvents('load');
			}.bind(this)
		});
	},

	closeMyBourso:function(){
		var myEffect = new Fx.Morph(this.myBourso.element, {
			duration: 'long',
			onComplete:function(element){
				element.destroy();
				delete this.myBourso;
			}.bind(this)
		}).start({
		  	'height': 0
		});

	},
	
	getBlock:function(blockid){
		var block_fund = null;
		window.workspaceBlocks.each(function(block){
			if (block.element.id == blockid) {
				block_fund = block;
			}
		});
		return block_fund;
	},
	
	getHackIframe:function(coordinates){
		if(!this.hackIframe){ 
			this.hackIframe = new IFrame({
				 src: 'javascript:false',
				 id:'hackiframe'
			}).inject(document.body);
			
			this.hackIframe.setStyle('position', 'absolute');
			this.hackIframe.setStyles({
				border:'1',
				'z-index':99,
				width:0,
				height:0,
				left:0,
				top:0
			});
		}
		
		coordinates.width = (parseInt(coordinates.width)-5) + 'px';
		coordinates.height = (parseInt(coordinates.height)-5) + 'px';
		
		this.hackIframe.setStyles(coordinates);
		
		return this.hackIframe;
	},
	
	isStreamingActiv:function(){
		return this.isStreaming;
	}
});



//------------------------------------------------------------------------------
//
//										DROP ELEMENT
//
//------------------------------------------------------------------------------
var DropElement = new Class({
	Implements: [Options, Events],

	options:{},

	initialize:function(element, options){
		this.element = $(element);
		this.setOptions(options);
	},

	canMoveElement: function(){
		return false;
	},

	canDropElement: function(){
		return false;
	},

	highlight: function(isOn){
		if(isOn)
			this.element.addClass('highlight');
		else
			this.element.removeClass('highlight');
	},
	
	initDrag:$empty,

	dragging: $empty,

	dropping:$empty,

	createMarker: $empty
});


//------------------------------------------------------------------------------
//
//									COLUMN - DROP
//------------------------------------------------------------------------------
var WorkspaceColumn = new Class({
	Extends: DropElement,

	initialize: function(element, options){
		//La config par défaut est défini dans l'objet window.columnsConfig, défini dans la page elle même
		this.parent(element, $merge(window.config.columns[element.id], options));
		window.workspaceColumns.set(element.id, this);

		this.element.getElements('div.html-block').each(function(blockElement, index){
			new WorkspaceBlock(blockElement, this, {
				onDisplayChange:saveBlockStates,
				onClose:saveDisposition
			});
		}.bind(this));
	},

	canMoveElement: function(){
		return this.options.canMoveBlock;
	},

	canDropElement: function(){
		return this.options.canDropBlock;
	},

	createMarker: function(draggable){
		return new Element('div', {'class':'marker', 'id':'column_marker'}).setStyles({'height':draggable.getSize().y});
	},
	
	initDrag:function(draggable){
		this.getBlocksDisposition(draggable);		
	},
	
	getBlocksDisposition:function(draggable){
		var tmp = new Hash();
		this.blocksFixedPosition = new Hash();
		
		var i=0;
		window.workspaceBlocks.each(function(block, index){
			if(block.columnParent == this && block.element != draggable){
				if(block.options.fixed !== false){
					this.blocksFixedPosition.set(parseInt(block.options.fixed), block.element.id);					
				}
				else{
					tmp.set(parseInt(block.getPosition()), block.element.id);
				}
			}
		}.bind(this));	
		
		var keys = tmp.getKeys();
		keys.sort();
		this.blocksMobilesDisposition = []
		for(i=0; i<keys.length; i++){
			this.blocksMobilesDisposition[i] = tmp.get(keys[i]);
		}
		
		return {mobile:this.blocksMobilesDisposition, 'fixed':this.blocksFixedPosition};
	},

	dragging: function(draggable, marker){
		var endPos = false;
		
		var direction = ((marker.getPosition().y - draggable.getPosition().y) > 0)?'before':'after';
		var draggableY = draggable.getPosition().y;
		
		var maxlength = this.blocksMobilesDisposition.length;
		if(maxlength == 0){
			var newDisposition = [marker.id];
			marker.inject(this.element, 'bottom');
			this.renderingFixed(newDisposition);
		}
		else{ 
			for(i=0; i<maxlength; i++){
				var element = $(this.blocksMobilesDisposition[i]);			
				if(draggableY >= element.getPosition().y && draggableY < (element.getPosition().y + 50)){
					endPos = i;
					break;
				}
			}
			
			if(endPos !== false){
				var newDisposition = [];
				
				if(direction == 'after') endPos++;
							
				for(i=0; i<endPos && i<maxlength; i++)
					newDisposition[i] = this.blocksMobilesDisposition[i];
				
				newDisposition[i] = marker.id;
				
				if(i == maxlength)
					marker.inject($(this.blocksMobilesDisposition[i-1]), 'after');
				else
					marker.inject($(this.blocksMobilesDisposition[i]), 'before');
										
				for(; i<maxlength; i++)
					newDisposition[(i+1)] = this.blocksMobilesDisposition[i];
	
				this.renderingFixed(newDisposition);			
			}
		}
	},
	
	renderingFixed:function(disposition){
		var finalDisposition = [];
				
		var j=0;				
		for(i=0; i<disposition.length; i++){
			var idblock = this.blocksFixedPosition.get(i);
			
			if(idblock != null){
				$(idblock).inject($(disposition[i]), 'before');
				finalDisposition[j] = idblock;
				j++;				
			}
			
			finalDisposition[j] = disposition[i];
			j++;						
		}
	},

	dropping:function(draggable, marker){
		if(this.element.hasChild(draggable)){
			//On déplace le block dans la même colonne
			draggable.replaces(marker);
			marker.destroy();
			this.fireEvent('blockMoved', this);
		}

		else {
			this.fireEvent('blockDropped', [draggable, this, marker]);
		}
	},
	
	delBlock:function(element){
		this.getBlocksDisposition(element);		
		this.renderingFixed(this.blocksMobilesDisposition);
	}
});

//------------------------------------------------------------------------------
//
//										TABLES - DROP
//
//------------------------------------------------------------------------------
var WorkspaceTable = new Class({

	Extends: DropElement,

	initialize: function(element, options){
		this.parent(element, $merge(window.config.tables[element.id], options, {'sortby':'-1'}));

		window.workspaceTables.set(element.id, this);

		this.element.getElements('thead a.sort').addEvent('click', function(e){
			e = new Event(e).stop();
			this.sort($(e.target));
		}.bind(this));
				
		if(this.options.canDragRow == 'true'){
			this.element.getElement('tbody').addEvent('mousedown', function(e){
				e = new Event(e).stop();

				var row = $(e.target).findParent('tr');

				this.drag = new Drag(this.element, {
					snap:5,
					onSnap:function(){
						this.drag.stop();
						new WorkspaceTableRow(row, {dragData:this.options.dragData[row.id]}).startDrag(e);
					}.bind(this),

					onCancel:function(){
						var anchor = row.getElement('a[rel=rowlink]');

						if(anchor){
							window.location.href = anchor.href;
						}
					}
				}).detach();

				this.drag.start(e);
			}.bind(this));
		}
		else{
			if(this.element.getElement('tbody')) {
				this.element.getElement('tbody').addEvent('click', function(e){
	
					var target = $(e.target);
	
					if(target.get('tag') == 'a'){
						e = new Event(e).stop();
						window.location.href = e.target.href;
					}
					else if(target.getParent().get('tag') == 'a'){
						e = new Event(e).stop();
						window.location.href = target.getParent().href;
					}
					else{
						var row = target.findParent('tr');
						if(!row) return false;
						var anchor = row.getElement('a[rel=rowlink]');
						if(anchor) {
							e = new Event(e).stop();
							window.location.href = anchor.href;
						}
					}
				});
			}
		}

		//IE6
		if(Browser.Engine.trident4){
			this.element.getElements('tbody tr').addEvents({
				'mouseenter':function(e){
					e = new Event(e).stop();
					this.addClass('mouseover');
				},

				'mouseleave':function(e){
					e = new Event(e).stop();
					this.removeClass('mouseover');
				}
			});
		}		
	},

	canDropElement: function(){
		return (this.options.canDropRow == 'true');
	},

	sort:function(anchor){
		var tableRows = this.element.getElements('tbody tr');
		
		//On récupère les données si ce n'est pas déjà fait
		if(!$defined(this.values)){
			this.values = [];

			tableRows.each(function(row, index){
				var cols = [];

				row.getChildren().each(function(col, index){
					//On supprime l'éventuel code HTML : couleur variation, img, etc.
					cols[index] = col.get('html');
				});

				this.values[index] = cols;
			}.bind(this));

			this.anchors = this.element.getElements('thead tr th a')
		}

		//Ordre et type de tri
		var sorttmp;
		for(sorttmp=0; sorttmp<this.anchors.length; sorttmp++){
			if(this.anchors[sorttmp] == anchor){
				break;
			}
		}

		if(sorttmp == this.options.sortby){
			if(this.sortorder == 'asc')
				this.sortorder = 'desc';
			else
				this.sortorder = 'asc';
		}
		else{
			this.options.sortby = sorttmp;
			this.sortorder = 'asc';
		}
		
		
		//Triage des données
		var i=0;
		this.values.sort(function(r1, r2){
			var value1 = r1[this.options.sortby].replace(/(<[^>]*>)|(<\/[^>]*>|( ))/gi, '');
			var value2 = r2[this.options.sortby].replace(/(<[^>]*>)|(<\/[^>]*>|( ))/gi, '');
			
			var regexpDate = new RegExp('^[0-9]{2}/[0-9]{2}/[0-9]{2,4}$');

			if (regexpDate.test(value1) && regexpDate.test(value2)) {
					date1=new Date(value1.substr(6),value1.substr(3,2),value1.substr(0,2));
					date2=new Date(value2.substr(6),value2.substr(3,2),value2.substr(0,2));
					
					if(date1.getTime() > date2.getTime())
						return ((this.sortorder == 'asc') ? 1 : -1);
					else if(date1.getTime() < date2.getTime())
						return ((this.sortorder == 'asc') ? -1 : 1);
					else
						return 0;
			}
			else {
				var regexp = new RegExp('^[-+0-9%.,]+[\s]*[A-Z]*$');
				
				if(regexp.test(value1)) value1 = parseFloat(value1);
				if(regexp.test(value2)) value2 = parseFloat(value2);
				
				if(value1 > value2)
					return ((this.sortorder == 'asc') ? 1 : -1);
				else if(value1 < value2)
					return ((this.sortorder == 'asc') ? -1 : 1);
				else
					return 0;
			}
		}.bind(this));

		//On redessine le tableau
		for(var i=0; i<this.values.length; i++){
			var cols = tableRows[i].getChildren();

			for(var j=0; j<this.values[i].length; j++){
				cols[j].set('html', this.values[i][j]);
			}
		}

		//On modifie la class qui affiche la classe
		var anchors = this.element.getElements('thead a');
		anchors.removeClass('asc');
		anchors.removeClass('desc');

		if(this.sortorder == 'asc')
			anchor.addClass('asc');
		else
			anchor.addClass('desc');
	},

	createMarker: function(draggable){
		var marker = new Element('div', {'class':'btableMarker'}).setStyles({
			'position':'absolute',
			'top':this.element.getPosition().y,
			'left':this.element.getPosition().x
		}).set('html', '+').inject(document.body);

		return marker;
	},

	dragging: function(draggable, marker){},

	dropping:function(draggable, marker){
		this.fireEvent('rowDropped', [draggable, this, marker]);
	}
});


//------------------------------------------------------------------------------
//
//									DRAG ELEMENT
//
//------------------------------------------------------------------------------
var DragElement = new Class({
	Implements: [Options, Events],

	options:{
		'drag':'none',
		'dragData':''
	},

	initialize:function(element, options){
		this.element = $(element);
		this.setOptions(options);
	},

	isDraggable:function(){
		return this.options.drag != 'none';
	},

	getDroppables:function(){
		return [];
	},

	getDragLimit: function(draggable){
		var limit = window.getScrollSize();
		return {x:[0, limit.x - draggable.getSize().x], y:[0, limit.y - draggable.getSize().y]};
	},

	getDragModifiers: function(){
		return {x:'left', y:'top'};
	},

	buildDraggable:function(mouse){
		this.element.store('dragData', this.options.dragData);
		this.element.store('styles', this.element.getStyles());
		this.element.store('coordinates', this.element.getCoordinates());
		return this.element;
	},

	startDrag:function(e){
		var draggable = this.buildDraggable(e.page);
		
		//Fix
		draggable.ondragstart = $lambda(false);
		
		new Drag(draggable, {
			modifiers: this.getDragModifiers(),
			limit: this.getDragLimit(draggable),
			onBeforeStart:this.beforeStart.bind(this),
			onDrag:this.drag.bind(this),
			onComplete:this.complete.bind(this),
			onCancel:this.cancel.bind(this)
		}).detach().start(e);
	},

	beforeStart:function(draggable){
		this.highlightDroppables(true);
		
		this.getDroppables().each(function(drop){
			drop.initDrag(draggable);
		})
		
		draggable.setStyles(draggable.retrieve('coordinates')); //init top, left, height, width for drag
		draggable.setStyles({position:'absolute', 'z-index':100});
				
		//Gestion des objet
		var hiddenElements = $A(this.element.getElements('select,applet,object,embed'));
		hiddenElements.each(function(el){el.style.visibility='hidden'});
		draggable.store('hiddenElements', hiddenElements);
		
		//Hack iframe
		this.iframe = window.workspace.getHackIframe(draggable.getCoordinates());
		this.iframe.show();
	},

	drag:function(draggable){
		this.iframe.setStyles({
			'top':draggable.getPosition().y,
			'left':draggable.getPosition().x
		});

		//Hovered
		var hovered = this.getHoveredElement(draggable);
		
		if(hovered){
			if(!this.marker){
				this.marker = hovered.createMarker(draggable).inject(document.body);				
			}
			hovered.dragging(draggable, this.marker);
		}
		else if(this.marker){
			this.marker.destroy();
			delete this.marker;
		}

		//scrolling
		var coordinates = draggable.getCoordinates();
		var windowY = window.getSize().y + window.getScroll().y;
		var windowX = window.getSize().x + window.getScroll().x;
		var scrollTo = {x:window.getScroll().x, y:window.getScroll().y}
		var scroll = false;

		if(coordinates.bottom > windowY){
			scrollTo.y = (coordinates.bottom < window.getScrollSize().y) ?  scrollTo.y+10 :  window.getScrollSize().y;
			scroll = true;
		}
		else if(coordinates.top < window.getScroll().y){
			scrollTo.y	= (coordinates.top > 0) ? scrollTo.y-10 : 0;
			scroll = true;
		}

		if(coordinates.right > windowX){
			scrollTo.x = (coordinates.right < window.getScrollSize().x) ? scrollTo.x+10 : window.getScrollSize().x;
			scroll = true;
		}
		else if(coordinates.left < window.getScroll().x){
			scrollTo.x = (coordinates.left > 0) ? scrollTo.x-10 : 0;
			scroll = true;
		}

		if(scroll){
			window.scrollTo(scrollTo.x, scrollTo.y);
		}
	},

	complete:function(draggable){
		var hovered = this.getHoveredElement(draggable);
		if(hovered)
			hovered.dropping(draggable, this.marker);
		else
			this.abort(draggable);
		this.endDrag(draggable);
	},
	
	abort: $empty,
	
	cancel:function(draggable){
		this.endDrag(draggable);
		
		if(this.marker) {
			this.marker.destroy();
			delete this.marker;
		}
	},
	
	endDrag:function(draggable){
		if(this.iframe) {
			this.iframe.hide();
		}
		
		draggable.removeProperty('style');
		draggable.setStyles(draggable.retrieve('styles'));
		
		//Force UI redraw
		var mark = new Element('div').inject(draggable, 'before');		
		draggable.dispose().inject(mark, 'after');		
		mark.destroy();
				
		this.highlightDroppables(false);
		draggable.retrieve('hiddenElements').each(function(el){el.style.visibility=''});
	},

	highlightDroppables:function(isOn){
		this.getDroppables().each(function(droppable){
			droppable.highlight(isOn);
		});
	},

	getHoveredElement:function(draggable){
		var hovered = false;

		var left = draggable.getCoordinates().left + (draggable.getSize().x / 2);
		var top = draggable.getCoordinates().top;

		this.getDroppables().each(function(droppable){
			var coord = droppable.element.getCoordinates();
			if(left >= coord.left && left <= coord.right && top >= coord.top && top <= coord.bottom){
				hovered = droppable;
			}
		}.bind(this));

		return hovered;
	}
});


//------------------------------------------------------------------------------
//
//										BLOCK
//
//------------------------------------------------------------------------------
var WorkspaceBlock = new Class({

	Extends: DragElement,

	statesToSave:{},

	initialize: function(element, column, options){
		this.parent(element, $merge(window.config.blocks[element.id], options), {dropAction:'moveBlock'});
		this.columnParent = column;
		window.workspaceBlocks.set(window.workspaceBlocks.getLength(), this);
		this.init();
	},

	init:function(){
		this.body = this.element.getElement('.body');
		//this.body = this.element; // allow event's handling on header and footer
		if(this.body) {
			this.statesToSave.displayBody = this.body.isVisible();
		
			this.element.getElements('.header a').addEvent('click', this.handleEvent.bind(this));
			this.element.getElements('.header select').addEvent('change', this.handleEvent.bind(this));
						
			this.body.addEvent('click', this.handleEvent.bind(this));
			
			if(this.isDraggable()){
				this.element.addEvent('mousedown', function(e){
					e = new Event(e);
					var target = $(e.target);
					
					try{
						if(target.hasClass('drag')){
						
							e.stop();
							this.startDrag(e);
						}
					}catch(e){}
				}.bind(this));
			}
	
			this.handleForms();
		}
	},
	
	handleEvent:function(e){
		var target = $(e.target);
		
		if(target.get('tag') == 'img' && target.getParent().get('tag') == 'a'){
			target = target.getParent();
		}
		
		target.getProperty("class").split(' ').each(function(classX) {			
			if(classX == 'update-body'){
				if(target.hasClass('selectable')){
					target.findParent('div').getElements('a.selected').removeClass('selected');
					target.addClass('selected');
				}
				
				switch(target.get('tag')){
					case 'a':
						e.stop();
						this.refresh({parameters:target.href.extractParameters()});
						break;
		
					case 'select':
						var params = new Hash();
						params.set(target.name,target.options[target.selectedIndex].value);
						this.refresh({parameters:params});
						break;					
				}
		
			}
		
			else if(classX == 'customization'){
				e.stop();
				this.refresh({displayFormCustomization:true});
			}
		
			else if(classX == 'close'){
				e.stop();
				if(window.confirm('Etes-vous sur de vouloir fermer ce bloc ?')){
					this.close();
				}
			}
		
			else if(classX == 'toggle-body'){
				e.stop();
				this.toggle();
			}
		
			else if(classX == 'maximize-body'){
				e.stop();
				this.maximize();
			}
		
			else if(classX == 'minimize-body'){
				e.stop();
				this.minimize();
			}
		
			else if(classX.match(/^saveParam\.(.+)\.(.+)/)) {
				e.stop();
				
				var infos = classX.split('.').associate(['null', 'param', 'value']);
		
				new Request.Bourso({
					url:'/ajax/block/saveparameters.phtml',
					data:'path=' + this.getPath() + '&position=' + this.getPosition() + '&page=' + window.workspace.getPageID() + '&column=' + this.columnParent.element.id + '&parameters[' + infos.param + ']='+infos.value
				}).post();
			}
		}.bind(this));
	},

	close:function(){
		window.workspaceBlocks.erase(window.workspaceBlocks.keyOf(this));
		this.columnParent.delBlock(this.element);
		this.element.destroy();
				
		this.fireEvent('close', this.columnParent);
	},

	toggle:function(){
		this.body.toggle();
		this.statesToSave.displayBody = this.body.isVisible();
		this.fireEvent('displayChange', this);
	},

	maximize:function(){
		this.body.show();
		this.statesToSave.displayBody = true;
		this.fireEvent('displayChange', this);
	},

	minimize:function(){
		this.body.hide();
		this.statesToSave.displayBody = false;
		this.fireEvent('displayChange', this);
	},

	isFullDrag: function(){
		return this.options.drag == 'full';
	},

	isColumnDrag: function(){
		return this.options.drag == 'column';
	},

	getDroppables:function(){
		if(this.isFullDrag()){
			var results = [];
			window.workspaceColumns.each(function(column){
				if(column.canDropElement() || column.canMoveElement()) results.include(column);
			});

			return results;
		}
		else if(this.isColumnDrag()){
			return [this.columnParent];
		}
	},

	getDragLimit: function(draggable){
		if(this.isFullDrag()) {
			var limit = window.getScrollSize();
			return {x:[0, limit.x - draggable.getSize().x], y:[0, limit.y - draggable.getSize().y]};
		}
		else{
			var coordColumn = this.columnParent.element.getCoordinates();
			return {x:[coordColumn.left, coordColumn.right - draggable.getSize().x], y:[coordColumn.top, coordColumn.bottom + draggable.getSize().y]};
		}
	},

	getDragModifiers: function(){
		if(this.isFullDrag())
			return {x:'left', y:'top'};
		else
			return {x:'top'}
	},
	
	beforeStart:function(draggable){
		this.marker = this.columnParent.createMarker(draggable).inject(this.element, 'after');
		this.parent(draggable);
	},
	
	getPath:function(){
		return this.element.id.substring(0,this.element.id.lastIndexOf('_'));
	},

	getPosition:function(){
		return this.element.id.substr(this.element.id.lastIndexOf('_')+1);
	},

	refresh:function(options){
		options = $merge({
			displayFormCustomization:false,
			saveCustomization:false,
			parameters:false
		}, options);

		var url = '/ajax/block/refresh.phtml';
		var data = 'path=' + this.getPath() + '&position=' + this.getPosition() + '&page=' + window.workspace.getPageID() + '&column=' + this.columnParent.element.id;

		if(options.displayFormCustomization) {
			data += '&displayFormCustomization=true';
		}
		
		var parameters = new Hash();
		
		if(this.options.parametersFixed)
			parameters = parameters.extend(new Hash(this.options.parametersFixed));

		if(options.parameters) {
			data += '&saveCustomization=1';
			parameters = parameters.extend(options.parameters);		
		}
		
		data += '&' + parameters.toQueryString();
		
		new Request.BoursoHTML({
			url:url,
			update: this.body,
			data:data,
			onComplete:function(){
				setupHTMLComponents(this.element);
				this.handleForms();
				this.fireEvent('refreshed');
			}.bind(this)
		}).post();
	},

	handleForms:function(){
		this.body.getElements('form.bform').each(function(form){
			form.addEvent('submit', function(e){
				e = new Event(e).stop();
				this.submitForm($(e.target));
			}.bind(this));

			form.getElements('select.submit').addEvent('change', function(e){
				this.submitForm($(e.target).form);
			}.bind(this));
			
			form.getElements('input[type=button].submit, input[type=submit].submit, input[type=checkbox].submit').addEvent('click', function(e){
				this.submitForm($(e.target).form);
			}.bind(this));

			form.getElements('.close').addEvent('click', function(e){
				e = new Event(e).stop();
				var form = $($(e.target).form);	
				form.getParent().dispose();
			}.bind(this));

		}.bind(this));
	},
	
	submitForm:function(form){
		if(window.workspace.isStreamingActiv())
			window.location.search = Hash.toQueryString($extend(window.location.search.extractParameters() || {}, form.toQueryString().extractParameters()));
		else
			this.refresh({parameters: form.toQueryString().extractParameters()});
	}
});


//------------------------------------------------------------------------------
//
//									TABLE ROW - DRAG
//
//------------------------------------------------------------------------------
var WorkspaceTableRow = new Class({

	Extends: DragElement,

	initialize: function(element, options){
		this.parent(element, $merge(options, {'drag':'yes'}));
	},

	getDroppables:function(){
		var results = [];

		window.workspaceTables.each(function(table){
			if(!table.element.hasChild(this.element) && table.canDropElement())
				results.include(table);
		}.bind(this));

		return results;
	},

	buildDraggable:function(mouse){
		var draggable = new Element('div', {'class':'drag'}).store('dragData', this.options.dragData);
		draggable.setStyles({
			position:'absolute',
			top:mouse.y,
			left:mouse.x
		});

		var elements = this.element.getElements('.draggable');
		if(elements.length > 0){
			draggable.set('html', elements[0].get('html'));
		}

		draggable.inject(document.body);

		return draggable;
	}
});


var WorkspaceMyBourso = new Class({
	Implements: [Options, Events],

	options:{
		//onLoad:$empty,
		data:''
	},

	initialize:function(){
		this.element = new Element('div', {'class':'myBourso'});
		this.element.set('html', 'Chargement...');
		this.element.inject($('content'), 'before');
	},

	load:function(options){
		this.setOptions(options);

		new Request.BoursoHTML({
			url:'/ajax/customization.phtml',
			data:this.options.data,
			update:this.element,

			onComplete:function(tree){
				this.fireEvent('load', this);

				var droppableColumn = this.element.getElement('input#droppableColumn');
				if(droppableColumn){
					droppableColumn = droppableColumn.get('value');

					this.element.getElements('div.drag').addEvent('mousedown', function(e){
						new WorkspaceMiniCustomizationBlock(this, {'droppableColumn':droppableColumn}).startDrag(e);
					});

					//Handle menu
					this.element.getElements('.Bgauche a').addEvent('click', function(e){
						e = new Event(e).stop();
						var target = $(e.target);
						this.load({data:target.search.substr(1)});
					}.bind(this));
				}

				//Handle close
				this.element.getElements('div.close').addEvent('click', window.workspace.closeMyBourso.bind(window.workspace));
			}.bind(this)
		}).post();
	}
});


var WorkspaceMiniCustomizationBlock = new Class({
	Extends: DragElement,

	initialize: function(element, options){
		this.parent(element,  $extend(options, {'drag':'yes'}));
	},

	getDroppables:function(){
		var column = window.workspaceColumns.get(this.options.droppableColumn);
		return (column)?[column]:false;
	},

	buildDraggable:function(mouse){
		var draggable = this.element.clone().inject(document.body);
		
		draggable.set('id', this.element.id.substr(5));
		draggable.removeProperty('style');
		draggable.setStyle('position', 'absolute');
		
		draggable.setStyles(this.element.getCoordinates());
		
		return draggable;
	},

	complete:function(draggable){
		this.parent(draggable);
		draggable.destroy();
	},

	cancel:function(draggable){
		this.parent(draggable);
		draggable.destroy();
	}
});


var WorkspaceLink = new Class({
	initialize: function(element){
		if(element.hasClass('external'))
			element.set('target', '_blank');
		else{
			element.addEvent('click', function(e){
				e = new Event(e).stop();
				
				try{
					var aDim = this.get('size').match(/[0-9]+/g);
				}catch(e){
					var aDim = this.rel.match(/[0-9]+/g);
				}
				
				new WorkspaceModalbox({'href':this.href, 'width':aDim[0], 'height':aDim[1], 'title':this.title, 'modal':false});
			});
		}
	}
});


var WorkspaceModalbox = new Class({
	Implements: [Options, Events],

	options:{
		'width':200,
		'height':150,
		'overlay':true,
		'href':false,
		'title':false,
		'modal':true,
		'method':'get',
		'fixed':false
		//'onLoad':$empty
		//'onClose':$empty
	},

	initialize:function(options){
		this.setOptions(options);
		
		window.workspaceModalbox = this;
		
		if($defined($('wmb_window'))) $('wmb_window').dispose();
		if($defined($('wmb_overlay'))) $('wmb_overlay').dispose();

		// overlay
		this.overlay = new Element('div').setProperty('id', 'wmb_overlay').setStyles({opacity:0, display: 'none'}).inject(document.body);
		
		// the center element
		this.window = new Element('div').setProperty('id', 'wmb_window').setStyles({display: 'none'}).inject(document.body);

		this.top = new Element('div').setProperty('id', 'wmb_top').injectInside(this.window);
		//Modal box
		if (!this.options.modal){
			this.closelink = new Element('a').setProperties({'id': 'wmb_closelink', 'class': 'click'}).injectInside(this.top);
			this.closelink.addEvent('click', this.close.bind(this));
			this.overlay.addEvent('click', this.close.bind(this));
		}
		
		this.title = new Element('div').setProperty('id', 'wmb_title').set('text', this.options.title).injectInside(this.top);
		this.contents = new Element('div').setProperty('id', 'wmb_contents').inject(this.window);
				
		this.overlayFX = new Fx.Tween(this.overlay, {duration: 300});

		/*
		this.windowFX = new Fx.Tween(this.window, {
			duration: 300
		});
		*/
		
		this.open();
	},

	open:function(){
		if(!this.options.fixed) window.addEvent('scroll', this.position.bind(this));
		window.addEvent('resize', this.position.bind(this));
		window.addEvent('keydown', this.keyboardListener.bindWithEvent(this));
		
		this.setSize();
		this.position();
		
		this.hiddenElements = $A($$('select, applet, object, embed'));
		this.hiddenElements.each(function(el){el.style.visibility='hidden'});
		// start chained animation		
		this.overlayFX.set('display', '').start('opacity', 0, 0.8).chain(function(){
			//this.windowFX.set('display', '').start('opacity', 0, 1);
						
			this.window.show();
			
			if(this.options.href.indexOf('?') == -1){
				this.loadContents(this.options.href);
			}
			else{
				this.loadContents(this.options.href.substring(0, this.options.href.indexOf('?')), Hash.toQueryString(this.options.href.extractParameters()), this.options.method);
			}			
		}.bind(this));		
	},
	
	setSize: function(){
		this.window.setStyles ({'width':this.options.width + "px", 'height': this.options.height + "px", 'margin-left': '-'+(this.options.width/2)+'px'});
		this.contents.setStyles({height: (this.options.height - 34) + "px"});
	},
	
	resize: function(width, height){
		this.options.width = width;
		this.options.height = height;
		
		this.setSize();
		this.position();
	},

	close:function(e){
		if(this.request && this.request.running) return false;
		
		if(!this.options.fixed) window.removeEvent('scroll', this.position.bind(this));
		window.removeEvent('resize', this.position.bind(this));
		window.removeEvent('keydown', this.keyboardListener.bindWithEvent(this));
		
		this.hiddenElements.each(function(el){el.style.visibility=''});
		
		this.window.dispose();		
		this.overlay.dispose();
		
		/*
		//this.window.setStyle('display', '');
		this.windowFX.start('opacity', 1, 0).chain(function(){
			this.overlayFX.start('opacity', 0.8, 0).chain(function(){
				this.overlay.hide();
			}.bind(this));
			this.window.hide();
		}.bind(this));
		*/
		
		window.workspaceModalbox = null;
		
		this.fireEvent('close', this);			
	},

	loadContents:function(url, data, method){
		method = method || 'get';
		data = data || {};
		
		this.lastUrl = url;
		
		this.request = new Request.BoursoHTML({
			url:url,
			update:this.contents,
			data:data,
			link:'cancel',
			onComplete:function(){
				this.fireEvent('load', this);
				
				this.contents.getElements('.close').addEvent('click', this.close.bind(this));
				
				setupHTMLComponents(this.contents);
				
				// submit button handler
				this.contents.getElements('a.submit').removeEvents('click');
				this.contents.getElements('a.submit').addEvent('click', function(e){
					e = new Event(e).stop();
					var form = $(e.target).getParent('form');
					this.loadContents(form.get('action'), form.toQueryString(), 'post');				
				}.bind(this));
				
				// form submit handler
				this.contents.getElements('form.bform').each(function(form){					
					form.addEvent("submit", function(e){
						e = new Event(e).stop();
						this.loadContents(form.get('action'), form.toQueryString(), 'post');
					}.bind(this));
				}.bind(this));
				
			}.bind(this)
		});
		
		if(method == 'get')
			this.request.get();
		else
			this.request.post();		
	},
	
	onFormSubmit: function(e, form) {
		new Event(e).stop();
		this.loadContents(form.get('action'), form.toQueryString(), 'post');
	},

	keyboardListener:function(event){
		if (((event.control && event.key == 'w') || (event.control && event.key == 'x') || (event.key == 'esc')) && (!this.options.modal)) {
			event.stop();
			this.close();
		}
	},

	position: function() {
		this.overlay.setStyles({top: window.getScrollTop()+'px', height: window.getHeight()+'px'});
		this.window.setStyles({top: (window.getScrollTop() + (window.getHeight() / 15)) +'px'});
		
		if(this.request && this.request.running) {
			var coord = this.contents.getCoordinates();
			coord.top += this.contents.getScroll().y;
			coord.left += this.contents.getScroll().x;
			window.workspace.getOverlay().setStyles(coord);
		}
	},
	
	getUrl: function(){
		var index = this.lastUrl.indexOf('?'); 
		if(index > -1)
			return this.lastUrl.substr(0, index);
		else
			return this.lastUrl;
	},
	
	setTitle: function(title){
		this.options.title = title;
		this.title.set('text', title);
	}
});


var WorkspaceAccesRapide = new Class({

	initialize:function(element){
		element.addEvent('click', this.toggle.bindWithEvent(this));
		this.panel = false;
		this.currentPanel = 'favoris';
		$('bookmark_page').addEvent('click', this.addUrl.bind(this, {type:'favoris',url:window.location.pathname+window.location.search, libelle:document.title}));
	},

	toggle:function(e){
		e = new Event(e).stop();

		if(!this.panel || !this.panel.isVisible()){
			var target = $(e.target);
			this.show({x:target.getCoordinates().right, y:target.getCoordinates().bottom});
		}
		else
			this.hide(e);
	},

	show:function(position){
		if(!this.panel) this.build();

		this.panel.show();
		this.panel.setStyles({top:position.y, left:(position.x - 250)});
		
		document.addEvent('click', this.hide.bind(this));

		this.refresh(this.currentPanel);
	},

	build:function(){
		this.panel = $('AccesRapides');

		this.body = this.panel.getElement('.body');

		this.panel.addEvent('click', function(e){
			e = new Event(e).stop();

			var target = $(e.target);
			if(target.get('tag') == 'img') target = target.findParent('a');

			if(target.hasClass('follow') || target.getProperty('rel') == 'follow'){
				window.location.href = target.href;
			}
			else if(target.hasClass('delete')){
				var infos = target.rel.split(',').associate(['id', 'type']);
				this.delUrl(infos);
			}
			else if(target.hasClass('update')){
				this.panel.getElements('ul.Item01 li a').removeClass('selected');
				target.addClass('selected');
				this.currentPanel = target.rel; 
				this.refresh(this.currentPanel);
			}
		}.bind(this));
	},

	refresh:function(type){
		new Request.BoursoHTML({
			url:'/ajax/dossier_personnel/refresh.phtml',
			update:this.body,
			onComplete:function(){
				this.iframe = window.workspace.getHackIframe(this.panel.getCoordinates());
				this.iframe.show();
			}.bind(this)
		}).post({'type':type});
	},

	hide:function(){
		document.removeEvent('click', this.hide.bind(this));
		this.panel.hide();
		this.iframe.hide();
	},

	addUrl:function(data){
		data = $merge({
			type:'',
			libelle:'',
			url:'',
			id:'',
			refresh:false
		}, data);

		if(data.type == "favoris"){
			data.libelle = prompt("Donner un nom à votre raccourci : ", data.libelle);
			if(data.libelle == null) return;
		}

		if(data.refresh){
			new Request.BoursoJSON({
				url:'/ajax/dossier_personnel/add.phtml',
				update:this.panel,
				onComplete:this.refresh.bind(this, data.type)
			}).post(data);
		}
		else{
			new Request.BoursoJSON({url:'/ajax/dossier_personnel/add.phtml'}).post(data);
		}
	},

	delUrl:function(data){
		data = $merge({
			type:'',
			id:''
		}, data);

		new Request.BoursoJSON({
			url:'/ajax/dossier_personnel/delete.phtml',
			update:this.panel,
			onComplete:this.refresh.bind(this, data.type)
		}).post(data);
	}
});


var WorkspaceSearch = new Class({
	options:{
		defaultValue:'Code, Libell\351, Mot cl\351'
	},

	initialize:function(elements){
		elements = $merge({
			bloc:false,
			type:false,
			query:false,
			categorie:false,
			exchanges:false
		}, elements);

		elements.bloc = $(elements.bloc);
		elements.type = $(elements.type);
		elements.query = $(elements.query);
		elements.categorie = $(elements.categorie);
		elements.exchanges = $(elements.exchanges);

		if(elements.query){
			elements.query.addEvents({
				'focus':function(e){
					var target = $(e.target);
					if(target.get('value') == this.options.defaultValue){
						target.set('value', '');
					}
				}.bind(this),

				'blur':function(e){
					var target = $(e.target);
					if(target.get('value') == ''){
						target.set('value', this.options.defaultValue);
					}
				}.bind(this)
			});
		}

		if(elements.type && elements.categorie && elements.exchanges){
			elements.type.addEvent('change', function(e){
				if(this.get('value') == 'cotations'){
					elements.categorie.showInline();
					elements.exchanges.showInline();
					elements.bloc.addClass('mot_rechercheWidth');
				}
				else{
					elements.categorie.hide();
					elements.exchanges.hide();
					elements.bloc.removeClass('mot_rechercheWidth');
				}
			});
		}

	}
});

//------------------------------------------------------------------------------
//
//									SETUP
//
//------------------------------------------------------------------------------
function setupExpandableDebug(debug){
	debug.addEvent('click', function(e){
		e = new Event(e).stop();

		var element = $(this.get('rel'));
		if($defined(element)) element.toggle();
	})
}



//------------------------------------------------------------------------------
//
//									CALLBACK
//
//------------------------------------------------------------------------------
function saveDisposition(column){
	var blockIds = new Hash();
	
	var i=0;
	column.element.getElements('div.html-block').each(function(element){
		window.workspaceBlocks.each(function(block){
			if(block.element.id == element.id){
				if(block.options.fixed===false){
					blockIds.set(i++, parseInt(element.id.substr(element.id.lastIndexOf('_')+1)));
				}
			}
		});				
	});
	
	var request = new Request.BoursoJSON({
		url:'/ajax/block/savedisposition.phtml',
		onComplete:function(result){
			result = new Hash(result);
			result.each(function(newId, oldId){
				$(oldId).id = newId;
			});
		}
	}).post({
		blocks:JSON.encode(blockIds),
		column:column.element.id,
		page:window.workspace.getPageID()
	});
}


function saveBlockStates(block){
	var request = new Request.BoursoJSON({'url':'/ajax/block/action.phtml'}).post({
		action:'saveblockstates',
		states:block.statesToSave,
		block:block.element.id,
		column:block.columnParent.element.id
	});
}

function dropBlockInColumn(draggable, newColumn, marker){
	marker.set('html', 'Chargement...');

	var request = new Request.BoursoHTML({
		'url':'/ajax/block/add.phtml',
		onComplete:function(tree, elements, html, javascript){
			if(tree.length == 0) {
				window.workspace.showErrorMessage("Impossible d'ajouter votre nouveau module");
				marker.destroy();
				return false;
			}

			var element = tree[0].replaces(marker);

			var block = new WorkspaceBlock(element, newColumn, {
				onDisplayChange:saveBlockStates,
				onClose:saveDisposition
			});

			setupHTMLComponents(this.element.getElement('.body'));

			saveDisposition(newColumn);
		}.bind(this)
	}).post({'path':draggable.id, 'column':newColumn.element.id, 'page':window.workspace.getPageID()});
}

function dropTableRow(dragElement, table, marker){
	marker.destroy();
	delete marker;

	var request = new Request.BoursoJSON({
		'url':'/ajax/btable/action.phtml',
		onRequest:function(){
			window.workspace.showOverlay(this.element);
		}.bind(this),

		onComplete:function(html){
			window.workspace.hideOverlay();

			//On remplace l'ancienne table
			var el = new Element('div').set('html', html);
			var newTable = el.getElement('table.btable');
			newTable.replaces(this.element);

			//On exécute les JS (Configuration de la table)
			html.stripScripts(true);

			//On recrée l'objet représentant la table
			new WorkspaceTable(newTable, {onDropRow:dropTableRow});
		}.bind(this)
	}).post({
		action:this.options.dropRowAction,
		id:this.options.dropRowData,
		symbol:dragElement.retrieve('dragData')
	});
}

//------------------------------------------------------------------------------
//
//								NOTIFICATION SYSTEM
//
//------------------------------------------------------------------------------
var Roar = new Class({

	Implements: [Options, Events, Chain],

	options: {
		duration: 3000,
		position: 'upperLeft',
		container: null,
		bodyFx: null,
		itemFx: null,
		margin: {x: 10, y: 10},
		offset: 10,
		className: 'roar',
		classColor: '',
		onShow: $empty,
		onHide: $empty,
		onRender: $empty
	},

	initialize: function(options) {
		this.setOptions(options);
		this.items = [];
		this.container = $(this.options.container) || document;
	},

	alert: function(title, message, options) {
		if(isStreaming==true) {
			hideEmbed();
		}
		var params = Array.link(arguments, {title: String.type, message: String.type, options: Object.type});
		if(params.title) {
			var items = [new Element('h3', {'html': $pick(params.title, '')})];
		} else {
			var items = [];
		}
		var _p = new Element('p', {'html': params.message});
		if (params.message) items.push(_p);
		return this.inject(items, params.options);
	},

	inject: function(elements, options) {
		if (!this.body) this.render();
		options = options || {};

		var offset = [-this.options.offset, 0];
		var last = this.items.getLast();
		if (last) {
			offset[0] = last.retrieve('roar:offset');
			offset[1] = offset[0] + last.offsetHeight + this.options.offset;
		}
		var to = {'opacity': 1};
		to[this.align.y] = offset;

		var item = new Element('div', {
			'class': this.options.className,
			'opacity': 0
		}).adopt(
			new Element('div', {
				'class': 'roar-bg'+(this.options.classColor ? ' '+this.options.classColor : ''),
				'opacity': 0.9
			}),
			elements
		);

		

		item.setStyle(this.align.x, 0).store('roar:offset', offset[1]).set('morph', $merge({
			unit: 'px',
			link: 'cancel',
			onStart: Chain.prototype.clearChain,
			transition: Fx.Transitions.Back.easeOut
		}, this.options.itemFx));

		var remove = this.remove.create({
			bind: this,
			arguments: [item],
			delay: 10
		});
		this.items.push(item.addEvent('click', remove));

		if (this.options.duration) {
			var over = false;
			var trigger = (function() {
				trigger = null;
				if (!over) remove();
			}).delay(this.options.duration);
			item.addEvents({
				mouseover: function() {
					over = true;
				},
				mouseout: function() {
					over = false;
					if (!trigger) remove();
				}
			});
		}
		item.inject(this.body).morph(to);
		
		//Hack iframe
		//this.iframe = window.workspace.getHackIframe(this.item.getCoordinates());
		//this.iframe.show();
		
		return this.fireEvent('onShow', [item, this.items.length]);
	},

	remove: function(item) {
		var index = this.items.indexOf(item);
		if (index == -1) return this;
		this.items.splice(index, 1);
		item.removeEvents();
		var to = {opacity: 0};
		to[this.align.y] = item.getStyle(this.align.y).toInt() - item.offsetHeight - this.options.offset;
		item.morph(to).get('morph').chain(item.destroy.bind(item));
		return this.fireEvent('onHide', [item, this.items.length]).callChain(item);
	},

	empty: function() {
		while (this.items.length) this.remove(this.items[0]);
		return this;
	},

	render: function() {
		this.position = this.options.position;
		if ($type(this.position) == 'string') {
			var position = {x: 'center', y: 'center'};
			this.align = {x: 'left', y: 'top'};
			if ((/left|west/i).test(this.position)) position.x = 'left';
			else if ((/right|east/i).test(this.position)) this.align.x = position.x = 'right';
			if ((/upper|top|north/i).test(this.position)) position.y = 'top';
			else if ((/bottom|lower|south/i).test(this.position)) this.align.y = position.y = 'bottom';
			this.position = position;
		}

		this.body = new Element('div', {'class': 'roar-body'}).inject(document.body);
		if (Browser.Engine.trident4) this.body.addClass('roar-body-ugly');
		this.moveTo = this.body.setStyles.bind(this.body);
		this.reposition();
		if (this.options.bodyFx) {
			var morph = new Fx.Morph(this.body, $merge({
				unit: 'px',
				chain: 'cancel',
				transition: Fx.Transitions.Circ.easeOut
			}, this.options.bodyFx));
			this.moveTo = morph.start.bind(morph);
		}
		var repos = this.reposition.bind(this);
		window.addEvents({
			scroll: repos,
			resize: repos
		});
		this.fireEvent('onRender', this.body);
	},

	reposition: function() {
		var max = document.getCoordinates(), scroll = document.getScroll(), margin = this.options.margin;
		max.left += scroll.x;
		max.right += scroll.x;
		max.top += scroll.y;
		max.bottom += scroll.y;
		var rel = ($type(this.container) == 'element') ? this.container.getCoordinates() : max;
		this.moveTo({
			left: (this.position.x == 'right')
				? (Math.min(rel.right, max.right) - margin.x)
				: (Math.max(rel.left, max.left) + margin.x),
			top: (this.position.y == 'bottom')
				? (Math.min(rel.bottom, max.bottom) - margin.y)
				: (Math.max(rel.top, max.top) + margin.y)
		});
	}
});


var WorkspaceCarousel = new Class({
	Implements: [Options],

	options:{
		itemwidth:400
	},

	initialize: function(carousel, slider, options){
		this.setOptions(options);

		window.workspaceCarousel.set(carousel.id, this);

		this.carousel = carousel;
		this.sliderItems = slider.getElements('li');
		this.items = this.carousel.getElements('li'); // The different elements, this is an array
		this.maxmargin = (this.items.length * this.options.itemwidth) - this.options.itemwidth;

		this.animation = new Fx.Tween(this.carousel, {duration: 500});

		// Set up the 'next' and 'previous' buttons
		slider.getFirst().removeEvents('click');
		slider.getLast().removeEvents('click');
		slider.getFirst().addEvent('click', this.previousItem.bind(this));
		slider.getLast().addEvent('click', this.nextItem.bind(this));

//		this.timer = this.nextItem.delay(10000, this);
	},

	nextItem: function(){
		var pos = parseInt(this.carousel.getStyle('left'));

		var newposition = (pos == -this.maxmargin) ? 0 : (pos - this.options.itemwidth);
		this.animation.start('left', newposition);

		this.hightlightSlide(Math.abs(newposition) / this.options.itemwidth);

		$clear(this.timer);
//		this.timer = this.nextItem.delay(5000, this);
	},

	previousItem:function(){
		var pos = parseInt(this.carousel.getStyle('left'));

		var newposition = (pos == 0) ?  -this.maxmargin : (pos + this.options.itemwidth);
		this.animation.start('left', newposition);

		this.hightlightSlide(Math.abs(newposition) / this.options.itemwidth);

		$clear(this.timer);
//		this.timer = this.nextItem.delay(5000, this);
	},

	hightlightSlide:function(idItem){
		this.sliderItems.removeClass('selected');
		this.sliderItems.each(function(item){
			if(item.hasClass(idItem)){
				item.addClass('selected');
			}
		});
	},

	destroy:function(){
		$clear(this.timer);
		this.carousel.destroy();
		delete this;
	}
});

var WorkspaceFlashGraph = new Class({
	config:false,

	swiff:false,

	initialize:function(element){
		this.element = $(element);

		window.workspaceGraphs.set(this.element.id, this);

		this.config = window.config.graphics[this.element.id] || {};

		if(this.config.show){
			this.show();
		}
	},

	show:function(){
		if(!this.swiff){
			if(Browser.Plugins.Flash.version >= 8){
				new Swiff(
					this.config.url,
					this.config.parameters
				);
			}
			else{
				this.element.set('html', this.config.urlCGI);
			}

			this.swiff = true;
		}
	},

	destroy:function(){
		this.element.destroy();
		delete this;
	}
});


function balert(msg, title){
	window.workspace.alert(msg, title);
}


function bnotify(msg, title){
	window.workspace.showNotification(msg, title);
}

function hideEmbed() {
	_liste = document.getElementsByTagName('embed');
	if(_liste.length==0)
		_liste = document.getElementsByTagName('object');

	for(i=0;i<_liste.length;i++) {
		if(_liste[i].style)
			_liste[i].style.visibility='hidden';
	}
	setTimeout('showEmbed()',3000);
	
}
function showEmbed() {
	_liste = document.getElementsByTagName('embed');
	if(_liste.length==0)
		_liste = document.getElementsByTagName('object');
	for(i=0;i<_liste.length;i++) {
		if(_liste[i].style)
			_liste[i].style.visibility='visible';
	}
}

function nostreaming() {
	if(typeof(isStreaming)!='undefined' && isStreaming) {
		window.workspace.showError('D\351sactivez le streaming pour utiliser cette fonctionalit\351',false);
		return false;
	}
	return true;
}

var BoursoUtils = {};
BoursoUtils = {
	detectAcrobat: function(){
		var isAcrobat = false;  
		var version = null;  
		if (window.ActiveXObject) {  
		    var control = null;  
		    try {  
		        // AcroPDF.PDF is used by version 7 and later  
		        control = new ActiveXObject('AcroPDF.PDF');  
		    } catch (e) {  
		         
		    }  
		    if (!control) {  
		        try {  
		            // PDF.PdfCtrl is used by version 6 and earlier  
		            control = new ActiveXObject('PDF.PdfCtrl');  
		        } catch (e) {  
		           
		        }  
		    }  
		    if (control) {  
		        isAcrobat = true;
		    }  
		} 
		else 
		{
			var testAcrobat = navigator.mimeTypes && navigator.mimeTypes["application/pdf"] && navigator.mimeTypes["application/pdf"].enabledPlugin;
		
			if (testAcrobat == undefined)
			{
				isAcrobat = false;
			}
			else
			{
				isAcrobat = true;
			}
		}
		
		return isAcrobat;
	},
	
	checkHighRes: function(){
		var isHigh = true;
		if (screen.height<=800){
			isHigh = false;
		}
		return isHigh;
	}
	
} 


// spécifique au forum

function showTooltip(id){
    if(_tt = $('tooltip_' + id)) {
	    _tt.style.display = "block";
	    x = _findPosX($('link_' + id));
	    y = _findPosY($('link_' + id));
	
	    _tt.style.left = x;
	    _tt.style.top = y + 20;
    }
}

function hideTooltip(id){
    if(_tt = $('tooltip_' + id)) {
    	_tt.style.display = "none";
    }
}

function _findPosX(obj){
	var curleft = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}

	else if (obj.x)
		curleft += obj.x;

	return curleft;
}


function _findPosY(obj){
	var curtop = 0;

	if (obj.offsetParent){
		while (obj.offsetParent){
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}

	else if (obj.y)
		curtop += obj.y;

	return curtop;
}


function getContentMessage(id_message,action) {
	_file = $('file').value;
	_symbole=$('symbole').value;
	_p=$('p').value;
	new Request.Bourso({
      'url' : '/forum/messageContent.phtml' ,
		'data' : 'id_message='+id_message+'&file='+_file+'&symbole='+_symbole+'&p='+_p+(action ? '&action='+action:''), 
      'onRequest' : function() { },
      'onSuccess' : function(html) {
	      	if(html) {
	      			//alert(html);
	      			tab = html.split('|');
	      			_id_message = tab[0];
	      			rang_ref = tab[1];
					
					// encadrer le message lu
					if(_div_message = $('link_'+_id_message)) {
						_classes = _div_message.className;
						_classes = _classes+' cur_message';
						_div_message.className = _classes;
					} else {
						// si le message existe, mais n'est pas affiché sur la page en cours : il faut changer de page
						_p = $('p').value;
						_max_id_message = $('max_id_message').value;
						
						if(_id_message > _max_id_message) {
							_p++;
						} else {
							_p--;
						}
						
						if(USE_RWURL) {
							window.open($('url_page').value + (_p>1 ? '-'+_p : '') + '?id_message='+_id_message,'_self');
						} else {
							window.open('/forum/message.phtml?id_message='+_id_message+'&p='+_p,'_self');
						}
						return false;
					}

					// enlever le cadre autour du message précédent
					if(_prec_obj = $('link_'+$('id_message').value)) {
						_classes = _prec_obj.className;
						_classes = _classes.replace('cur_message','');
						_prec_obj.className = _classes;
					}
					reco_ok=true;

					// afficher le contenu du message
	      			html = html.replace(_id_message+'|'+rang_ref+'|','');
	      			$('main_message_div').innerHTML = html;
					setupHTMLComponents('main_message_div');
					
					// mise à jour du rang du message dans la pagination des messages
					_elems = document.getElementsByTagName('span');
					for(i=0;i<_elems.length;i++) {
						_class = _elems[i].getAttribute('cur');
						if(_class == 'true') {
							_elems[i].innerHTML = Number(rang_ref);
						}
					}
					
					// retour en haut de la page
					window.scrollTo(0,0);
				}
		}
    }
    ).post();
}
function recommander(reco_id) {
	if(!reco_ok) {
		window.workspace.showError('Vous avez d\351j\340 recommand\351 ce message.');
		return false;
	}
	_url = '/forum/reco.phtml';
	_data = 'reco_id='+reco_id;

	new Request.Bourso({
      'url' : _url ,
		'data' : _data, 
      'onRequest' : function() { },
      'onSuccess' : function(html) {
			if(html=='ok') {
				$('nb_recos').innerHTML = Number($('nb_recos').innerHTML) + 1;
				bnotify('Message recommand\351 avec succ\350s');
				reco_ok=false;
			} else {
				window.workspace.showError(html);
			}
		}
    }
    ).post();
}

function messagePrev(obj) {
	disableSelection(obj);
	getContentMessage($('id_message').value,'prev');
}
function messageNext(obj) {
	disableSelection(obj);
	getContentMessage($('id_message').value,'next');
}

function disableSelection(target){
	if (typeof target.onselectstart!="undefined") //IE route
		target.onselectstart=function(){return false}
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
		target.style.MozUserSelect="none"
	else //All other route (ie: Opera)
		target.onmousedown=function(){return false}
}

