var AJAX_BLOCK_PATH = (window.location.href.indexOf('/trader-terminal/') >= 0) ? '/trader-terminal/ajax/block/' : '/ajax/block/';

window.addEvent('domready', function(){
	window.workspace = new Workspace();
	
	//if ($defined($('content'))) document.standardPage = new standardPage();
	
	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();
	
	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);
	});

 	try {
 		new multiBox({containerToUpdate: container});
 	}
 	catch(e) {
 	}
	

	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
		});
	});
	
	container.getElements('div.toggling').each(function(toggling){
		toggling.getElements('div.toggler').addEvent('click', function(e){
			var element = $('element' + this.get('id').substr(5));

			if(element.isVisible()){
				element.hide();
				this.removeClass('closed');
				this.addClass('open');
			}
			else{
				element.show();
				this.removeClass('open');
				this.addClass('closed');
			}


			var request = new Request({
				'url':'/ajax/mysettings.phtml',
				'data':{'id' : this.get('id'), 'visible' : (element.isVisible()) ? 'visible' : 'hidden'}
			});

			request.post();
		});

		toggling.getElements('div.toggler a').addEvent('click', function(e){
			e = new Event(e).stop();
			window.location.href = this.href;
		});
	});
	
	
	
	$$('img[src=/images/iconos/icono_que_hace_mercado.gif]').addEvent('click',function(e){
			e = new Event(e).stop();
			window.open('/popups/hace_mercado.phtml', 'indices', 'width=300, height=750, resizable=yes, scrollbars=yes, menubar=no, status=no');
			//new WorkspaceModalbox({'href':'/popups/hace_mercado.phtml', 'width':300, 'height':490, 'title':'Que hace el mercado'});
		}
	)
	
	setupButtons(container);
	setupFields(container);
	setupComboboxes(container);
}

// buttons
function setupButtons(container) {
	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";
    	var combo = 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;
		}
	},
	strongHide: function() {
		this.setStyle('display','none');
		this.disabled = true;
		return this;
	},
	strongShow: function(display) {
		this.show(display);
		this.disabled = false;
		return this;
	},
	formShow: function(display) {
		this.strongShow(display);
		if ($('datepicker-'+this.id+''))
			$('datepicker-'+this.id+'').show(display);
		if ($$('label[for='+this.id+']'))
			$$('label[for='+this.id+']').show();
		return this;
	},
	formHide: function() {
		this.strongHide();
		if ($('datepicker-'+this.id+''))
			$('datepicker-'+this.id+'').hide();
		if ($$('label[for='+this.id+']'))
			$$('label[for='+this.id+']').hide();
		return this;
	},
  	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,
			//onTimeout:$empty,
			encoding:'ISO-8859-1',
			timeout:false
		}, options);

		this.parent(options);
	},
	
	send: function(options){
		var timeout = (this.options.timeout || (options ? options.timeout: null));
		if (timeout) {
			this.timeoutTimer = window.setTimeout(this.callTimeout.bindWithEvent(this), timeout);
			this.addEvent('onComplete', this.removeTimer);
		}
		return this.parent(options);
	},

	defaultOnFailure: function(){
		window.workspace.showError('An error has occurred.', 'Please try again shortly.');
		this.hideOverlay();
	},

	defaultOnCancel: function(){
		this.hideOverlay();
	},

	defaultOnException:function(){
		window.workspace.showError('An error has occurred.', 'Please try again shortly.');
		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;
		}		
	},
	
	/**
	 * lock the timeout & start the timer
	 *
	 * @returns {Request} return this
	 */
	callTimeout: function () {
		if (!this.running) return this;
		this.running = false;
		this.xhr.abort();
		this.xhr.onreadystatechange = $empty;
		this.xhr = new Browser.Request();
		this.onFailure();
		this.fireEvent('onTimeout');
		return this;
	},
 
	/**
	 * clear current timeout
	 * 
	 * @returns undefined
	 */
	removeTimer: function() {
		window.clearTimeout(this.timeoutTimer);
	}
});

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){
			window.workspace.showOverlay(this.options.update).addClass('ajax-loading');
			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('An error has occurred.', 'Please try again shortly.');
		}

		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){
			}
		}
		
		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){
			window.workspace.showOverlay(this.options.update).addClass('ajax-loading');
		}
	},

	end:function(){
		if(this.options.update){
			window.workspace.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);
		this.isStreaming = false;
		
		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 = new Element('div', {id:'workspace_overlay'}).setStyles({'opacity':0.2, 'background-color':'black', 'display':'none', 'z-index':999, 'position':'absolute'}).inject(document.body);
		}

		if(element) {
			this.overlay.setStyles(element.getCoordinates());
		}

		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(){
		// this doesnt work if one access /trader-terminal/ and then /trader-terminal/index.php
		//var page = window.location.pathname;

		// so we must replace the final '/' with '/index.phtml'
		var page = window.location.pathname.replace(/\/$/, '/index.phtml');

		// and so we dont need this test
		//return (page == '/') 
		//? 'index'
		//: page.substring(1, page.lastIndexOf('.')).replace(/\//, '_');

		return 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,

	stopDragging: $empty,

	dragging: $empty,

	dropping:$empty,

	createMarker: $empty
});


//------------------------------------------------------------------------------
//
//									COLUMN - DROP
//------------------------------------------------------------------------------
var WorkspaceColumn = new Class({
	Extends: DropElement,

	initialize: function(element, options){
		// The default config is defined in the object window.columnsConfig, defined in the page itself
		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:onBlockClose
			});
		}.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){
		// set a dotted border to the draggable area
		//this.element.style.border='1px dotted #00519E';
		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)){
			// Moves the block in the current column
			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);
	}
});

//	JBROTA : add carousel
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 standardPage = new Class({

	initialize: function(){
		this.navBar();
		this.menuSec();
		this.setPrint();
		this.fuentes();
	},

	navBar: function(){
		if(!$defined($("navBar"))) return;

		var cTr = cTl = null;
		$$('#navBar a').each(function(el) {
			cTr = this.createElementsCurves("cTr");
			cTl = this.createElementsCurves("cTl");
			el.appendChild(cTr);
			el.appendChild(cTl);
			cTr = cTl = null;
		}.bind(this));
	},

	menuSec: function(){
		if(!$defined($("menuSec"))) return;

		var cTr = cTl = null;
		$$('#menuSec a').each(function(el) {
			cTr = this.createElementsCurves("cTr");
			cTl = this.createElementsCurves("cTl");
			el.appendChild(cTr);
			el.appendChild(cTl);
			cTr = cTl = null;
		}.bind(this));
	},

	createElementsCurves:function(style){
		var element = document.createElement("div");
		element.className = style + " sp";
		element.appendChild(document.createTextNode(" "));
		return element;
	},

	setPrint:function(){
		var utilidades = $("content").getElements("utilidades");
		var liElement = aElement = null;
		if(utilidades.length != 0){
			liElement = document.createElement("li");
			aElement = document.createElement("a");
			aElement.className = "print";
			aElement.href = "javascript:window.print()";
			aElement.appendChild(document.createTextNode("Imprimir"));
			liElement.appendChild(aElement);
			utilidades[0].appendChild(liElement);
		}
	}
/*
	fuentes:function(){
		var contador=0;
		var rangoAumento=15;
		var rangoDisminucion=15;
		var interSuma=0;
		var interResta=0;
		//document.getElementById("header").style.marginBottom=2.5 + "em";
		var sp1 = document.createElement("ul");
		sp1.setAttribute("id", "tamanno");
		var sp2=document.createElement("li");
		var sp3=new Element("a");
		sp3.setAttribute("href","#");
		sp3.setAttribute("id","aumenta");
		sp3.setAttribute("title","Aumenta el tamaño de la letra")
		var sp4=document.createElement("img")
		sp4.setAttribute("src","/images/ico_aumenta.gif")
		sp4.setAttribute("alt","Aumenta el tamaño de la letra")
		sp4.setAttribute("title","Aumenta el tamaño de la letra")
		var sp5=document.createElement("li")
		var sp6= new Element("a");
		sp6.setAttribute("href","#")
		sp6.setAttribute("id","disminuye")
		sp6.setAttribute("title","Disminuye el tamaño de la letra")
		var sp7=document.createElement("img")
		sp7.setAttribute("src","/images/ico_disminuye.gif")
		sp7.setAttribute("alt","Disminuye el tamaño de la letra")
		sp7.setAttribute("title","Disminuye el tamaño de la letra")
		var nodo1=sp1.appendChild(sp2)
		var nodo2=nodo1.appendChild(sp3)
		nodo2.appendChild(sp4)
		var nodo3=sp1.appendChild(sp5)
		var nodo4=nodo3.appendChild(sp6)
		nodo4.appendChild(sp7)
		var sp8 = document.getElementById("logo").parentNode;
	 	var parentDiv = sp8.parentNode;
		parentDiv.insertBefore(sp1, sp8);

		sp3.addEvent('click', function(){
			interSuma++;
			if(interSuma==1 && interResta==1){document.getElementsByTagName("body")[0].style.fontSize="62.5%";interSuma=0; interResta=0;}
			else if(interSuma==1 && interResta==2){document.getElementsByTagName("body")[0].style.fontSize="50%"}
			else if(interSuma==2 && interResta==1){document.getElementsByTagName("body")[0].style.fontSize="70%"}
			else if(interSuma==2 && interResta==0){document.getElementsByTagName("body")[0].style.fontSize="80%"}
			else if(interSuma==1 && interResta==0){document.getElementsByTagName("body")[0].style.fontSize="70%"}
			else if(interSuma==2 && interResta==2){document.getElementsByTagName("body")[0].style.fontSize="62.5%";interSuma=0; interResta=0;}
			if(interSuma==3) {interSuma=2}
			return false;
		});

		sp6.addEvent('click', function(){
			interResta++;
			if(interResta==1 && interSuma==0){document.getElementsByTagName("body")[0].style.fontSize="50%"}
			else if(interResta==1 && interSuma==1){document.getElementsByTagName("body")[0].style.fontSize="62.5%";interSuma=0; interResta=0;}
			else if(interResta==1 && interSuma==2){document.getElementsByTagName("body")[0].style.fontSize="70%"}
			else if(interResta==2 && interSuma==0){document.getElementsByTagName("body")[0].style.fontSize="45%"}
			else if(interResta==2 && interSuma==1){document.getElementsByTagName("body")[0].style.fontSize="50%"}
			else if(interResta==2 && interSuma==2){document.getElementsByTagName("body")[0].style.fontSize="62.5%";interSuma=0; interResta=0;}
			if(interResta==3) {interResta=2;interSuma=0}
			return false;
		});
	}
*/
});


//------------------------------------------------------------------------------
//
//										TABLES - DROP
//
//------------------------------------------------------------------------------
var WorkspaceTable = new Class({
	Extends: DropElement,
	
	Implements: [Options],

	options: {
		'sortby':'-1'
	},

	element: false,

	initialize: function(element, options){
		this.element = element;
		this.setOptions(options);

		this.element.getElements('thead a.sort').addEvent('click', function(e){
			e = new Event(e).stop();
			this.sort($(e.target));
		}.bind(this));

		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');

		// Retrieves the data if not already done
		if(!$defined(this.values)){
			this.values = [];

			tableRows.each(function(row, index){
				var cols = [];

				row.getChildren().each(function(col, index){
					// removes any HTML such as color, img, etc..
					cols[index] = col.get('html');
				});

				this.values[index] = cols;
			}.bind(this));

			this.anchors = this.element.getElements('thead tr th a')
		}

		// Sets the order and type of sort
		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';
		}


		// Perform data sort
		var i=0;

		this.values.sort(function(r1, r2){
			var value1 = '';			
			var value2 = '';			
			if(r1[this.options.sortby]) {
				value1 = r1[this.options.sortby].replace(/(<[^>]*>)|(<\/[^>]*>|(\s*))/gi, '');
			}
			if(r2[this.options.sortby]) {
				value2 = r2[this.options.sortby].replace(/(<[^>]*>)|(<\/[^>]*>|(\s*))/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]*.*$');

				if(regexp.test(value1))
					value1 = parseFloat(value1.replace(/\./g, '').replace(/,/g, '.'));
				else
					value1 = value1.toLowerCase();

				if(regexp.test(value2))
					value2 = parseFloat(value2.replace(/\./g, '').replace(/,/g, '.'));
				else
					value2 = value2.toLowerCase();

				if(value1 > value2)
					return ((this.sortorder == 'asc') ? 1 : -1);
				else if(value1 < value2)
					return ((this.sortorder == 'asc') ? -1 : 1);
				else
					return 0;
			}
		}.bind(this));

		// Redraw table
		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]);
			}
		}

		// Update the class that displays the content
		var anchors = this.element.getElements('thead a');
		anchors.removeClass('asc');
		anchors.removeClass('desc');

		if(this.sortorder == 'asc')
			anchor.addClass('asc');
		else
			anchor.addClass('desc');
	}
});





//------------------------------------------------------------------------------
//
//									DRAG ELEMENT
//
//------------------------------------------------------------------------------
var DragElement = new Class({
	Implements: [Options, Events],

	options:{
		'drag':'none',
		'data':'',
		'iframehack':false
	},

	initialize:function(element, options){
		this.element = $(element);
		this.setOptions(options);
	},

	isDraggable:function(){
		return this.options.drag != 'none';
	},

	getDroppables:function(){
		return [];
	},
	
	getSnap:function() {
		return 5;
	},

	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(){
		this.element.store('data', this.options.data);
		this.element.store('styles', this.element.getStyles());
		this.element.store('coordinates', this.element.getCoordinates());
		return this.element;
	},

	startDrag:function(e){
		e = new Event(e).stop();
		
		var draggable = this.buildDraggable();
		//Fix
		draggable.ondragstart = $lambda(false);
		new Drag(draggable, {
			snap:this.getSnap(),
			modifiers: this.getDragModifiers(),
			limit: this.getDragLimit(draggable),
			onDrag:this.drag.bind(this),
			onBeforeStart:this.beforeStart.bind(this),
			onSnap:this.snap.bind(this),
			onComplete:this.complete.bind(this),
			onCancel:this.cancel.bind(this),
			preventDefault: true,
			stopPropagation: true
		}).detach().start(e);
	},
	
	beforeStart:function(draggable){
		draggable.setStyles({display:'none'});
	},
	
	snap:function(draggable) {
		if(draggable.getStyle('display') == 'none')
			draggable.setStyles({display:''});
		
		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
		if(this.options.iframehack) {
			this.iframe = window.workspace.getHackIframe(draggable.getCoordinates());
			this.iframe.show();
		}
	},

	drag:function(draggable){		
		if(this.options.iframehack) {
			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){
		if(draggable.getStyle('display') == 'none') {
			
		}
		else {
			this.endDrag(draggable);
		}
		if(this.marker) {
			this.marker.destroy();
			delete this.marker;
		}
		draggable.dispose();
	},
	
	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',iframehack:true});
		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, .hd 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('Are you sure ?')){
					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_PATH + '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(){
		if($defined(window.__STREAMING)){
			window.__STREAMING.removeDOMElements(this.element.getElements('*[id^=brs-sl]'));
		}
		
		window.workspaceBlocks.erase(window.workspaceBlocks.keyOf(this));
		this.columnParent.delBlock(this.element);
		this.element.destroy();
				
		this.fireEvent('close', this.columnParent);
	},
	
	cancel:function(draggable){
		this.endDrag(draggable);
		
		if(this.marker) {
			this.marker.destroy();
			delete this.marker;
		}
	},

	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 {y:'top'};
	},
	
	getSnap:function(){
		return 0;
	},
	
	beforeStart:function(draggable){
		this.marker = this.columnParent.createMarker(draggable).inject(this.element, 'after');
		this.snap(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){
		
		if($defined(window.__STREAMING)){
			window.__STREAMING.removeDOMElements(this.element.getElements('*[id^=brs-sl]'));
		}
		
		options = $merge({
			displayFormCustomization:false,
			saveCustomization:false,
			parameters:false
		}, options);

		var url = AJAX_BLOCK_PATH +'/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;
	}
});

//----------------------------------------
//
//			MYBOURSO
//
//---------------------------------------
var WorkspaceMyBourso = new Class({
	Implements: [Options, Events],

	options:{
		//onLoad:$empty,
		data:''
	},

	initialize:function(){
		this.element = new Element('div', {'class':'myBourso'});
		this.element.set('html', 'In progress...');
		this.element.inject($('content'), 'before');
		
	},

	load:function(options){
		this.setOptions(options);

		new Request.BoursoHTML({
			url: (window.location.pathname.split( '/' )[1] == 'trader-terminal') ? '/trader-terminal/customization.php' : '/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();
	}
});

//----------------------------------------------
//
//		MINICUSTOMIZATIONBLOCK
//
//----------------------------------------------
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 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;
	}
});

var WorkspaceModalbox = new Class({
	Implements: [Options, Events],

	options:{
		'width':200,
		'height':150,
		'overlay':true,
		'href':false,
		'title':false,
		'modal':true,
		'method':'get',
		'fixed':false
	},

	initialize:function(options){
		this.setOptions(options);

		window.workspaceModalbox = this;

		if(!$defined($('wmb_window'))){
			this.overlay = new Element('div').setProperty('id', 'wmb_overlay').setStyles({'opacity':0.8}).inject(document.body);
			// the center element
			this.window = new Element('div').setProperty('id', 'wmb_window').setStyles({
				marginLeft: '-'+(this.options.width/2)+'px',
				display: 'none'
			}).inject(document.body);

			this.top = new Element('div').setProperty('id', 'wmb_top').injectInside(this.window);
			this.closelink = new Element('a').setProperties({'id': 'wmb_closelink', 'class': 'click'}).injectInside(this.top);
			this.title = new Element('div').setProperty('id', 'wmb_title').injectInside(this.top);
			this.contents = new Element('div').setProperty('id', 'wmb_contents').inject(this.window);

			//Events
			this.closelink.addEvent('click', this.close.bind(this));
			this.overlay.addEvent('click', this.close.bind(this));
		}
		else{
			this.overlay = $('wmb_overlay');
			this.window = $('wmb_window');
			this.top = $('wmb_top');
			this.closelink = $('wmb_closelink');
			this.title = $('wmb_title');
			this.contents = $('wmb_contents');
		}

		this.title.set('text', this.options.title);

		this.open();
	},

	open:function(){
		window.addEvent('scroll', this.position.bind(this));
		window.addEvent('resize', this.position.bind(this));
		window.addEvent('keydown', this.keyboardListener.bindWithEvent(this));

		this.window.setStyles ({width:this.options.width + "px", height: this.options.height + "px"});
		this.contents.setStyles({height: (this.options.height - 34) + "px"});

		this.position();

		this.hiddenElements = $A($$('select, applet, object, embed'));
		this.hiddenElements.each(function(el){el.style.visibility='hidden'});

		this.window.setStyle('display', '');

		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()));
		}

	},

	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){
		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.setStyle('display', '');

		this.window.destroy();
		this.overlay.destroy();

		window.workspaceModalbox = null;
	},

	loadContents:function(url, data, method){

		method = method || 'get';

		var request = new Request.BoursoHTML({
			url:url,
			update:this.contents,
			data:data,
			onComplete:function(){
				this.contents.getElements('.close').addEvent('click', this.close.bind(this));

				this.contents.getElements('form.bform').each(function(form){
					form.addEvent('submit', function(e){
						e = new Event(e).stop();
						this.loadContents(form.action, form.toQueryString(), 'post');
					}.bind(this));
				}.bind(this));
			}.bind(this)
		});

		if(method == 'get')
			request.get();
		else
			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')) {
			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'});
	},
	
	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);
	}
	
});

//------------------------------------------------------------------------------
//
//									CALLBACK
//
//------------------------------------------------------------------------------
function onBlockClose(column){
	saveDisposition(column,	function(){
		if(window.workspace.myBourso)
			window.workspace.myBourso.load({data:'myBoursoCustomization[menu]='+column.element.get('id')});
	});
}

function saveDisposition(column, callback){
	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){
					// we rely on the blocks's id (element.id.substr(element.id.lastIndexOf('_')+1)),
					// not on its position. This way we can have several instances of the same block
					blockIds.set(i, parseInt(element.id.substr(element.id.lastIndexOf('_')+1)));
					element.set('id', element.id.substr(0, element.id.lastIndexOf('_') + 1) + i++);
				}
			}
		});				
	});

	var request = new Request.BoursoJSON({
		url:AJAX_BLOCK_PATH + 'savedisposition.phtml',
		onComplete:function(result){
			result = new Hash(result);
			result.each(function(newId, oldId){
				if($(oldId))
					$(oldId).id = newId;
			});
			if(callback)
				callback();
		}
	}).post({
		blocks:JSON.encode(blockIds),
		column:column.element.id,
		page:window.workspace.getPageID()
	});
}


function saveBlockStates(block){
	var request = new Request.BoursoJSON({'url': AJAX_BLOCK_PATH + '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', 'In progress...');
	
	/*
		hide dummy block after drop, prevent double drop same block
	*/
	if($(draggable).get('id') && $('mini_'+$(draggable).get('id'))) {
		$('mini_'+$(draggable).get('id')).hide();
	}
	
	var request = new Request.BoursoHTML({
		'url':AJAX_BLOCK_PATH + 'add.phtml',
		evalScripts:false,
		onComplete:function(tree, elements, html, javascript){
			if(tree.length == 0) {
				window.workspace.showErrorMessage("Unable to add block.");
				marker.destroy();
				return false;
			}
			//console.log(tree[0]);
			var element = tree[0].replaces(marker);
			
			$exec(javascript);

			var block = new WorkspaceBlock(element, newColumn, {
				onDisplayChange:saveBlockStates,
				onClose:onBlockClose
			});

			setupHTMLComponents(this.element.getElement('.body'));

			saveDisposition(newColumn);

			/*
				Remove dummy block after drop
			*/			
			if($(draggable).get('id') && $('mini_'+$(draggable).get('id'))) {
				$('mini_'+$(draggable).get('id')).dispose();
			}
			
			return true;
		}.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_BLOCK_PATH + '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(window.workspace.isStreamingActiv()) {
			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);
		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)
		});
	}
});


function balert(msg, title){
	window.workspace.alert(msg, title);
}


function bnotify(msg, title){
	window.workspace.showNotification(msg, title);
}


function hideEmbed() {
	$$('applet,object,embed').each(function(el){el.style.visibility = 'hidden';});
	showEmbed.delay(3000);	
}
function showEmbed() {
	$$('applet,object,embed').each(function(el){el.style.visibility = 'visible';});
}

function nostreaming() {
	if(typeof(isStreaming)!='undefined' && isStreaming) {
		window.workspace.showError('Deactivate streaming to use this feature',false);
		return false;
	}
	return true;
}

function adjustIFrameSize (iframeWindow,adjustX) {
	if (adjustX == undefined) {
		adjustX = false;
	}

	if (iframeWindow.document.height) {
		var iframeElement = parent.document.getElementById(iframeWindow.name);
		
		if (iframeElement){
			iframeElement.style.height = iframeWindow.document.height + 'px';
			if (adjustX)
				iframeElement.style.width = iframeWindow.document.width + 'px';
		}
	}
	else if (document.all) {
		var iframeElement = parent.document.all[iframeWindow.name];
		
		if (iframeElement){
			if (iframeWindow.document.compatMode && iframeWindow.document.compatMode != 'BackCompat')  {
				iframeElement.style.height = iframeWindow.document.documentElement.scrollHeight +  5 +  'px';
				if (adjustX)
					iframeElement.style.width = iframeWindow.document.documentElement.scrollWidth +  5 +  'px';
			}
			else {
				iframeElement.style.height = iframeWindow.document.body.scrollHeight  + 5 +  'px';
				if (adjustX)
					iframeElement.style.width = iframeWindow.document.body.scrollWidth  + 5 +  'px';
			}
		}
	}
}

