var Command = new Class.create({
	id: null,
	callback: null,
	undoCallback: null,

	initialize: function(id,callback,undoCallback){
		this.id = id;
		this.callback = function () { callback(); };
		this.undoCallback = undoCallback;
	},
	
	execute: function(){
		this.callback();
	},
	
	revert: function(){
		this.undoCallback();
	}
});

var CallbackCommand = new Class.create(Command,{

	callback: null,
	undoCallback: null,

	initialize: function(id,callback,undoCallback){
		this.id = id;
		this.callback = callback;
		this.undoCallback = undoCallback;
	},
	
	execute: function(){
		this.callback();
	},
	
	revert: function(){
		this.undoCallback();
	}
});

var UndoManager = new Class.create({
	
	id: null,
	present: null,
	commands: null,
	
	initialize: function(id){
		this.id = id;
		this.present = -1;
		this.commands = new Array();
	},
	
	reset: function(){
		this.initialize();
	},
	
	appendCommand: function(command){
		var next = this.present+1;
		var howMany = this.commands.length-this.present;
		this.commands.splice(next,howMany,command);
		this.present = next;
		document.fire('ws:undomanager');
	},
	
	pushCommand: function(command){
		var next = this.present+1;
		var howMany = this.commands.length-this.present;
		this.commands.splice(next,howMany,command);	
		this.redo();
	},
	
	canUndo: function(){
		if ((this.present>=0)&&(this.commands.length>0)){
			return true;
		}
		
		return false;
	},
	
	canRedo: function(){
		if (this.present<(this.commands.length-1)){
			return true;
		}
		return false;
	},
	
	redo: function(){
		if (this.commands.length==0) return;
		
		var next = this.present+1;
		if (this.commands[next]){
			this.present = next;
			this.commands[next].execute();
		}
		document.fire('ws:undomanager');
	},
	
	undo: function(){
		if (this.commands.length==0) return;
		if (this.present<0) return;
		
		if (this.commands[this.present]){
			this.commands[this.present].revert();
			this.present--;
		}
		document.fire('ws:undomanager');		
	},
	
	revert: function(){
		while(this.canUndo()){
			this.undo();
		}
	}
	
});


var ItemTickerManager = new Class.create({
	onTimeOut: function(idPrefix,maxItems,time,currentItemIndex) {
		var nextItemIndex = currentItemIndex + 1;
		if( nextItemIndex==maxItems ) {
			nextItemIndex = 0;
		}

		// Obtener el elemento actual y el siguiente, el actual se oculta, el siguiente se muestra
		var currentItem = $(idPrefix + currentItemIndex);
		var nextItem = $(idPrefix + nextItemIndex);

		// El proceso se cancelará si los dos itemId son iguales, lo que quiere decir que solo hay un elemento en la lista
		if( nextItemIndex==currentItemIndex ) {
			return;
		}

		// Puede que el elemento no exista, porque el usuario haya cambiado de página. En ese caso, simplemente
		// se cancela todo el proceso
		if( currentItem && nextItem ) {
			currentItem.hide();
			nextItem.show();
			setTimeout("itemTickerManager.onTimeOut('" +
						idPrefix + "'," +
						maxItems + "," + 
						time + "," +
						nextItemIndex + ")",time*1000);
		}
	},
	
	animationStep: function(tickerId,speedFactor,maxWidth) {
		var ticker = $(tickerId);
		if( ticker ) {
			var width = ticker.getWidth();
			var left = parseInt(ticker.style.left,10);
			if( isNaN(left) ) {
				left = 0;
			}
			if( left>-width ) {
				var newPos = left - 2;
				ticker.style.left = newPos + 'px';
			}
			else {
				var startPos = maxWidth;
				ticker.style.left = startPos + 'px';
			}
			setTimeout("itemTickerManager.animationStep('" +
							tickerId + "', " +
							speedFactor + ", " + maxWidth + ")",speedFactor*500);
		}
	}
});

var itemTickerManager = new ItemTickerManager();

var ItemTicker = new Class.create({
	initialize: function(idPrefix,maxItems,time) {
		setTimeout("itemTickerManager.onTimeOut('" + 
						idPrefix + "'," +
						maxItems + "," +
						time + ",0)",time*1000);
	}
});

var TextTicker = new Class.create({
	initialize: function(tickerId,speed,parentId) {
		var parent = $(parentId);
		if( parent ) {
			var tickerItems = $(parent).select('div');
			var totalWidth = 100;
			for( var item in tickerItems ) {
				var newItem = Element.extend(tickerItems[item]);
				if( newItem.className=='newsTickerItem' ) {
					totalWidth += newItem.getWidth();
				}
			}
			var tickerItemSeparators = $(parent).select('div.tickerItemSeparator');
			for( var newItem in tickerItems ) {
				newItem = Element.extend(tickerItems[item]);
				if( newItem.className=='tickerItemSeparator' ) {
					totalWidth += newItem.getWidth();
				}
			}
			if( $(tickerId) ) {
				$(tickerId).style.width = totalWidth + 'px';
			}
			setTimeout("itemTickerManager.animationStep('"+
						tickerId + "', " +
						1/speed + "," + parent.getWidth() +")",1.0/speed*100);
		}
	}
});


var MediaPickerButton = new Class.create({
	loadImageName: function(containerId,imageId,params) {

		var parameters = {};
		if (params){
			parameters = params;			
		}
		parameters.command = 'getImageName';
		parameters.style = system.getCurrentStyle();
		parameters.imageId = imageId;
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_image_picker_actions.php',{
			method:'post',
			parameters:parameters,
			onSuccess:function(transport) {
				$(containerId).innerHTML = transport.responseText;
			}
		});
	},
	
	loadImageGroupName: function(containerId,groupId,params) {
		
		var parameters = {};
		if (params){
			parameters = params;			
		}
		parameters.command = 'getImageGroupName';
		parameters.style = system.getCurrentStyle();
		parameters.groupId = groupId;
		
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_image_picker_actions.php',{
			method:'post',
			parameters:parameters,
			onSuccess:function(transport) {
				$(containerId).innerHTML = transport.responseText;
			}
		});
	},
	
	loadFileName: function(containerId,fileId,params) {
		
		var parameters = {};
		if (params){
			parameters = params;			
		}
		parameters.command = 'getFileName';
		parameters.style = system.getCurrentStyle();
		parameters.fileId = fileId;
		
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_file_picker_actions.php',{
			method:'post',
			parameters:parameters,
			onSuccess:function(transport) {
				$(containerId).innerHTML = transport.responseText;
			}
		});
	},
	
	loadVideoName: function(containerId,videoId,params) {
		
		var parameters = {};
		if (params){
			parameters = params;			
		}
		parameters.command = 'getVideoName';
		parameters.style = system.getCurrentStyle();
		parameters.videoId = videoId;
		
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_video_picker_actions.php',{
			method:'post',
			parameters:parameters,
			onSuccess:function(transport) {
				$(containerId).innerHTML = transport.responseText;
			}
		});
	},
	
	loadVideoGroupName: function(containerId,groupId,params) {

		var parameters = {};
		if (params){
			parameters = params;			
		}
		parameters.command = 'getVideoGroupName';
		parameters.style = system.getCurrentStyle();
		parameters.groupId = groupId;
		
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_video_picker_actions.php',{
			method:'post',
			parameters:parameters,
			onSuccess:function(transport) {
				$(containerId).innerHTML = transport.responseText;
			}
		});
	},
	
	loadFlashClipName: function(containerId,videoId,params) {
		
		var parameters = {};
		if (params){
			parameters = params;			
		}
		parameters.command = 'getFlashClipName';
		parameters.style = system.getCurrentStyle();
		parameters.videoId = videoId;
		
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_video_picker_actions.php',{
			method:'post',
			parameters:parameters,
			onSuccess:function(transport) {
				$(containerId).innerHTML = transport.responseText;
			}
		});
	},
	
	loadModelName: function(containerId,modelId,params) {
		
		var parameters = {};
		if (params){
			parameters = params;			
		}
		parameters.command = 'getModelName';
		parameters.style = system.getCurrentStyle();
		parameters.modelId = modelId;
		
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_model_picker_actions.php',{
			method:'post',
			parameters:parameters,
			onSuccess:function(transport) {
				$(containerId).innerHTML = transport.responseText;
			}
		});
	},
	
	loadSiteName: function(containerId,siteId) {
		this.loadName('_website_picker_actions.php','getSiteName',containerId,siteId);
	},
	
	loadSectionName: function(containerId,sectionId) {
		this.loadName('_website_picker_actions.php','getSectionName',containerId,sectionId);
	},
	
	loadPageName: function(containerId,pageId) {
		this.loadName('_website_picker_actions.php','getPageName',containerId,pageId);
	},
	
	loadName: function(actionFile,command,containerId,targetId) {
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/' + actionFile,{
			method:'post',
			parameters:{command:command,style:system.getCurrentStyle(),targetId:targetId},
			onSuccess:function(transport) {
				$(containerId).innerHTML = transport.responseText;
			}
		});
	}
});

var mediaPickerButton = new MediaPickerButton();

var TextTranslator = new Class.create({
	loadTextIntoContainer: function(languageCBoxId,textId,dstContainer) {
		var lang = $(languageCBoxId).value;
		var actionFile = system.getLibraryPath() + 'plasticbriqFramework/actions/_language_widget_actions.php';
		new Ajax.Request(actionFile,{
			method:'post',
			parameters:{command:'getTranslatedText',textId:textId,languageId:lang},
			onSuccess:function(transport){
				var container = $(dstContainer);
				container.value = transport.responseText;
			}
		});
	}
});

var PageBlockEditorWidget = new Class.create({
	
	initialize: function() {
		Event.observe(document,'keypress',function(event){ if (event.which==43){ $('pageBlock_add').onclick(); } });
	},
	
	showEditTitle: function(){
		$('PageTitleText').hide();
		$('PageTitleField').show();
		$('pageTitle').focus();
		$('pageTitle').select();
		$('pageTitle').setAttribute('onclick','event.cancelBubble = true;return false;');
		document.observe('click',function(){ widgetsManager.getPageBlockEditor().hideEditTitle(); });
		$('PageTitleField').observe('keydown',function(event){ 
				if (event.keyCode==27) { 
					widgetsManager.getPageBlockEditor().hideCancelEditTitle(); 
				} 
				else if (event.keyCode==13){ 
					widgetsManager.getPageBlockEditor().hideEditTitle(); 
				} 
			});
	},
	
	hideEditTitle: function(){
		
		if ($('PageTitleText').style.display=='inline') return;
		
		$('PageTitleText').innerHTML = $('pageTitle').value;
		
		this.hideCancelEditTitle();
		
		var pageId = $('pageSelectorPageList').value;
		
		if (!pageId) return;
		
		new Ajax.Request(this.getActionFile(), {
				method:'post',
				parameters:{ command:'editPageTitle', style:system.getCurrentStyle(), pageId:pageId, pageTitle: $('pageTitle').value },
				onSuccess: function(transport) {
					//$('PageTitleText').innerHTML = $('pageTitle').value;
				}
		});
	},
	
	hideCancelEditTitle: function(){
		$('PageTitleText').style.display = 'inline';
		$('PageTitleField').hide();
	},
	
	loadPage: function() {
		var pageId = $('pageSelectorPageList').value;
		var actionFile = this.getActionFile();
		if( pageId && $('pageBlockEditor')!=null ) {
			new Ajax.Request(actionFile, {
				method:'post',
				parameters:{ command:'loadPage', style:system.getCurrentStyle(), pageId:pageId, destinationLibraryPath:system.getLibraryPath() },
				onSuccess: function(transport) {
					$('pageBlockEditor').innerHTML = transport.responseText;
					system.evalAllScripts('pageBlockEditor','loadPageBlocks');
					widgetsManager.getPageBlockEditor().updateSortables();
				}
			});
		}
		else {
			 widgetsManager.getPageBlockEditor().loadEmptyPage();
		}
	},
	
	loadEmptyPage: function() {
		var actionFile = this.getActionFile();
		new Ajax.Request(actionFile,{
			method:'post',
			parameters:{command:'loadEmptyPage',style:system.getCurrentStyle()},
			onSuccess:function(transport){
				$('pageBlockEditor').innerHTML = transport.responseText;
			}
		});
	},
	
	updateSortables: function(){
		Sortable.create('pageBlocks',{ tag: 'div' ,
							onUpdate: function() { widgetsManager.getPageBlockEditor().saveBlocksOrder(); }
		});		
	},
	
	addPage: function(pageId,type) {
		var actionFile = this.getActionFile();
		new Ajax.Request(actionFile,{
			method:'post',
			parameters:{command:'addBlock', pageId:pageId, destinationLibraryPath:system.getLibraryPath(),type:type },
			onSuccess: function(transport) {
				//widgetsManager.getPageBlockEditor().loadPage();
				
				
				var blockContainer = $('pageBlocks');
				//blockContainer.innerHTML = blockContainer.innerHTML + transport.responseText;
				
				Element.insert(blockContainer,transport.responseText);
				
				widgetsManager.getPageBlockEditor().updateSortables();
				
				
	//			Para que funcione esto necesito el ID del bloque, si no luego no se puede borrar ni mover.
	//			var blockContainer = $('pageBlocks');
	//			var newBlock = document.createElement('div');
	//			Element.extend(newBlock);
	//			newBlock.addClassName('pageBlock');
	//			blockContainer.appendChild(newBlock);
	//			newBlock.innerHTML = transport.responseText;
			}
		});
	},
	
	editBlock: function(id,type,module,actionFile) {
		$('pageBlockButton_' + id).hide();
		$('pageBlockButtonSave_' + id).show();
		$('pageBlockButtonCancel_' + id).show();
		var blockTypeLabel = $('pageBlockTypeLabel_' + id);
		//alert('Quieres desplegar el bloque ' + id + ' de tipo ' + type +
		//		', ubicado en el módulo ' + module + ' e implementado en el fichero ' + actionFile);
		new Ajax.Request(system.getLibraryPath() + module + '/' + actionFile, {
			method:'post',
			parameters:{command:'insertControlPanel',style:system.getCurrentStyle(),blockId:id,formId:'pageBlockEditForm_'+id}, // No cambiar 'pageBlockEditForm_'. Mirar fichero _page_block_editor.php
			onSuccess: function(transport) {
				$('pageBlockContent_' + id).hide();
				$('pageBlockContent_' + id).innerHTML = transport.responseText;
				Effect.BlindDown('pageBlockContent_'+id,{duration:0.2});
				system.evalAllScripts('pageBlockContent_' + id);
			}
		});
	},
	
	cancelEditBlock: function(id,type,module,actionFile) {
		
		document.fire('ws:cancellingEditBlock',{ id: id });
				
		$('pageBlockButton_' + id).show();
		$('pageBlockButtonSave_' + id).hide();
		$('pageBlockButtonCancel_' + id).hide();

		//Effect.BlindUp('pageBlockContent_'+id,{duration:0.2, afterFinish: function () { $('pageBlockContent_'+id).innerHTML = ''; } });
		this.hideBlockContent(id);
	},
	
	updateTextPreview: function(id,type,module,actionFile) {
		
		new Ajax.Request(system.getLibraryPath() + module + '/' + actionFile, {
			method:'post',
			parameters:{ command: 'updateTextPreview', style: system.getCurrentStyle(), type: type, blockId: id },
			onSuccess: function(transport) {
				$('pageBlockTextPreview_' + id).innerHTML = transport.responseText;
			}
		});		
	},
	
	hideBlockContent: function(id){
		Effect.BlindUp('pageBlockContent_'+id,{duration:0.2, afterFinish: function () { $('pageBlockContent_'+id).innerHTML = ''; } });
	},
	
	saveBlock: function(id,type,module,actionFile) {
		
		document.fire('ws:savingBlock',{ id: id });
		$('pageBlockEditForm_' + id).fire('ws:updateText');
		
		$('pageBlockButton_' + id).show();
		$('pageBlockButtonSave_' + id).hide();
		$('pageBlockButtonCancel_' + id).hide();
		var parameters = {};
		var form = $('pageBlockEditForm_'+id);
		if( form ) {
			parameters = form.serialize(true);
		}
		
		var obj = this;
		
		parameters.command='saveBlock';
		parameters.blockId=id;
		parameters.type=type;
		parameters.module=module;
		new Ajax.Request(system.getLibraryPath() + module + '/' + actionFile, {
			method:'post',
			parameters:parameters,
			onSuccess: function(transport) {
				obj.hideBlockContent(id);
				//Effect.BlindUp('pageBlockContent_'+id,{duration:0.2});
				widgetsManager.getPageBlockEditor().updateTextPreview(id,type,module,actionFile);
			}
		});
	},
	blockToTrash: function(id) {
		//alert('Mover a la papelera el bloque ' + id);
		new Ajax.Request(this.getActionFile(),{
			method:'post',
			parameters:{command:'blockToTrash',blockId:id},
			onSuccess:function(transport){
				if( transport.responseText=='OK') {
					$('pageBlock_'+id).remove();
					// Redibujar papelera
					new Ajax.Request(system.getLibraryPath()+'web/_index.php',{
						method:'post',
						parameters:{command:'printTrashIcon',style:system.getCurrentStyle()},
						onSuccess:function(transport){
							//$('blockTrashContainer').innerHTML = transport.responseText;
							$('pageBlock_' + id).remove();
						}
					});
				}
				else {
					alert(transport.responseText);
				}
			}
		});
	},
	
	recoverBlock: function(id) {
		this.executeTrashAction(id,'recoverItem');
	},
	
	removeBlock:function(id) {
		this.executeTrashAction(id,'removeFromTrash');
	},
	
	executeTrashAction: function(itemId,actionCommand) {
		var actionParameters = { command:actionCommand, blockId:itemId };

		new Ajax.Request(system.getLibraryPath()+'web/_index.php', {
			method:'post',
			parameters: actionParameters,
			onSuccess: function(transport) {
				var pageId = $('pageSelectorPageList').value;
				var actionFile = widgetsManager.getPageBlockEditor().getActionFile();
				if( pageId && $('pageBlockEditor')!=null ) {
					new Ajax.Request(actionFile, {
						method:'post',
						parameters:{ command:'loadPage', style:system.getCurrentStyle(), pageId:pageId, destinationLibraryPath:system.getLibraryPath() },
						onSuccess: function(transport) {
							$('pageBlockEditor').innerHTML = transport.responseText;
							new Ajax.Request(system.getLibraryPath()+'web/_index.php',{
								method:'post',
								parameters:{command:'printTrashIcon',style:system.getCurrentStyle()},
								onSuccess:function(transport){
									$('blockTrashContainer').innerHTML = transport.responseText;
									system.getPopUp().setContent('Loading data...'); 
									system.getPopUp().setContentWithURL(system.getLibraryPath()+'web/_index.php', { command:'printTrash', style:system.getCurrentStyle() });
								}
							});
						}
					});
				}
			}
		});
	},
	
	changeBlockType: function(id,module,actionFile) {
		var newBlockType = $('blockTypeCombo_'+id).value;
		
		new Ajax.Request(this.getActionFile(),{
			method:'post',
			parameters:{command:'changeBlockType',blockId:id,newBlockType:newBlockType,destinationLibraryPath:system.getLibraryPath()},
			onSuccess:function(transport) {
				if (transport.responseText!=""){
					$('pageBlock_'+id).innerHTML = transport.responseText;
					$('pageBlockButton_'+id).onclick();					
				}
				//widgetsManager.getPageBlockEditor().editBlock(id,newBlockType,module,this.getActionFile());
			}
		});
	},
	
	blockUp: function(id) {
		new Ajax.Request(this.getActionFile(),{
			method:'post',
			parameters:{command:'blockUp',blockId:id},
			onSuccess: function(transport){
				if(transport.responseText=='OK'){
					// TODO: Mover el bloque con usando el arbol DOM
					widgetsManager.getPageBlockEditor().loadPage();
				}
				else {
					alert(transport.responseText);
				}
			}
		});
	},

	blockDown: function(id) {
		new Ajax.Request(this.getActionFile(),{
			method:'post',
			parameters:{command:'blockDown',blockId:id},
			onSuccess: function(transport){
				if(transport.responseText=='OK'){
					// TODO: Mover el bloque con usando el arbol DOM
					widgetsManager.getPageBlockEditor().loadPage();
				}
				else {
					alert(transport.responseText);
				}
			}
		});
	},
	
	saveBlocksOrder: function(){
		
		var blocks = $('pageBlocks').childElements();
		var blockIds = new Array();
		for (var i=0;i<blocks.length;i++){
			
		
		//blocks.each(function(name,index){ blockIds.push(block.id.substring(10)); });
			blockIds.push(blocks[i].id.substring(10));
			 // Quitar el pageBlock_
		}
		
		blockIds = blockIds.join(',');
		
		new Ajax.Request(this.getActionFile(),{
			method:'post',
			parameters:{ command:'saveBlocksOrder',blockIds: blockIds },
			onSuccess: function(transport){
				if(transport.responseText=='OK'){
					// TODO: Mover el bloque con usando el arbol DOM
					//widgetsManager.getPageBlockEditor().loadPage();
				}
				else {
					alert(transport.responseText);
				}
			}
		});
	},
	
	getActionFile: function() {
		return system.getLibraryPath() + 'plasticbriqFramework/actions/_page_block_editor.php';
	}
});

var PageSelectorWidget = new Class.create({
	actionFile:'',
	addSite: function(actionURL,command) {
		new Ajax.Request(actionURL, {
			method: 'post',
			parameters: { command:command },
			onSuccess: function(transport) {
				if( transport.responseText=='OK' ) {
					widgetsManager.getPageSelector().loadSiteList();
				}
				else {
					system.getMessageManager().showMessage(transport.responseText,{color:'red'});
				}
			}
		});
	},
	
	addSection: function(actionURL,command) {
		var currentSite = $('pageSelectorSiteList').value;

		if( currentSite ) {
			new Ajax.Request(actionURL, {
				method:'post',
				parameters: { command:command, siteId:currentSite },
				onSuccess: function(transport) {
					if( transport.responseText=='OK' ) {
						widgetsManager.getPageSelector().loadSectionList();
					}
					else {
						system.getMessageManager().showMessage(transport.responseText,{color:'red'});
					}
				}
			});
		}
	},
	
	addPage: function(actionURL,command) {
		var currentSection = $('pageSelectorSectionList').value;

		if( currentSection ) {
			new Ajax.Request(actionURL, {
				method:'post',
				parameters: { command:command, sectionId:currentSection },
				onSuccess: function(transport) {
					if( transport.responseText=='OK' ) {
						widgetsManager.getPageSelector().loadPageList();
					}
					else {
						system.getMessageManager().showMessage(transport.responseText,{color:'red'});
					}
				}
			});
		}
	},
	
	duplicatePage: function(actionURL,command) {
		var selectedPage = $('pageSelectorPageList').value;

		if( selectedPage ) {
			new Ajax.Request(actionURL, {
				method:'post',
				parameters: { command:command, pageId:selectedPage },
				onSuccess: function(transport) {
					if( transport.responseText=='OK' ) {
						widgetsManager.getPageSelector().loadPageList();
					}
					else {
						system.getMessageManager().showMessage(transport.responseText,{color:'red'});
					}
				}
			});
		}
	},
	
	removeSite: function(actionURL,command) {
		var selectedSite = $('pageSelectorSiteList').value;
		
		if( selectedSite ) {
			new Ajax.Request(actionURL, {
				method:'post',
				parameters: { command:command, siteId:selectedSite },
				onSuccess: function(transport) {
					if( transport.responseText=='OK' ) {
						widgetsManager.getPageSelector().loadSiteList();
						system.getMessageManager().hideMessage();
					}
					else {
						system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
					}
				}
			});
		}
	},
	
	removeSection: function(actionURL,command) {
		var selectedSection = $('pageSelectorSectionList').value;
		
		if( selectedSection ) {
			new Ajax.Request(actionURL, {
				method:'post',
				parameters: { command:command, sectionId:selectedSection },
				onSuccess: function(transport) {
					if( transport.responseText=='OK' ) {
						widgetsManager.getPageSelector().loadSectionList();
						system.getMessageManager().hideMessage();
					}
					else {
						system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
					}
				}
			});
		}

	},
	
	removePage: function(actionURL,command) {
		var selectedPage = $('pageSelectorPageList').value;
		
		if( selectedPage ) {
			new Ajax.Request(actionURL, {
				method:'post',
				parameters: { command:command, pageId:selectedPage },
				onSuccess: function(transport) {
					if( transport.responseText=='OK' ) {
						widgetsManager.getPageSelector().loadPageList();
						system.getMessageManager().hideMessage();
					}
					else {
						system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
					}
				}
			});
		}

	},
	
	editSite: function(actionURL,command) {
		var currentSite = $('pageSelectorSiteList').value;
		var parameters = { command:'printEditSite', style:system.getCurrentStyle(), doCommand:command, actionURL:actionURL, siteId:currentSite };
		if( currentSite ) {
			system.getPopUp().setContent('Loading data...'); 
			system.getPopUp().setContentWithURL(this.getActionFile(),parameters);
			system.getPopUp().open();
		}
	},
	
	saveSiteInfo: function(actionURL,formId,command) {
		var params = $(formId).serialize(true);
		params.style = system.getCurrentStyle();
		params.command = command;

		new Ajax.Request(actionURL, {
			method:'post',
			parameters: params,
			onSuccess: function(transport) {
				if( transport.responseText=='OK' ) {
					widgetsManager.getPageSelector().loadSiteList();
					system.getMessageManager().hideMessage();
					system.getPopUp().close();
				}
				else {
					system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
				}
			}
		});
	},

	editSection: function(actionURL,command) {
		var currentSection = $('pageSelectorSectionList').value;
		var parameters = { command:'printEditSection', style:system.getCurrentStyle(), doCommand:command, actionURL:actionURL, sectionId:currentSection };
		if( currentSection ) {
			system.getPopUp().setContent('Loading data...'); 
			system.getPopUp().setContentWithURL(this.getActionFile(),parameters);
			system.getPopUp().open();
		}
	},

	saveSectionInfo: function(actionURL,formId,command) {
		var params = $(formId).serialize(true);
		params.style = system.getCurrentStyle();
		params.command = command;

		new Ajax.Request(actionURL, {
			method:'post',
			parameters: params,
			onSuccess: function(transport) {
				if( transport.responseText=='OK' ) {
					widgetsManager.getPageSelector().loadSectionList();
					system.getMessageManager().hideMessage();
					system.getPopUp().close();
				}
				else {
					system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
				}
			}
		});
	},

	editPage: function(actionURL,command) {
		var currentPage = $('pageSelectorPageList').value;
		var parameters = { command:'printEditPage', style:system.getCurrentStyle(), doCommand:command, actionURL:actionURL, pageId:currentPage };
		if( currentPage ) {
			system.getPopUp().setContent('Loading data...'); 
			system.getPopUp().setContentWithURL(this.getActionFile(),parameters);
			system.getPopUp().open();
		}
	},
	
	savePageInfo: function(actionURL,formId,command) {
		var params = $(formId).serialize(true);
		params.style = system.getCurrentStyle();
		params.command = command;

		new Ajax.Request(actionURL, {
			method:'post',
			parameters: params,
			onSuccess: function(transport) {
				if( transport.responseText=='OK' ) {
					widgetsManager.getPageSelector().loadPageList();
					system.getMessageManager().hideMessage();
					system.getPopUp().close();
				}
				else {
					system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
				}
			}
		});
	},
	
	showSiteTrash: function() {
		var parameters = { command:'printSiteTrash', style:system.getCurrentStyle() };
		system.getPopUp().setContent('Loading data...'); 
		system.getPopUp().setContentWithURL(this.getActionFile(),parameters);
		system.getPopUp().open();
	},

	showSectionTrash: function() {
		var parameters = { command:'printSectionTrash', style:system.getCurrentStyle() };
		system.getPopUp().setContent('Loading data...'); 
		system.getPopUp().setContentWithURL(this.getActionFile(),parameters);
		system.getPopUp().open();
	},
	
	showPageTrash: function() {
		var parameters = { command:'printPageTrash', style:system.getCurrentStyle() };
		system.getPopUp().setContent('Loading data...'); 
		system.getPopUp().setContentWithURL(this.getActionFile(),parameters);
		system.getPopUp().open();
	},
	
	removeItem: function(table,id,resourceType) {
		new Ajax.Request(this.getActionFile(), {
			method:'post',
			parameters:{command:'removeItem',id:id,tableName:table},
			onSuccess: function(transport) {
				var pageSelector = widgetsManager.getPageSelector();
				if( transport.responseText=='OK' ) {
					if( resourceType=='site' ) pageSelector.loadSiteList();
					else if( resourceType=='section' ) pageSelector.loadSectionList();
					else if( resourceType=='page' ) pageSelector.loadPageList();
					system.getPopUp().close();
				}
			}
		});
	},

	recoverItem: function(table,id,resourceType) {
		new Ajax.Request(this.getActionFile(), {
			method:'post',
			parameters:{command:'recoverItem',id:id,tableName:table},
			onSuccess: function(transport) {
				var pageSelector = widgetsManager.getPageSelector();
				if( transport.responseText=='OK' ) {
					if( resourceType=='site' ) pageSelector.loadSiteList();
					else if( resourceType=='section' ) pageSelector.loadSectionList();
					else if( resourceType=='page' ) pageSelector.loadPageList();
					system.getPopUp().close();
				}
			}
		});
	},

	loadSiteList: function(containerSuffix) {
		if( !containerSuffix ) containerSuffix = '';
		var siteContainer = 'pageSelectorSiteListContainer' + containerSuffix;
		var sectionContainer = 'pageSelectorSectionListContainer' + containerSuffix;
		var pageContainer = 'pageSelectorPageListContainer' + containerSuffix;
		new Ajax.Request(this.getActionFile(), {
			method:'post',
			parameters: { command:'loadSiteList' },
			onSuccess: function(transport) {
				$(siteContainer).innerHTML = transport.responseText;
				$(sectionContainer).innerHTML = '<select id="pageSelectorSectionList" size="7" style="width:100%;"></select>';
				$(pageContainer).innerHTML = '<select id="pageSelectorPageList" size="7" style="width:100%;"></select>';
				widgetsManager.getPageBlockEditor().loadEmptyPage();
				widgetsManager.getPageSelector().loadSectionList(containerSuffix);
			}
		});
	},

	loadSectionList: function(containerSuffix) {
		if( !containerSuffix ) containerSuffix='';
		var pageContainer = 'pageSelectorPageListContainer' + containerSuffix;
		var sectionContainer = 'pageSelectorSectionListContainer' + containerSuffix;
		var siteId = $('pageSelectorSiteList' + containerSuffix).value;

		new Ajax.Request(this.getActionFile(), {
			method:'post',
			parameters: { command:'loadSectionList', siteId:siteId },
			onSuccess: function(transport) {
				$(sectionContainer).innerHTML = transport.responseText;
				$(pageContainer).innerHTML = '<select id="pageSelectorSectionList" size="7" onchange="" style="width:100%;"></select>';
				widgetsManager.getPageBlockEditor().loadEmptyPage();
				widgetsManager.getPageSelector().loadPageList(containerSuffix);
			}
		});
	},
	
	loadPageList: function(containerSuffix) {
		if( !containerSuffix ) containerSuffix='';
		var sectionId = $('pageSelectorSectionList' + containerSuffix).value;
		
		if (!sectionId){
			$('pageSelectorPageListContainer' + containerSuffix).innerHTML = "<select id=\"pageSelectorPageList\" size=\"7\" style=\"width:100%;height: 90px;\"></select>;";
				
			widgetsManager.getPageBlockEditor().loadEmptyPage();
		}
		else {
			new Ajax.Request(this.getActionFile(), {
				method:'post',
				parameters: { command:'loadPageList', sectionId:sectionId },
				onSuccess: function(transport) {
					$('pageSelectorPageListContainer' + containerSuffix).innerHTML = transport.responseText;
					//widgetsManager.getPageBlockEditor().loadEmptyPage();
					widgetsManager.getPageBlockEditor().loadPage();
				}
			});			
		}
	},

	openSiteDesigner: function(user,passwd) {
		var selectedSite = $('pageSelectorSiteList').value;
		
		if( selectedSite ) {
			window.open(system.getLibraryPath() + 'design/website_designer.php?siteId=' + $('pageSelectorSiteList').value,'Site Designer',"location=0,directories=0,menubar=0,status=0,toolbar=0,scrollbars=1");
		}
	},
	
	openPageDesigner: function(user,passwd) {
		var selectedPage = $('pageSelectorPageList').value;
		
		if( selectedPage ) {
			window.open(system.getLibraryPath() + 'web/webpage_editor.php?siteId=' + $('pageSelectorSiteList').value + '&pageId=' + selectedPage,'plasticbriQ Web Engine - Page Designer',"location=0,directories=0,menubar=0,status=0,toolbar=0,scrollbars=1");
		}
	},
	
	getActionFile: function() {
		if( this.actionFile=='' ) {
			this.actionFile = system.getLibraryPath() + 'plasticbriqFramework/actions/_page_selector_widget.php';
		}
		return this.actionFile;
	}
});

var PageSelectorWidgetGeneric = new Class.create({
	actionFile:'',
	loadSiteList: function() {
		containerSuffix = '_generic';
		var siteContainer = 'pageSelectorSiteListContainer' + containerSuffix;
		var sectionContainer = 'pageSelectorSectionListContainer' + containerSuffix;
		var pageContainer = 'pageSelectorPageListContainer' + containerSuffix;
		new Ajax.Request(this.getActionFile(), {
			method:'post',
			parameters: { command:'loadSiteListGeneric' },
			onSuccess: function(transport) {
				$(siteContainer).innerHTML = transport.responseText;
				$(sectionContainer).innerHTML = '<select id="pageSelectorSectionList' + containerSuffix +'" size="7" style="width:100%;"></select>';
				$(pageContainer).innerHTML = '<select id="pageSelectorPageList' + containerSuffix + '" size="7" style="width:100%;"></select>';
				widgetsManager.getPageSelectorGeneric().loadSectionList();
			}
		});
	},

	loadSectionList: function() {
		containerSuffix = '_generic';
		var pageContainer = 'pageSelectorPageListContainer' + containerSuffix;
		var sectionContainer = 'pageSelectorSectionListContainer' + containerSuffix;
		var siteId = $('pageSelectorSiteList' + containerSuffix).value;

		new Ajax.Request(this.getActionFile(), {
			method:'post',
			parameters: { command:'loadSectionListGeneric', siteId:siteId },
			onSuccess: function(transport) {
				$(sectionContainer).innerHTML = transport.responseText;
				$(pageContainer).innerHTML = '<select id="pageSelectorSectionList' + containerSuffix + '" size="7" onchange="" style="width:100%;"></select>';
				widgetsManager.getPageSelectorGeneric().loadPageList();
			}
		});
	},
	
	loadPageList: function() {
		containerSuffix = '_generic';
		var sectionId = $('pageSelectorSectionList' + containerSuffix).value;

		new Ajax.Request(this.getActionFile(), {
			method:'post',
			parameters: { command:'loadPageListGeneric', sectionId:sectionId },
			onSuccess: function(transport) {
				$('pageSelectorPageListContainer' + containerSuffix).innerHTML = transport.responseText;
			}
		});
	},
	
	getActionFile: function() {
		if( this.actionFile=='' ) {
			this.actionFile = system.getLibraryPath() + 'plasticbriqFramework/actions/_page_selector_widget.php';
		}
		return this.actionFile;
	}
});


var LocalizedStringEditor = new Class.create({
	fieldId: '',

	initialize: function(fieldId)  {
		this.fieldId = fieldId;
	},
	
	changeLanguage: function(languageSelectorId) {
		var langSelector = $(languageSelectorId);
		var currentLanguage = $(this.fieldId + '_currentLanguage');
		var currentField = $(this.fieldId + '_' + currentLanguage.value + '_Container');
		var newField = $(this.fieldId + '_' + langSelector.value + '_Container');

		if( currentField ) {
			currentField.hide();
		}
		if( newField ) {
			newField.show();
		}

		currentLanguage.value = langSelector.value;
	}
});

var WidgetsManager = new Class.create({
	pageSelectorWidget: null,
	pageSelectorWidgetGeneric: null,
	pageBlockEditor:null,
	textTranslator:null,

	initialize: function() {
		this.pageSelectorWidget = new PageSelectorWidget();
		this.pageSelectorWidgetGeneric = new PageSelectorWidgetGeneric();
		this.pageBlockEditor = new PageBlockEditorWidget();
		this.textTranslator = new TextTranslator();
	},
	
	getPageSelector: function() {
		return this.pageSelectorWidget;
	},
	
	getPageSelectorGeneric: function() {
		return this.pageSelectorWidgetGeneric;
	},
	
	getPageBlockEditor: function() {
		return this.pageBlockEditor;
	},
	
	getTextTranslator: function() {
		return this.textTranslator;
	}
});

var widgetsManager = new WidgetsManager();

var BigImage = Class.create({

	imageUrl: null,
	width: null,
	height: null,
	imageName: null,
	description: null,
	index: null,

	initialize: function(imageUrl,width,height,imageName,description,index) {
		this.imageUrl = imageUrl;
		this.width = width;
		this.height = height;
		this.imageName = imageName;
		this.description = description;
		this.index = index;
	}
	
});

var ImageViewer = Class.create({

	usePopUp: true,
	containerId:null,
	downloadIcon:null,
	topLeftIcon:null,
	topRightIcon:null,
	bottomLeftIcon:null,
	bottomRightIcon:null,
	leftIcon:null,
	rightIcon:null,
	topIcon:null,
	bottomIcon:null,
	minWidth: 200,
	
	images: null,
	imageIndices: null,
	numImages: 0,

	initialize: function (containerId) {
		if (!containerId){
			this.containerId = 'ImageDetailContainer';
		}
		else {
			this.containerId = containerId;
			this.usePopUp = false;
		}
	},
	
	scrollTop: function () {
		var scrollManager = new ScrollManager();
		var marginBase = 5;
		return marginBase + scrollManager.currentOffset();
	},
	
	resetImages: function(){
		this.images = new Array();
		this.imageIndices = new Array();
		this.numImages = 0;
	},
	
	addImage: function(imageUrl,width,height,imageName,description){
		
		if (!this.images) this.resetImages();
		
		var newImage = new BigImage(imageUrl,width,height,imageName,description,this.numImages);
		this.images[imageUrl] = newImage;
		this.imageIndices.push(newImage);
		this.numImages++;
	},
	
	showStoredImage: function(imageUrl){
		var bigImage = this.images[imageUrl];
		if (bigImage){
			this.showImage(imageUrl,bigImage.width,bigImage.height,'',bigImage.imageName,bigImage.description,true);
		}
	},
	
	showImage: function (imageUrl,width,height,clickText,imageName,description,disableAnimation) {


		var aux = new Image();
		aux.src = imageUrl;

		var obj = this;

		aux.onload = function(){
			
			var marginLeft = 0;
			var imageSize = new Array(this.width,this.height);

			if ((!width) || (!height)) {


				if (!width) {
					width = this.width;
				}
				if (!height) {
					height = this.height;
				}
			}
			
			width = parseInt(width);

			if (width<obj.minWidth){
				width = obj.minWidth;
			}
			
			if (width<(imageName.length*6 + 132)){
				width = imageName.length*6 + 132;
			}

			//marginLeft = parseInt((width-aux.width)/2);

			if (!obj.containerId){
				obj.containerId = 'ImageDetailContainer';
				obj.usePopUp = true;
			}

			if (!obj.usePopUp) {

				if (system.browserIgnoresEmbeddedZIndex()) {
					system.hideElementsWithTagName('object');
					system.hideElementsWithTagName('embed');
				}

				var container = $(obj.containerId);
				if (container){
					container.className = 'imageViewerItemContainer';
					var widthStyle = '';
					var heightStyle = '';

					var frameSize = media.getSizeForFrame(container.offsetWidth,container.offsetHeight,imageSize);

					widthStyle = 'width: ' + frameSize[0] + 'px;';
					heightStyle = 'height: ' + frameSize[1] + 'px;';
					marginTopStyle = 'margin-top:' + (container.offsetHeight-frameSize[1])/2 + 'px;';

					container.innerHTML = '<div id="' + obj.containerId + '_imageContainer"><img id="' + obj.containerId + '_image" class="imageViewerItem" style="' + widthStyle + heightStyle + marginTopStyle + 'display:block;margin-left:auto;margin-right:auto;" src="' + imageUrl + '"/></div>';

					$(obj.containerId + '_imageContainer').hide();
					Effect.Appear(obj.containerId + '_imageContainer',{duration:1.0});
				}
			}
			else {

				var urlParts = imageUrl.split('/');
				var imageFile = urlParts[urlParts.length-1];
				var downloadUrl = system.getDownloaderUrl() + '?file=' + imageFile + '&path=images';
				
				var bigImage = obj.images[imageUrl];

				var previousImage = null;
				var nextImage = null;
				
				if (bigImage){
					if (bigImage.index>0){
						previousImage = obj.imageIndices[bigImage.index-1];						
					}
					if (bigImage.index<(obj.imageIndices.length-1)){
						nextImage = obj.imageIndices[bigImage.index+1];						
					}
				}


				$('ImagePopUpDownload').observe('click',function(event){ window.location.href = downloadUrl; });

				if (previousImage){
					$('ImagePopUpPrevious').style.visibility = 'visible';
					//$('ImagePopUpPrevious').observe('click',function(event){ imageViewer.showStoredImage(previousImage.imageUrl); });
					
					$('ImagePopUpPrevious').setAttribute("onclick", "imageViewer.showStoredImage('" + previousImage.imageUrl + "');");
				}
				else {
					$('ImagePopUpPrevious').style.visibility = 'hidden';
				}

				if (nextImage){
					$('ImagePopUpNext').style.visibility = 'visible';
					//$('ImagePopUpNext').observe('click',function(event){ imageViewer.showStoredImage(nextImage.imageUrl); });
					$('ImagePopUpNext').setAttribute("onclick", "imageViewer.showStoredImage('" + nextImage.imageUrl + "');");
				}
				else {
					$('ImagePopUpNext').style.visibility = 'hidden';
				}

				
				//.onclick = 'window.location.href=' + downloadUrl + ';';

				if (!disableAnimation){
					obj.hideImage();					
				}


				if (system.browserIgnoresEmbeddedZIndex()) {
					system.hideElementsWithTagName('object');
					system.hideElementsWithTagName('embed');
				}

				var imageTopMargin = 10;

				width = parseInt(width);
				height = parseInt(height);

				$('imagePopUpFrame').style.marginTop = (obj.scrollTop()+50) + 'px';
				$('imagePopUpFrame').style.width = (width + 38*2) + "px";
				$('imagePopUpFrame').style.height = (height + 38 + 36 + imageTopMargin + 1 + 23) + "px";

				$('ImagePopUpTop').style.width = width + "px";
				$('ImagePopUpBar').style.width = width + "px";
				$('ImagePopUpBorder').style.width = width + "px";
				$('ImagePopUpDescription').style.width = width + "px";
				$('ImagePopUpLeft').style.height = (height + imageTopMargin) + "px";
				$('ImagePopUpRight').style.height = (height + imageTopMargin) + "px";
				$('ImagePopUpBottom').style.width = width + "px";

				if (imageName){
					$('ImagePopUpName').show();
					$('ImagePopUpName').innerHTML = imageName;
					$('ImagePopUpName').style.marginLeft = 20 + "px";
					$('ImagePopUpName').style.width = (width - 132) + "px"; // 122 viene de 4(botones)*18(ancho de un botón)*10(margen entre botones) + 20 de margen
				}
				else {
					$('ImagePopUpName').innerHTML = '';
				}
				
				if (description){
					$('ImagePopUpLeftDescription').show();
					$('ImagePopUpDescription').show();
					$('ImagePopUpDescription').innerHTML = description;
					$('ImagePopUpRightDescription').show();
				}
				else {
					$('ImagePopUpDescription').innerHTML = '';
				}


				var content = $('ImagePopUpContent');
				content.style.width = width + "px";
				content.style.height = (height + imageTopMargin) + "px";

				//var image = new Element('img',{ 'src' : imageUrl, 'style':'cursor: pointer; cursor: hand;margin-bottom: 10px;' });
				content.innerHTML = '<img src="' + imageUrl + '" style="margin-left: auto;margin-right:auto;display:block;margin-top:' + imageTopMargin + 'px;margin-bottom: 10px;">';

				if (!disableAnimation){
					if (system.browserIgnoresEmbeddedZIndex()) {
						$('imagePopUp').show();
					}
					else {
						$('imagePopUp').appear({ duration: 0.3 });
					}					
				}
			}
			
		};

		//imageContainer.style.display = 'block';
	},

	hideImage: function () {
		/*if ($(this.containerId)) {
			$(this.containerId).fade();
		}*/
				
		if ($('imagePopUp').style.display!='none'){
			if (system.browserIgnoresEmbeddedZIndex()) {
				$('imagePopUp').hide();
			}
			else {
				$('imagePopUp').fade({duration: 0.3 });
			}		
		}
		
		if (system.browserIgnoresEmbeddedZIndex()) {
			system.showElementsWithTagName('object');
			system.showElementsWithTagName('embed');
		}
		
	},
	removeImage: function(){
		
		if ($(this.containerId)) {
			$(this.containerId).remove();
		}
	}
	
});

var imageViewer = new ImageViewer();

var HTMLClipPicker = new Class.create({
	insertYouTubeClip: function(textId,paramMessage) {
		var parameter = '';
		if( paramMessage ) {
			parameter = prompt(paramMessage);
		}
		if (parameter){
			var parameters = {command:'printYouTubeClip',videoURL:parameter};
			this.printText(textId,parameters);	
		}
	},
	
	insertCreativeCommonsClip: function(textId,commercialWorkMessage,derivateWorkMessage,shareLicenseMessage) {
		var commercialWork = confirm(commercialWorkMessage);
		var derivateWork = confirm(derivateWorkMessage);
		var shareWithSameLicense = false;
		if( derivateWork ) {
			shareWithSameLicense = confirm(shareLicenseMessage);
		}
		var parameters = {command:'printCreativeCommonsClip',allowCommercial:commercialWork,allowDerivate:derivateWork,sameLicense:shareWithSameLicense};
		this.printText(textId,parameters);
	},
	
	insertGPLClip: function(textId) {
		this.printText(textId,{command:'printGPLClip'});
	},
	
	insertLGPLClip: function(textId) {
		this.printText(textId,{command:'printLGPLClip'});
	},
	
	insertBrowserClip: function(textId,browser) {
		var parameters = {command:'printBrowserClip',browserName:browser};
		this.printText(textId,parameters);
	},
	
	printText: function(textId,parameters) {
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_html_picker_actions.php',{
			method:'post',
			parameters:parameters,
			onSuccess:function(transport) {
				$(textId).value = transport.responseText;
			}
		});
	},
	
	preview: function(textId) {
		$('htmlClipPickerPreview_'+textId).innerHTML = $(textId).value;
	}
});

var htmlClipPicker = new HTMLClipPicker();

var ScoreManager = new Class.create({
	select: function(fieldId,starIndex,maxStars) {
		var hiddenField = $(fieldId);
		hiddenField.value = starIndex + 1;
		// var scoreHint = $('scoreHint_' + fieldId);
		// 		scoreHint.innerHTML = starIndex + 1;
		var newClassName;
		for( var i=0; i<maxStars; ++i ) {
			if( i<=starIndex) {
				newClassName = 'selectedStar';
			}
			else {
				newClassName = 'unselectedStar';
			}
			$('score_' + fieldId + '_star_' + i).className = newClassName;
		}
	},
	
	over: function(fieldId,starIndex,maxStars) {
		// var scoreHint = $('scoreHint_' + fieldId);
		// scoreHint.innerHTML = starIndex + 1;
		var newClassName;
		for( var i=0; i<maxStars; ++i ) {
			if( i<=starIndex) {
				newClassName = 'selectedStar';
			}
			else {
				newClassName = 'unselectedStar';
			}
			$('score_' + fieldId + '_star_' + i).className = newClassName;
		}
	},
	
	out: function(fieldId,starIndex,maxStars) {
		var hiddenField = $(fieldId);
		starIndex = hiddenField.value-1;

		// var scoreHint = $('scoreHint_' + fieldId);
		// scoreHint.innerHTML = starIndex + 1;
		var newClassName;
		for( var i=0; i<maxStars; ++i ) {
			if( i<=starIndex) {
				newClassName = 'selectedStar';
			}
			else {
				newClassName = 'unselectedStar';
			}
			$('score_' + fieldId + '_star_' + i).className = newClassName;
		}
	}
});

var scoreManager = new ScoreManager();


var OneByOneGallery = new Class.create({
	
	id: null,
	lastPage: null,
	leftArrowId: null,
	rightArrowId: null,
	currentPage: 0,
	
	initialize: function(id,lastPage,leftArrowId,rightArrowId) {
		this.id = id;
		this.lastPage = lastPage;
		this.leftArrowId = leftArrowId;
		this.rightArrowId = rightArrowId;
	},
	
	switchPage: function(oldPage,newPage) {
		$(oldPage).style.display = 'none';
		$(newPage).style.display = 'block';
	},
	
	previous: function(){
		
		var currentObjectId = this.id + this.currentPage;
				
		if (this.currentPage>0){
			this.currentPage--;
		}
		
		var nextObjectId = this.id + this.currentPage;

		this.switchPage(currentObjectId,nextObjectId);
		
		this.checkLeftArrowVisibility();
		this.checkRightArrowVisibility();
	},
	
	next: function(){

		var currentObjectId = this.id + this.currentPage;

		if (this.currentPage<this.lastPage){
			this.currentPage++;
		}

		var nextObjectId = this.id + this.currentPage;

		this.switchPage(currentObjectId,nextObjectId);
		
		this.checkLeftArrowVisibility();
		this.checkRightArrowVisibility();		
	},
	
	checkLeftArrowVisibility: function(){
		var leftArrow = $(this.leftArrowId);
		if (this.currentPage==0){
			leftArrow.hide();
		}
		else{
			leftArrow.show();
		}		
	},
	
	checkRightArrowVisibility: function(){
		var rightArrow = $(this.rightArrowId);
		if (this.currentPage==this.lastPage){
			rightArrow.hide();
		}
		else{
			rightArrow.show();
		}
	}
	
});


var ItemGallery = new Class.create({
	
	id: null,
	
	initialize: function(id) {
		this.id = id;
	}
	
	
});


var GalleryManager = new Class.create({
	
	galleries: new Object(),
	
	addGallery: function(id){
		this.removeGallery(id);
		this.galleries[id] = new ItemGallery(id);
	},
	
	addOneByOneGallery: function(id,lastPage,leftArrowId,rightArrowId){
		this.removeGallery(id);
		this.galleries[id] = new OneByOneGallery(id,lastPage,leftArrowId,rightArrowId);
	},
	
	addSlideshowGallery: function(id,lastPage) {
		this.removeGallery(id);
		this.galleries[id] = new SlideshowGallery(id,lastPage);
	},
	
	gallery: function(id){
		return this.galleries[id];
	},
	
	removeGallery: function(id){
		if (this.galleries[id]){
			delete this.galleries[id];			
		}
		this.galleries[id] = null;
	}
	
});

var TabView = new Class.create({
	
	id: null,
	selectedItem: null,
	type: null,
	
	initialize: function(id,selectedItem,type){
		this.id = id;
		
		this.type = type;
		if (!type){
			this.type = 'Icon';			
		}
		
		this.select(selectedItem);
		this.selectedItem = selectedItem;
	},
	
	select: function(itemId){

		if (this.selectedItem){
			$(this.selectedItem + '_content').hide();
			if (this.type=='Icon'){
				$(this.selectedItem).className = 'TabItem';
			}
			else {
				$(this.selectedItem).className = 'TabItemLabel';
				$(this.selectedItem + '_left').className = 'TabItemLabelLeft';
				$(this.selectedItem + '_right').className = 'TabItemLabelRight';
			}
		}

		$(itemId + '_content').show();

		if (this.type=='Icon'){
			$(itemId).className = 'TabItemSelected';
		}
		else { 
			$(itemId).className = 'TabItemLabelSelected';
			if ($(itemId + '_left')){
				$(itemId + '_left').className = 'TabItemLabelLeftSelected';				
			}
			if ($(itemId + '_right')){
				$(itemId + '_right').className = 'TabItemLabelRightSelected';				
			}
		}

		this.selectedItem = itemId;
	},
	
	selectWithCustomAction: function(itemId){
		if (this.selectedItem){
			if (this.type=='Icon'){
				$(this.selectedItem).className = 'TabItem';
			}
			else {
				$(this.selectedItem).className = 'TabItemLabel';	
				$(this.selectedItem + '_left').className = 'TabItemLabelLeft';
				$(this.selectedItem + '_right').className = 'TabItemLabelRight';
			}
		}

		if (this.type=='Icon'){
			$(itemId).className = 'TabItemSelected';
		}
		else { 
			$(itemId).className = 'TabItemLabelSelected';
			if ($(itemId + '_left')){
				$(itemId + '_left').className = 'TabItemLabelLeftSelected';				
			}
			if ($(itemId + '_right')){
				$(itemId + '_right').className = 'TabItemLabelRightSelected';				
			}
		}

		this.selectedItem = itemId;
	},
	
	getCurrentTabContentField: function(){
		var field = $(this.selectedItem + '_content');
		if (field) return field;
		
		var contentFields = Selector.findChildElements($(this.id), ['.TabContent']);
		if (contentFields.length>0){
			return contentFields[0];
		}
		else return null;
	}
	
});

var TabViewManager = new Class.create({
	
	tabViews: new Object(),
	
	initialize: function(){
	},
	
	addTabView: function(id,selectedItem,type){
		this.removeTabView(id);
		this.tabViews[id] = new TabView(id,selectedItem,type);
	},
	
	tabView: function(id){
		return this.tabViews[id];
	},
	
	removeTabView: function(id){
		if (this.tabViews[id]){
			delete this.tabViews[id];			
		}
		this.tabViews[id] = null;	
	}	
});

var tabViewManager = new TabViewManager();

var SlideshowGallery = new Class.create({
	
	id: null,
	lastPage: null,
	currentPage: 0,
	effect: "",
	engine: null,
	time: 1,
	
	initialize: function(id,lastPage,leftArrowId,rightArrowId) {
		this.id = id;
		this.lastPage = lastPage;
		this.effect = "";
	},
	
	start: function(){
		var gallery = this;
		this.engine = new PeriodicalExecuter(function(pe) {
			var fun = gallery.next.bind(gallery);
			fun();
		}, this.time);
	},
	
	stop: function(){
		this.engine.stop();
	},
	
	switchPage: function(oldPage,newPage) {
		if (this.effect==''){
			$(oldPage).style.display = 'none';
			$(newPage).style.display = 'block';			
		}
		else if (this.effect=='fade'){
			Effect.Fade(oldPage, {duration: 0.5});
			Effect.Appear(newPage, {duration: 0.5});
		}
	},
	
	previous: function(){
		
		var currentObjectId = this.id + this.currentPage;
				
		if (this.currentPage>0){
			this.currentPage--;
		}
		else {
			this.currentPage = this.lastPage;
		}
		
		var nextObjectId = this.id + this.currentPage;

		this.switchPage(currentObjectId,nextObjectId);		
	},
	
	next: function(){

		var currentObjectId = this.id + this.currentPage;

		if (this.currentPage<this.lastPage){
			this.currentPage++;
		}
		else {
			this.currentPage = 0;
		}

		var nextObjectId = this.id + this.currentPage;

		this.switchPage(currentObjectId,nextObjectId);		
	}
	
});


var HUDWindow = new Class.create({
	
	id: null,
	title: "",
	draggable: null,
	container: null,
	toggleCallback: null,
	hideCallback: null,
	showCallback: null,
	startCallback: null,
	dragCallback: null,
	endCallback: null,
	visible: true,
	titleNode: null,
	maxHeight: null,
	
	initialize: function(id,title,width,height,minHeight) {
		this.id = id;
		this.title = title;
		this.createWindow(title,width,height,minHeight);
	},
	
	getContentNode: function(){
		return $(this.id + '_content');
	},
	
	setMaxHeight: function(maxHeight){
		this.maxHeight = maxHeight;
		var content = $(this.id + '_content');
		if (content) {
			content.style.maxHeight = this.maxHeight;
		}
	},
	
	showNothingSelected: function(){
		this.showMessage(localizedString.get('Nothing Selected'));
	},
	
	showMessage: function(message){
		this.setContent('<div style=\"margin: 40px; text-align: center; font-family: \'Lucida Grande\'; font-size: 19px; color: grey;\">' + message + '</div>');
	},
	
	toggle: function(){
		var id = this.id;
		Effect.toggle(this.id, 'appear',{ duration: 0.2 ,afterFinish: function(){ document.fire('ws:hudwindow_toggle',{ id: id }); 
									if (hudWindowManager.getHUDWindow(id).isVisible()){ depthManagers['hudWindows'].sendToFront(id); } } });
		this.visible = !this.visible;
		document.fire('ws:hudwindow_changed_visibility',{ id: this.id });
	},
	
	setTitle: function(newTitle){
		this.title = newTitle;
		this.titleNode.innerHTML = newTitle;
	},
	
	open: function(){
		this.show();
		document.fire('ws:hudwindow_open',{ id: this.id });
	},
	
	show: function(){
		$(this.id).show();
		this.visible = true;
		depthManagers['hudWindows'].sendToFront(this.id);
		document.fire('ws:hudwindow_show',{ id: this.id });
		document.fire('ws:hudwindow_changed_visibility',{ id: this.id });
	},
	
	hide: function(){
		$(this.id).hide();
		this.visible = false;
		document.fire('ws:hudwindow_hide',{ id: this.id });
		document.fire('ws:hudwindow_changed_visibility',{ id: this.id });
	},
	
	close: function(){
		this.hide();
		document.fire('ws:hudwindow_close',{ id: this.id });
	},
	
	isVisible: function(){
		return this.visible;
	},
	
	setPosition: function(position){
		$(this.id).style.position = position;
	},
	
	getNode: function(){
		return $(this.id);
	},
	
	setLeftPos: function(left){
		$(this.id).style.left = left;
		this.draggable = new Draggable(this.id, { starteffect: null,endeffect: null,handle: this.id + '_title',onStart:this.startCallback,onDrag: this.dragCallback,onEnd: this.endCallback,zindex:20000 });
	},
	
	setRightPos: function(right){
		
		var left = (pb.core.browserWindow.getWidth() - parseInt(this.container.style.width) - parseInt(right)) + 'px';

		this.setLeftPos(left);
		// $(this.id).style.right = right;
		// this.draggable = new Draggable(this.id, { starteffect: null,endeffect: null,handle: this.id + '_title',onStart:this.startCallback,onDrag: this.dragCallback,onEnd: this.endCallback,zindex:20000 });
	},

	setTopPos: function(top){
		$(this.id).style.top = top;
		this.draggable = new Draggable(this.id, { starteffect: null,endeffect: null,handle: this.id + '_title',onStart:this.startCallback,onDrag: this.dragCallback,onEnd: this.endCallback,zindex:20000 });
	},
	
	setBottomPos: function(bottom){
		$(this.id).style.bottom = bottom;
		this.draggable = new Draggable(this.id, { starteffect: null,endeffect: null,handle: this.id + '_title',onStart:this.startCallback,onDrag: this.dragCallback,onEnd: this.endCallback,zindex:20000 });	
	},
	
	setOnStart: function(callback){
		if (this.draggable){
			this.draggable.destroy();
		}
		
		this.startCallback = callback;
		
		this.draggable = new Draggable(this.id, { starteffect: null,endeffect: null,handle: this.id + '_title',onStart:this.startCallback,onDrag: this.dragCallback,onEnd: this.endCallback,zindex:20000 });
	},

	setOnDrag: function(callback){
		if (this.draggable){
			this.draggable.destroy();
		}
		
		this.dragCallback = callback;
		
		this.draggable = new Draggable(this.id, { starteffect: null,endeffect: null,handle: this.id + '_title',onStart:this.startCallback,onDrag: this.dragCallback,onEnd: this.endCallback,zindex:20000 });
	},
	
	setOnEnd: function(callback){
		if (this.draggable){
			this.draggable.destroy();
		}
		
		this.endCallback = callback;
		
		this.draggable = new Draggable(this.id, { starteffect: null,endeffect: null,handle: this.id + '_title',onStart:this.startCallback,onDrag: this.dragCallback,onEnd: this.endCallback,zindex:20000 });
	},
	
	setContentPadding: function(top,bottom,left,right){
		if (top){
			$(this.id + '_content').style.paddingTop = top;
		}
		if (bottom){
			$(this.id + '_content').style.paddingBottom = bottom;
		}
		if (left){
			$(this.id + '_content').style.paddingLeft = left;
		}
		if (right){
			$(this.id + '_content').style.paddingRight = right;
		}	
	},
	
	createWindow: function(titleText,width,height,minHeight){
		
		var iconTitleLeft = system.getLibraryPath() + '/plasticbriqFramework/interfaceFiles/images/hud_title_left.png';
		var iconTitleRight = system.getLibraryPath() + '/plasticbriqFramework/interfaceFiles/images/hud_title_right.png';
		var iconTitleClose = system.getLibraryPath() + '/plasticbriqFramework/interfaceFiles/images/hud_close.png';
				
		var container = new Element('div',{ 'id': this.id, 'class' : 'hudWindow' });
		container.style.width = width;
		container.style.height = height;
		if (container.style.minHeight){
			container.style.minHeight = minHeight;			
		}
		container.style.position = 'absolute';
		container.style.color = 'white';
		container.style.zIndex = 10000;
		container.style.fontFamily = 'verdana';
		container.setAttribute("onclick", "depthManagers['hudWindows'].sendToFront('" + this.id + "');event.cancelBubble = true;return false;");
		
		this.container = container;
		
		// container.style.backgroundColor = 'black';

		var title = new Element('div',{ 'id': this.id + '_title', 'width': '100%' });
		title.style.width = '100%';
		title.style.height = '20px';
		title.style.textAlign = 'center';
		title.style.fontSize = '12px';
				
		var titleLeft = new Element('div',{ 'width': '7px','height': '19px' });
		titleLeft.style.width = '8px';
		titleLeft.style.height = '20px';
		titleLeft.style.position = 'absolute';
		titleLeft.style.left = 0;
		titleLeft.style.background = "url(" + iconTitleLeft + ")";
		
		var titleClose = new Element('div',{ 'id': this.id + '_close' });
		titleClose.style.width = '13px';
		titleClose.style.height = '13px';
		titleClose.style.position = 'absolute';
		titleClose.style.left = '5px';
		titleClose.style.top = '4px';
		titleClose.style.zIndex = 10010;
		titleClose.style.background = "url(" + iconTitleClose + ')';
		titleClose.style.cursor = 'pointer';
		titleClose.style.cursor = 'hand';
		
		//titleClose.windowId = this.id;
		titleClose.setAttribute("onclick","hudWindowManager.getHUDWindow('" + this.id + "').close();event.cancelBubble = true;return false;");
		//Element.observe(titleClose,'click',function (event) { hudWindowManager.getHUDWindow(this.windowId).close(); } );
		
		var titleRight = new Element('div');
		titleRight.style.width = '8px';
		titleRight.style.height = '20px';
		titleRight.style.position = 'absolute';
		titleRight.style.right = 0;
		titleRight.style.top = 0;
		titleRight.style.background = "url(" + iconTitleRight + ")";		


		var titleCenter = new Element('div',{ 'id': this.id + '_title_center' });
		titleCenter.innerHTML = titleText;
		titleCenter.style.position = 'absolute';
		titleCenter.style.left = '7px';
		titleCenter.style.width = (parseInt(width)-14) + 'px';
		titleCenter.style.height = '19px';
		titleCenter.style.lineHeight = '19px';
		titleCenter.style.top = 0;
		titleCenter.style.backgroundColor = '#363636';
		titleCenter.style.cursor = 'default';
		titleCenter.style.borderTopStyle = 'solid';
		titleCenter.style.borderTopColor = '#999';
		titleCenter.style.borderTopWidth = '1px';
		this.titleNode = titleCenter;
		
		var content = new Element('div',{ 'id': this.id + '_content', 'class' : 'hudContent' });
		content.style.backgroundColor = '#2a2a2a';
		content.style.width = (parseInt(width)-2) + 'px';
		if (height){
			content.style.height = (parseInt(height) - 19) + 'px';			
		}

		content.style.color = 'white';
		content.style.overflow = 'auto';
		content.style.fontSize = '11px';
		content.style.borderLeftStyle = 'solid';
		content.style.borderLeftColor = '#999';
		content.style.borderLeftWidth = '1px';
		content.style.borderBottomStyle = 'solid';
		content.style.borderBottomColor = '#999';
		content.style.borderBottomWidth = '1px';
		content.style.borderRightStyle = 'solid';
		content.style.borderRightColor = '#999';
		content.style.borderRightWidth = '1px';
		
		if (this.maxHeight){
			content.style.maxHeight = maxHeight;
		}
		
		// content.style.paddingLeft = '3px';
		// content.style.paddingRight = '3px';
		// content.style.paddingTop = '3px';
		// content.style.paddingBottom = '3px';
		// content.style.scrollbarShadowColor="colorname"
		// content.style.scrollbarHighlightColor="colorname"
		// content.style.scrollbar3dlightColor="colorname"
		// content.style.scrollbarDarkshadowColor="colorname"
		
		// content.style.marginTop = '-19px';
				
		title.appendChild(titleLeft);
		title.appendChild(titleClose);
		title.appendChild(titleCenter);
		title.appendChild(titleRight);
		
		container.appendChild(title);
		container.appendChild(content);
		
		document.body.appendChild(container);
		
		this.draggable = new Draggable(this.id, { starteffect: null, endeffect: null,handle: this.id + '_title',zindex:20000 });
		depthManagers['hudWindows'].addField(this.id);
	},
	
	
	setContent: function(content) {
		$(this.id + '_content').innerHTML = content;
	},

	setContentWithURL: function(url,parameters) {
		
		var progressIcon = system.getLoadingIconBlack();
		this.setContent('<div style="height: 100px;"><img style="display:table;margin-top:50px;margin-left:auto;margin-right:auto;" title="' + localizedString.get('Loading data...') + '" src="' + progressIcon + '"/></div>');
		
		var popUpId = this.id;
		new Ajax.Request(url, {
			method:'post',
			parameters:parameters,
			onSuccess: function(transport) {
				$(popUpId + '_content').innerHTML = transport.responseText;
				
				system.evalAllScripts(popUpId + '_content');
				document.fire('ws:init');
			}
		});
	}
		
});

var HUDWindowManager = new Class.create({
	
	HUDWindows: new Object(),
	
	initialize: function(){
		depthManagers['hudWindows'] = new DepthManager(2000,3000);
	},
	
	addHUDWindow: function(id,title,width,height){
		this.removeHUDWindow(id);
		this.HUDWindows[id] = new HUDWindow(id,title,width,height);
	},
		
	getHUDWindow: function(id){		
		return this.HUDWindows[id];
	},
	
	removeHUDWindow: function(id){
		if (this.HUDWindows[id]){
			delete this.HUDWindows[id];			
		}
		this.HUDWindows[id] = null;
	}
	
});


var ViewportPlacer = new Class.create({
	
	place: function(nodeId,horizontal,vertical){
		var node = $(nodeId);
		node.style.position = 'absolute';
		
		var width = node.offsetWidth;
		var height = node.offsetHeight;
		
		if (!width){
			width = parseInt(node.style.width);
		}
		
		if (height==0){
			height = parseInt(node.style.height);
			if (isNaN(height)){
				height = 10;
			}
		}
		
		var viewportSize = system.getViewportSize();
		var scrolls = system.getScrolls();
		
		var w3 = viewportSize[0]/3;
		var h3 = viewportSize[1]/3;
		
		var posX = 0;
		var posY = 0;
		
		if (width<w3){
			if (horizontal=='left'){
				posX = (w3-width)/2;
			}
			else if (horizontal=='right'){
				posX = 2*w3 + (w3-width)/2;
			}
			else {
				posX = w3 + (w3-width)/2;
			}
		}
		else {
			if (horizontal=='left'){
				posX = 0;
			}
			else if (horizontal=='right'){
				posX = viewportSize[0]-width;
			}
			else {
				posX = (viewportSize[0]-width)/2;
			}
		}
		
		if (height<h3){
			if (vertical=='top'){
				posY = (h3-height)/2;
			}
			else if (vertical=='bottom'){
				posY = 2*h3 + (h3-height)/2;
			}
			else {
				posY = h3 + (h3-height)/2;
			}
		}
		else {
			if (vertical=='top'){
				posY = 0;
			}
			else if (vertical=='bottom'){
				posY = viewportSize[1]-height;
			}
			else {
				posY = (viewportSize[1]-height)/2;
			}
		}
		
		
		node.style.left = posX + 'px';
		if (posY){
			node.style.top = posY + 'px';
		}
		else {
			node.style.top = '100px';
		}
	}
	
});

var viewportPlacer = new ViewportPlacer();


var ValueObserver = Class.create(Abstract.TimedObserver, {
	currentValue: null,
  getValue: function() {
    return this.currentValue;
  }
});


var Resizer = new Class.create({
	
	id: null,
	zIndex: null,
	container: null,
	topLeftDragger: null,
	topDragger: null,
	topRightDragger: null,
	leftDragger: null,
	rightDragger: null,
	bottomLeftDragger: null,
	bottomDragger: null,
	bottomRightDragger: null,

	containerDraggable: null,
	topLeftDraggable: null,
	topDraggable: null,
	topRightDraggable: null,	
	leftDraggable: null,
	rightDraggable: null,
	bottomLeftDraggable: null,
	bottomDraggable: null,
	bottomRightDraggable: null,
	
	draggerWidth: 6,
	draggerHeight: 6,
	draggerWidth2: 3,
	draggerHeight2: 3,
	
	moveInc: 1,
	moveIncFast: 5,
		
	mousePosX: null,
	mousePosY: null,
	
	clickCallback: null,
	dblClickCallback: null,
	startDragCallback: null,
	dragCallback: null,
	endDragCallback: null,
	startResizeCallback: null,
	resizeCallback: null,
	
	handlesVisible: false,
	handlesDisabled: false,
	
	undoManager: null,
	
	oldLeft:0,
	oldTop: 0,
	
	minWidth: null,
	minHeight: null,
			
	initialize: function(id,zIndex){
		this.id = id;
		if (zIndex){
			this.zIndex = zIndex;
		}
		else {
			this.zIndex = 10000;
		}

		this.createDraggers();
	},
	
	setUndoManager: function(undoManager){
		this.undoManager = undoManager;
	},
	
	getUndoManager: function(undoManager){
		return this.undoManager;
	},
		
	update: function(dragging) {
	
		var field = $(this.id);
		
		if (!field) {
			return;
		}
		
		anchorLeft = field.getAttribute('anchorLeft');
		anchorTop = field.getAttribute('anchorTop');
		if (dragging || (field.style.position!='fixed')){
			if (anchorLeft!='center') anchorLeft = 'left';
			if (anchorTop!='center') anchorTop = 'top';
		}

		// Ajustar contenedor
		this.adjustContainerToNode(field,anchorLeft,anchorTop);
		
		// Ajustar los controles para redimensionar
		var dw2 = this.draggerWidth2;//  (this.draggerWidth/2);
		var dh2 = this.draggerHeight2; // (this.draggerHeight/2);
		var width = pb.core.cssUtils.getWidth(field);
		var height = pb.core.cssUtils.getHeight(field);
		var w2 = (width/2);
		var h2 = (height/2);

		// Ajustar pivotes horizontalmente
		if (anchorLeft=='both'){
			var left = field.offsetLeft;
			if (this.topLeftDragger){
				this.topLeftDragger.style.left = (left - dw2) + 'px';
				this.topLeftDragger.style.right = '';
			}
			
			this.leftDragger.style.left = left + 'px';
			this.leftDragger.style.right = '';
			
			if (this.bottomLeftDragger){
				this.bottomLeftDragger.style.left = left + 'px';
				this.bottomLeftDragger.style.right = '';
			}
			
			var right = (parseInt(field.style.right)||0);
			//var left = right + width -dw2;
			right -= dw2;
			
			if (this.topRightDragger){
				this.topRightDragger.style.left = '';
				this.topRightDragger.style.right = right + 'px';
			}
			
			this.rightDragger.style.left = '';
			this.rightDragger.style.right = right + 'px';
			
			if (this.bottomRightDragger){
				this.bottomRightDragger.style.left = '';
				this.bottomRightDragger.style.right = right + 'px';				
			}
			
		}
		else if (anchorLeft=='right'){
			var right = (parseInt(field.style.right)||0);
			var left = right + width -dw2;
			right -= dw2;
			
			if (this.topLeftDragger){
				this.topLeftDragger.style.left = '';
				this.topLeftDragger.style.right = left + 'px';				
			}
			if (this.topDragger){
				this.topDragger.style.left = '';
				this.topDragger.style.right = (right + w2) + 'px';				
			}
			if (this.topRightDragger){
				this.topRightDragger.style.left = '';
				this.topRightDragger.style.right = right + 'px';				
			}
			if (this.leftDragger){
				this.leftDragger.style.left = '';
				this.leftDragger.style.right = left + 'px';				
			}
			if (this.rightDragger){
				this.rightDragger.style.left = '';
				this.rightDragger.style.right = right + 'px';
			}
			if (this.bottomLeftDragger){
				this.bottomLeftDragger.style.left = '';
				this.bottomLeftDragger.style.right = left + 'px';				
			}
			if (this.bottomDragger){
				this.bottomDragger.style.left = '';
				this.bottomDragger.style.right = (right + w2) + 'px';
			}
			if (this.bottomRightDragger){
				this.bottomRightDragger.style.left = '';
				this.bottomRightDragger.style.right = right + 'px';				
			}
		}
		else if (anchorLeft!='center'){
			var left = field.offsetLeft - dh2;
			var right = left + (parseInt(field.offsetWidth)||0);
			if (this.topLeftDragger) this.topLeftDragger.style.left = left + 'px';
			if (this.topLeftDragger) this.topLeftDragger.style.right = '';
			if (this.topDragger) this.topDragger.style.left = (left + w2) + 'px';
			if (this.topDragger) this.topDragger.style.right = '';
			if (this.topRightDragger) this.topRightDragger.style.left = right + 'px';
			if (this.topRightDragger) this.topRightDragger.style.right = '';
			
			if (this.leftDragger) this.leftDragger.style.left = left + 'px';
			if (this.leftDragger) this.leftDragger.style.right = '';
			if (this.rightDragger) this.rightDragger.style.left = right + 'px';
			if (this.rightDragger) this.rightDragger.style.right = '';
			if (this.bottomLeftDragger) this.bottomLeftDragger.style.left = left + 'px';
			if (this.bottomLeftDragger) this.bottomLeftDragger.style.right = '';
			if (this.bottomDragger) this.bottomDragger.style.left = (left + w2) + 'px';
			if (this.bottomDragger) this.bottomDragger.style.right = '';
			if (this.bottomRightDragger) this.bottomRightDragger.style.left = right + 'px';
			if (this.bottomRightDragger) this.bottomRightDragger.style.right = '';
		}
		
		
		//Ajustar pivotes verticalmente
		if (anchorTop=='both'){
			var top = field.offsetTop;
			top = top - dh2;
			bottom = top + height;

			this.topDragger.style.top = top + 'px';
			this.topDragger.style.bottom = '';

			if (anchorLeft!='center'){
				this.topLeftDragger.style.top = (top - dh2) + 'px';
				this.topLeftDragger.style.bottom = '';
				this.topRightDragger.style.top = top + 'px';
				this.topRightDragger.style.bottom = '';				
			}
			
			
			var bottom = (parseInt(field.style.bottom)||0);
			var top = (bottom + height - dh2);
			
			bottom -= dh2;

			this.bottomDragger.style.bottom = bottom + 'px';
			this.bottomDragger.style.top = '';

			if (anchorLeft!='center'){
				this.bottomLeftDragger.style.bottom = bottom + 'px';
				this.bottomLeftDragger.style.top = '';
				this.bottomRightDragger.style.bottom = bottom + 'px';
				this.bottomRightDragger.style.top = '';				
			}
			
		}
		else if (anchorTop=='bottom'){
			
			var bottom = (parseInt(field.style.bottom)||0);
			var top = (bottom + height - dh2);
			
			bottom -= dh2;

			this.topDragger.style.top = '';
			this.topDragger.style.bottom = top + 'px';
			this.bottomDragger.style.bottom = bottom + 'px';
			this.bottomDragger.style.top = '';			
			
			if (anchorLeft!='center'){
				this.topLeftDragger.style.top = '';
				this.topLeftDragger.style.bottom = top + 'px';
				this.topRightDragger.style.top = '';
				this.topRightDragger.style.bottom = top + 'px';
				this.leftDragger.style.bottom = (bottom + h2) + 'px';
				this.leftDragger.style.top = '';
				this.rightDragger.style.bottom = (bottom + h2) + 'px';
				this.rightDragger.style.top = '';
				this.bottomLeftDragger.style.bottom = bottom + 'px';
				this.bottomLeftDragger.style.top = '';
				this.bottomRightDragger.style.bottom = bottom + 'px';
				this.bottomRightDragger.style.top = '';				
			}

		}
		else if (anchorTop!='center'){
			var top = field.offsetTop;
			top = top - dh2;
			bottom = top + height;

			this.topDragger.style.top = top + 'px';
			this.topDragger.style.bottom = '';
			this.bottomDragger.style.top = bottom + 'px';
			this.bottomDragger.style.bottom = '';

			if (anchorLeft!='center'){
				this.topLeftDragger.style.top = top + 'px';
				this.topLeftDragger.style.bottom = '';
				this.topRightDragger.style.top = top + 'px';
				this.topRightDragger.style.bottom = '';
				this.leftDragger.style.top = (top + h2) + 'px';
				this.leftDragger.style.bottom = '';
				this.rightDragger.style.top = (top + h2) + 'px';
				this.rightDragger.style.bottom = '';
				this.bottomLeftDragger.style.top = bottom + 'px';
				this.bottomLeftDragger.style.bottom = '';
				this.bottomRightDragger.style.top = bottom + 'px';
				this.bottomRightDragger.style.bottom = '';
			}

		}
		
		var left = field.offsetLeft;
		var top = field.offsetTop;
		
		if (width<this.minWidth) width = this.minWidth;
		if (height<this.minHeight) height = this.minHeight;
		
		width = width + 'px';
		height = height + 'px';

		if (anchorLeft!='both'){
			this.container.style.width = width;			
			this.setFieldWidth(width + 'px');
		}
		
		if (anchorTop!='both'){
			this.container.style.height = height;
			this.setFieldHeight(height + 'px');
		}
	},
	
	appendPixels: function(value){
	
		var result = String(value).trim();
		if (parseInt(result)==result) {
			result = result + 'px';
		}
		return result;
	},

	setFieldWidth: function(value){
		
		var field = $(this.id);
		
		var originalValue = value;

		if (value<0) value = 0;
		
		var paddingLeft = parseInt(field.style.paddingLeft);
		var paddingRight = parseInt(field.style.paddingRight);
		
		if (isNaN(paddingLeft)){
			paddingLeft = 0;
		}

		if (isNaN(paddingRight)){
			paddingRight = 0;
		}
		
		value = parseInt(value) - paddingLeft - paddingRight;
				
		value = this.appendPixels(value);
		if (!originalValue || (originalValue=="")){
			value = "";
			field.style.width = 'auto';
		}
		else {
			field.style.width = value;
		}	
	},
	
	setFieldHeight: function(value){
		
		var field = $(this.id);
		
		var originalValue = value;

		if (parseInt(value)<0) value = 0;
		
		var paddingTop = parseInt(field.style.paddingTop);
		var paddingBottom = parseInt(field.style.paddingBottom);
				
		if (isNaN(paddingTop)){
			paddingTop = 0;
		}

		if (isNaN(paddingBottom)){
			paddingBottom = 0;
		}
		
		value = parseInt(value) - paddingTop - paddingBottom;
		
		value = this.appendPixels(value);
		if (!originalValue || (originalValue=="")){
			value = "";
			field.style.height = '';
		}
		else {
			field.style.height = value;
		}
	},
	
	selected: function(){
		return this.handlesVisible;
	},
	
	updateZIndex: function(){
		var field = $(this.id);
		if (!field) return;
		var zIndex = parseInt(field.style.zIndex);
		if ((!zIndex) || (isNaN(zIndex))) return;
		
		this.container.style.zIndex = zIndex;
		
		zIndex = zIndex + 10;
		
		this.topDragger.style.zIndex = zIndex;
		this.bottomDragger.style.zIndex = zIndex;
					
		if ($(this.id).getAttribute('anchorLeft')!='center'){
			this.topLeftDragger.style.zIndex = zIndex;			
			this.topRightDragger.style.zIndex = zIndex;
			this.leftDragger.style.zIndex = zIndex;
			this.rightDragger.style.zIndex = zIndex;
			this.bottomLeftDragger.style.zIndex = zIndex;
			this.bottomRightDragger.style.zIndex = zIndex;			
		}
		
	},
	
	addCommand: function(id,callback,undoCallback){
		if (this.undoManager){
			var command = new CallbackCommand(id,callback.bind(this),undoCallback.bind(this));
			this.undoManager.pushCommand(command);
		}
		else {
			callback();
		}
	},
	
	moveLeft: function(){
		var field = $(this.id);
		if (!field) return;
		field.style.left = (parseInt(field.style.left) - this.moveInc) + 'px';
		this.update();		
	},

	moveRight: function(){
		var field = $(this.id);
		if (!field) return;
		field.style.left = (parseInt(field.style.left) + this.moveInc) + 'px';
		this.update();		
	},
	
	moveUp: function(){
		var field = $(this.id);
		if (!field) return;
		field.style.top = (parseInt(field.style.top) - this.moveInc) + 'px';
		this.update();		
	},
	
	
	moveDown: function(){
		var field = $(this.id);
		if (!field) return;
		field.style.top = (parseInt(field.style.top) + this.moveInc) + 'px';
		this.update();		
	},
	
	moveLeftFast: function(){
		var field = $(this.id);
		if (!field) return;
		field.style.left = (parseInt(field.style.left) - this.moveIncFast) + 'px';
		this.update();		
	},

	moveRightFast: function(){
		var field = $(this.id);
		if (!field) return;
		field.style.left = (parseInt(field.style.left) + this.moveIncFast) + 'px';
		this.update();		
	},
	
	moveUpFast: function(){
		var field = $(this.id);
		if (!field) return;
		field.style.top = (parseInt(field.style.top) - this.moveIncFast) + 'px';
		this.update();		
	},
	
	
	moveDownFast: function(){
		var field = $(this.id);
		if (!field) return;
		field.style.top = (parseInt(field.style.top) + this.moveIncFast) + 'px';
		this.update();		
	},
	
	saveMousePosition: function(event){
		this.mousePosX = Event.pointerX(event);
		this.mousePosY = Event.pointerY(event);
	},
	
	mouseMoved: function(event){
		if (!this.mousePosX) return true;
		if (!this.mousePosY) return true;
				
		var mousePosX = Event.pointerX(event);
		var mousePosY = Event.pointerY(event);
		if (((mousePosX-this.mousePosX)==0) && ((mousePosY-this.mousePosY)==0)){
			return false;
		}
		return true;
	},
	
	clickEvent: function(){
		if (this.clickCallback){
			this.clickCallback();
		}
	},
	
	dblClickEvent: function(){
		if (this.dblClickCallback){
			this.dblClickCallback();
		}
	},
	
	startDragEvent: function(){
		if (this.startDragCallback){
			this.startDragCallback();
		}	
	},
	
	dragEvent: function(){
		if (this.dragCallback){
			this.dragCallback();
		}
	},
	
	endDragEvent: function(){
		if (this.endDragCallback){
			this.endDragCallback();
		}
	},
		
	disableMouseOver: function (){
		Event.stopObserving(this.container,'mouseover',this.containerMouseover);
		Event.stopObserving(this.container,'mouseout', this.containerMouseout);	
	},
	
	// Activado por defecto
	enableMouseOver: function(){
		Element.observe(this.container,'mouseover',this.containerMouseover);
		Element.observe(this.container,'mouseout', this.containerMouseout);	
	},
	
	adjustNodeForDragging: function(field){
		if (field.getAttribute('anchorLeft')=='both'){
			var left = (parseInt(field.style.left)||0);
			var right = (parseInt(field.style.right)||0);
			field.style.left = left + 'px';
			field.style.right = right + 'px';
		}
		else if (field.getAttribute('anchorLeft')=='right'){
			var right = (parseInt(field.style.right)||0);
			var left = pb.core.cssUtils.calculateLeftPosFromRight(field);
			field.style.left = left + 'px';
			field.style.right = '';
		}
		else {
			field.style.right = '';
		}


		if (field.getAttribute('anchorTop')=='both'){
			var top = (parseInt(field.style.top)||0);
			var bottom = (parseInt(field.style.bottom)||0);
			field.style.top = top + 'px';
			field.style.bottom = bottom + 'px';
		}
		else if (field.getAttribute('anchorTop')=='bottom'){
			var bottom = (parseInt(field.style.bottom)||0);
			var top = pb.core.cssUtils.calculateTopPosFromBottom(field);
			field.style = top + 'px';
			field.style.bottom = '';
		}
		else {
			field.style.bottom = '';
		}
	},
	
	adjustContainerToNode: function(field,anchorLeft,anchorTop){
		this.container.style.position = field.style.position;
		//console.time('adjustContainerToNode');
		if (anchorLeft=='both'){
			var left = (parseInt(field.style.left)||0);
			var right = (parseInt(field.style.right)||0);
			this.container.style.left = left + 'px';
			this.container.style.right = right + 'px';
		}
		else if (anchorLeft=='right'){
			var right = (parseInt(field.style.right)||0);
			var left = pb.core.cssUtils.calculateLeftPosFromRight(field);
			this.container.style.left = '';
			this.container.style.right = right + 'px';
		}
		else if (anchorLeft=='center'){
			this.container.style.left = field.style.left;
			this.container.style.marginLeft = field.style.marginLeft;
		}
		else {
			var left = parseInt(field.offsetLeft);
			
			//console.log('adjusting container to node. Left ' + left);
						
			this.container.style.left = left + 'px';
			this.container.style.right = '';
		}
		
		if (anchorTop=='both'){
			var top = (parseInt(field.style.top)||0);
			var bottom = (parseInt(field.style.bottom)||0);
			this.container.style.top = top + 'px';
			this.container.style.bottom = bottom + 'px';
		}
		else if (anchorTop=='bottom'){
			var bottom = (parseInt(field.style.bottom)||0);
			var top = pb.core.cssUtils.calculateTopPosFromBottom(field);
			this.container.style.top = '';
			this.container.style.bottom = bottom + 'px';
		}
		else if (anchorTop=='center'){
			this.container.style.top = field.style.top;
			this.container.style.marginTop = field.style.marginTop;
		}
		else {
			var top = parseInt(field.offsetTop);
			var bottom = pb.core.cssUtils.getOffsetBottom(field);
			this.container.style.top = top + 'px';
			this.container.style.bottom = '';
		}
		//console.timeEnd('adjustContainerToNode');
	},

	
	adjustForDragging: function(node,anchorLeft,anchorTop){
		
		if (anchorLeft=='both'){
			var leftPos = (parseInt(node.style.left)||0);
			node.style.width = leftPos + (pb.core.cssUtils.switchToLeftCoords(parseInt(node.style.right)||0)-leftPos);
			node.style.right = '';
		}
		else if (anchorLeft=='right'){
			if (node.style.right=='') return; // Por si nos llaman 2 veces
			node.style.left = pb.core.cssUtils.calculateLeftPosFromRight(node);
			node.style.right = '';
		}
		
		if (anchorTop=='both'){
			var topPos = (parseInt(node.style.top)||0);
			node.style.height = topPos + (pb.core.cssUtils.switchToTopCoords(parseInt(node.style.bottom)||0)-topPos);
			node.style.bottom = '';
		}
		else if (anchorTop=='bottom'){
			if (node.style.bottom=='') return; // Por si nos llaman 2 veces
			node.style.top = pb.core.cssUtils.calculateTopPosFromBottom(node);
			node.style.bottom = '';
		}	
	},
	
	restoreFromDragging: function(node,anchorLeft,anchorTop){
		if (anchorLeft=='both'){			
			node.style.right = pb.core.cssUtils.calculateRightPosFromLeft(node);
			node.style.width = '';
		}
		else if (anchorLeft=='right'){
			node.style.right = pb.core.cssUtils.calculateRightPosFromLeft(node);
			node.style.left = '';
		}
		
		if (anchorTop=='both'){
			node.style.bottom = pb.core.cssUtils.calculateBottomPosFromTop(node);
			node.style.height = '';
		}
		else if (anchorTop=='bottom'){
			node.style.bottom = pb.core.cssUtils.calculateBottomPosFromTop(node);
			node.style.top = '';
		}	
	},
	
	prepareForDragging: function(){
		field = $(this.id);
		var anchorLeft = field.getAttribute('anchorLeft');
		var anchorTop = field.getAttribute('anchorTop');

		this.adjustForDragging(field,anchorLeft,anchorTop);
		this.adjustForDragging(this.container,anchorLeft,anchorTop);
		
		if (anchorTop!='center'){
			if (anchorLeft!='center'){
				this.adjustForDragging(this.topDragger,anchorLeft,anchorTop);		
				this.adjustForDragging(this.bottomDragger,anchorLeft,anchorTop);
				this.adjustForDragging(this.topLeftDragger,anchorLeft,anchorTop);
				this.adjustForDragging(this.topRightDragger,anchorLeft,anchorTop);			
				this.adjustForDragging(this.bottomLeftDragger,anchorLeft,anchorTop);
				this.adjustForDragging(this.bottomRightDragger,anchorLeft,anchorTop);
				this.adjustForDragging(this.leftDragger,anchorLeft,anchorTop);
				this.adjustForDragging(this.rightDragger,anchorLeft,anchorTop);				
			}
			else {
				this.adjustForDragging(this.topDragger,anchorLeft,anchorTop);		
				this.adjustForDragging(this.bottomDragger,anchorLeft,anchorTop);
			}			
		}
		else {
			if (anchorLeft!='center'){
				this.adjustForDragging(this.leftDragger,anchorLeft,anchorTop);
				this.adjustForDragging(this.rightDragger,anchorLeft,anchorTop);
			}
		}
	},
	
	prepareForStopDragging: function(){
		field = $(this.id);
		var anchorLeft = field.getAttribute('anchorLeft');
		var anchorTop = field.getAttribute('anchorTop');
		
		this.restoreFromDragging(field,anchorLeft,anchorTop);
		this.restoreFromDragging(this.container,anchorLeft,anchorTop);
		
		if (anchorTop!='center'){
			if (anchorLeft!='center'){
				this.restoreFromDragging(this.topDragger,anchorLeft,anchorTop);		
				this.restoreFromDragging(this.bottomDragger,anchorLeft,anchorTop);
				this.restoreFromDragging(this.topLeftDragger,anchorLeft,anchorTop);
				this.restoreFromDragging(this.topRightDragger,anchorLeft,anchorTop);			
				this.restoreFromDragging(this.bottomLeftDragger,anchorLeft,anchorTop);
				this.restoreFromDragging(this.bottomRightDragger,anchorLeft,anchorTop);
				this.restoreFromDragging(this.leftDragger,anchorLeft,anchorTop);
				this.restoreFromDragging(this.rightDragger,anchorLeft,anchorTop);				
			}
			else {
				this.restoreFromDragging(this.topDragger,anchorLeft,anchorTop);		
				this.restoreFromDragging(this.bottomDragger,anchorLeft,anchorTop);
			}			
		}
		else {
			if (anchorLeft!='center'){
				this.restoreFromDragging(this.leftDragger,anchorLeft,anchorTop);
				this.restoreFromDragging(this.rightDragger,anchorLeft,anchorTop);
			}
		}
	},
	
	initTopDragger: function(field,left,right,top,bottom,w2,h2,zIndex){
		this.topDragger = document.createElement('div');
		this.topDragger.id = 'topDragger_' + this.id;
		this.topDragger.style.width = this.draggerWidth + 'px';
		this.topDragger.style.height = this.draggerHeight + 'px';
		this.topDragger.style.backgroundColor = 'white';
		this.topDragger.style.borderLeftColor = 'black';
		this.topDragger.style.borderLeftStyle = 'solid';
		this.topDragger.style.borderLeftWidth = '1px';
		this.topDragger.style.borderTopColor = 'black';
		this.topDragger.style.borderTopStyle = 'solid';
		this.topDragger.style.borderTopWidth = '1px';
		this.topDragger.style.borderRightColor = 'black';
		this.topDragger.style.borderRightStyle = 'solid';
		this.topDragger.style.borderRightWidth = '1px';
		this.topDragger.style.borderBottomColor = 'black';
		this.topDragger.style.borderBottomStyle = 'solid';
		this.topDragger.style.borderBottomWidth = '1px';
		this.topDragger.style.position = field.style.position;
		//if (field.style.position=='fixed') this.topDragger.style.position = 'fixed';
		this.topDragger.style.left = (left + w2) + 'px';
		this.topDragger.style.top = top + 'px';
		this.topDragger.style.cursor = 'n-resize';
		this.topDragger.style.zIndex = zIndex;
		this.topDragger.setAttribute("onclick", "event.cancelBubble = true;return false;");
		this.topDragger.style.display = 'none';
		field.parentNode.appendChild(this.topDragger);
	},
	
	initTopLeftDragger: function(field,left,right,top,bottom,w2,h2,zIndex){
		this.topLeftDragger = document.createElement('div');
		this.topLeftDragger.id = 'topLeftDragger_' + this.id;
		this.topLeftDragger.style.width = this.draggerWidth + 'px';
		this.topLeftDragger.style.height = this.draggerHeight + 'px';
		this.topLeftDragger.style.backgroundColor = 'white';
		this.topLeftDragger.style.borderLeftColor = 'black';
		this.topLeftDragger.style.borderLeftStyle = 'solid';
		this.topLeftDragger.style.borderLeftWidth = '1px';
		this.topLeftDragger.style.borderTopColor = 'black';
		this.topLeftDragger.style.borderTopStyle = 'solid';
		this.topLeftDragger.style.borderTopWidth = '1px';
		this.topLeftDragger.style.borderRightColor = 'black';
		this.topLeftDragger.style.borderRightStyle = 'solid';
		this.topLeftDragger.style.borderRightWidth = '1px';
		this.topLeftDragger.style.borderBottomColor = 'black';
		this.topLeftDragger.style.borderBottomStyle = 'solid';
		this.topLeftDragger.style.borderBottomWidth = '1px';
		this.topLeftDragger.style.position = field.style.position;

		//if (field.style.position=='fixed') this.topLeftDragger.style.position = 'fixed';
		this.topLeftDragger.style.left = left + 'px';
		this.topLeftDragger.style.top = top + 'px';		
	
		this.topLeftDragger.style.cursor = 'nw-resize';
		this.topLeftDragger.style.zIndex = zIndex;
		this.topLeftDragger.setAttribute("onclick", "event.cancelBubble = true;return false;");
		this.topLeftDragger.style.display = 'none';	
		field.parentNode.appendChild(this.topLeftDragger);	
	},
	
	initTopRightDragger: function (field,left,right,top,bottom,w2,h2,zIndex){
		this.topRightDragger = document.createElement('div');
		this.topRightDragger.id = 'topRightDragger_' + this.id;
		this.topRightDragger.style.width = this.draggerWidth + 'px';
		this.topRightDragger.style.height = this.draggerHeight + 'px';
		this.topRightDragger.style.backgroundColor = 'white';
		this.topRightDragger.style.borderLeftColor = 'black';
		this.topRightDragger.style.borderLeftStyle = 'solid';
		this.topRightDragger.style.borderLeftWidth = '1px';
		this.topRightDragger.style.borderTopColor = 'black';
		this.topRightDragger.style.borderTopStyle = 'solid';
		this.topRightDragger.style.borderTopWidth = '1px';
		this.topRightDragger.style.borderRightColor = 'black';
		this.topRightDragger.style.borderRightStyle = 'solid';
		this.topRightDragger.style.borderRightWidth = '1px';
		this.topRightDragger.style.borderBottomColor = 'black';
		this.topRightDragger.style.borderBottomStyle = 'solid';
		this.topRightDragger.style.borderBottomWidth = '1px';
		this.topRightDragger.style.position = field.style.position;
		//if (field.style.position=='fixed') this.topRightDragger.style.position = 'fixed';
		this.topRightDragger.style.left = right + 'px';
		this.topRightDragger.style.top = top + 'px';
		this.topRightDragger.style.cursor = 'ne-resize';
		this.topRightDragger.style.zIndex = zIndex;
		this.topRightDragger.setAttribute("onclick", "event.cancelBubble = true;return false;");
		this.topRightDragger.style.display = 'none';
		field.parentNode.appendChild(this.topRightDragger);
	},

	initBottomLeftDragger: function (field,left,right,top,bottom,w2,h2,zIndex){
		this.bottomLeftDragger = document.createElement('div');
		this.bottomLeftDragger.id = 'bottomLeftDragger_' + this.id;
		this.bottomLeftDragger.style.width = this.draggerWidth + 'px';
		this.bottomLeftDragger.style.height = this.draggerHeight + 'px';
		this.bottomLeftDragger.style.backgroundColor = 'white';
		this.bottomLeftDragger.style.borderLeftColor = 'black';
		this.bottomLeftDragger.style.borderLeftStyle = 'solid';
		this.bottomLeftDragger.style.borderLeftWidth = '1px';
		this.bottomLeftDragger.style.borderTopColor = 'black';
		this.bottomLeftDragger.style.borderTopStyle = 'solid';
		this.bottomLeftDragger.style.borderTopWidth = '1px';
		this.bottomLeftDragger.style.borderRightColor = 'black';
		this.bottomLeftDragger.style.borderRightStyle = 'solid';
		this.bottomLeftDragger.style.borderRightWidth = '1px';
		this.bottomLeftDragger.style.borderBottomColor = 'black';
		this.bottomLeftDragger.style.borderBottomStyle = 'solid';
		this.bottomLeftDragger.style.borderBottomWidth = '1px';
		this.bottomLeftDragger.style.position = field.style.position;
		//if (field.style.position=='fixed') this.bottomLeftDragger.style.position = 'fixed';
		this.bottomLeftDragger.style.left = left + 'px';
		this.bottomLeftDragger.style.top = bottom + 'px';
		this.bottomLeftDragger.style.cursor = 'sw-resize';
		this.bottomLeftDragger.style.zIndex = zIndex;
		this.bottomLeftDragger.setAttribute("onclick", "event.cancelBubble = true;return false;");
		this.bottomLeftDragger.style.display = 'none';			
		field.parentNode.appendChild(this.bottomLeftDragger);
	},

	initBottomRightDragger: function (field,left,right,top,bottom,w2,h2,zIndex){
		this.bottomRightDragger = document.createElement('div');
		this.bottomRightDragger.id = 'bottomRightDragger_' + this.id;
		this.bottomRightDragger.style.width = this.draggerWidth + 'px';
		this.bottomRightDragger.style.height = this.draggerHeight + 'px';
		this.bottomRightDragger.style.backgroundColor = 'white';
		this.bottomRightDragger.style.borderLeftColor = 'black';
		this.bottomRightDragger.style.borderLeftStyle = 'solid';
		this.bottomRightDragger.style.borderLeftWidth = '1px';
		this.bottomRightDragger.style.borderTopColor = 'black';
		this.bottomRightDragger.style.borderTopStyle = 'solid';
		this.bottomRightDragger.style.borderTopWidth = '1px';
		this.bottomRightDragger.style.borderRightColor = 'black';
		this.bottomRightDragger.style.borderRightStyle = 'solid';
		this.bottomRightDragger.style.borderRightWidth = '1px';
		this.bottomRightDragger.style.borderBottomColor = 'black';
		this.bottomRightDragger.style.borderBottomStyle = 'solid';
		this.bottomRightDragger.style.borderBottomWidth = '1px';
		this.bottomRightDragger.style.position = field.style.position;
		//if (field.style.position=='fixed') this.bottomRightDragger.style.position = 'fixed';	
		this.bottomRightDragger.style.left = right + 'px';
		this.bottomRightDragger.style.top = bottom + 'px';
		this.bottomRightDragger.style.cursor = 'se-resize';
		this.bottomRightDragger.style.zIndex = zIndex;
		this.bottomRightDragger.setAttribute("onclick", "event.cancelBubble = true;return false;");
		this.bottomRightDragger.style.display = 'none';	
		field.parentNode.appendChild(this.bottomRightDragger);
	},

	initBottomDragger: function (field,left,right,top,bottom,w2,h2,zIndex){
		this.bottomDragger = document.createElement('div');
		this.bottomDragger.id = 'bottomDragger_' + this.id;
		this.bottomDragger.style.width = this.draggerWidth + 'px';
		this.bottomDragger.style.height = this.draggerHeight + 'px';
		this.bottomDragger.style.backgroundColor = 'white';
		this.bottomDragger.style.borderLeftColor = 'black';
		this.bottomDragger.style.borderLeftStyle = 'solid';
		this.bottomDragger.style.borderLeftWidth = '1px';
		this.bottomDragger.style.borderTopColor = 'black';
		this.bottomDragger.style.borderTopStyle = 'solid';
		this.bottomDragger.style.borderTopWidth = '1px';
		this.bottomDragger.style.borderRightColor = 'black';
		this.bottomDragger.style.borderRightStyle = 'solid';
		this.bottomDragger.style.borderRightWidth = '1px';
		this.bottomDragger.style.borderBottomColor = 'black';
		this.bottomDragger.style.borderBottomStyle = 'solid';
		this.bottomDragger.style.borderBottomWidth = '1px';
		this.bottomDragger.style.position = field.style.position;
		//if (field.style.position=='fixed') this.bottomDragger.style.position = 'fixed';
		this.bottomDragger.style.left = (left + w2) + 'px';
		this.bottomDragger.style.top = bottom + 'px';
		this.bottomDragger.style.cursor = 's-resize';
		this.bottomDragger.style.zIndex = zIndex;
		this.bottomDragger.setAttribute("onclick", "event.cancelBubble = true;return false;");
		this.bottomDragger.style.display = 'none';
		field.parentNode.appendChild(this.bottomDragger);
	},

	initLeftDragger: function (field,left,right,top,bottom,w2,h2,zIndex){
		this.leftDragger = document.createElement('div');
		this.leftDragger.id = 'leftDragger_' + this.id;
		this.leftDragger.style.width = this.draggerWidth + 'px';
		this.leftDragger.style.height = this.draggerHeight + 'px';
		this.leftDragger.style.backgroundColor = 'white';
		this.leftDragger.style.borderLeftColor = 'black';
		this.leftDragger.style.borderLeftStyle = 'solid';
		this.leftDragger.style.borderLeftWidth = '1px';
		this.leftDragger.style.borderTopColor = 'black';
		this.leftDragger.style.borderTopStyle = 'solid';
		this.leftDragger.style.borderTopWidth = '1px';
		this.leftDragger.style.borderRightColor = 'black';
		this.leftDragger.style.borderRightStyle = 'solid';
		this.leftDragger.style.borderRightWidth = '1px';
		this.leftDragger.style.borderBottomColor = 'black';
		this.leftDragger.style.borderBottomStyle = 'solid';
		this.leftDragger.style.borderBottomWidth = '1px';
		this.leftDragger.style.position = field.style.position;
		//if (field.style.position=='fixed') this.leftDragger.style.position = 'fixed';
		this.leftDragger.style.left = left + 'px';
		this.leftDragger.style.top = (top + h2) + 'px';
		this.leftDragger.style.cursor = 'w-resize';
		this.leftDragger.style.zIndex = zIndex;
		this.leftDragger.setAttribute("onclick", "event.cancelBubble = true;return false;");
		this.leftDragger.style.display = 'none';
		field.parentNode.appendChild(this.leftDragger);
	},

	initRightDragger: function (field,left,right,top,bottom,w2,h2,zIndex){
		this.rightDragger = document.createElement('div');
		this.rightDragger.id = 'rightDragger_' + this.id;
		this.rightDragger.style.width = this.draggerWidth + 'px';
		this.rightDragger.style.height = this.draggerHeight + 'px';
		this.rightDragger.style.backgroundColor = 'white';
		this.rightDragger.style.borderLeftColor = 'black';
		this.rightDragger.style.borderLeftStyle = 'solid';
		this.rightDragger.style.borderLeftWidth = '1px';
		this.rightDragger.style.borderTopColor = 'black';
		this.rightDragger.style.borderTopStyle = 'solid';
		this.rightDragger.style.borderTopWidth = '1px';
		this.rightDragger.style.borderRightColor = 'black';
		this.rightDragger.style.borderRightStyle = 'solid';
		this.rightDragger.style.borderRightWidth = '1px';
		this.rightDragger.style.borderBottomColor = 'black';
		this.rightDragger.style.borderBottomStyle = 'solid';
		this.rightDragger.style.borderBottomWidth = '1px';
		this.rightDragger.style.position = field.style.position;
		//if (field.style.position=='fixed') this.rightDragger.style.position = 'fixed';
		this.rightDragger.style.left = right + 'px';
		this.rightDragger.style.top = (top + h2) + 'px';
		this.rightDragger.style.cursor = 'e-resize';
		this.rightDragger.style.zIndex = zIndex;
		this.rightDragger.setAttribute("onclick", "event.cancelBubble = true;return false;");
		this.rightDragger.style.display = 'none';		
		field.parentNode.appendChild(this.rightDragger);
	},
	
	createDraggers: function(){
		
		//console.log('createDraggers');
		
		var field = $(this.id);
		var id = this.id;
		
		if (!field) return;
		
		var left = field.offsetLeft;
		var top = field.offsetTop;
		var width = field.offsetWidth;
		var height = field.offsetHeight;
		
		if ((!width) || (!height)) {
			var obj = this;
			setTimeout(obj.update.bind(obj),1000);
		}
		
		if ((!width) || (width==0)){
			width = 100;
		}

		if ((!height) || (height==0)){
			height = 100;
		}
		
		var w2 = (width/2);
		var h2 = (height/2);
		
		this.draggerWidth2 = (this.draggerWidth/2);
		this.draggerHeight2 = (this.draggerHeight/2);
		
		var dw2 = (this.draggerWidth/2);
		var dh2 = (this.draggerHeight/2);
		var zIndex = field.style.zIndex;
		if (!zIndex){
			zIndex = this.zIndex;
		}
		
		top = top - (this.draggerHeight/2);
		left = left - (this.draggerWidth/2);
		right = left + width;
		bottom = top + height;

		this.container = document.createElement('div');
		this.container.id = 'container_' + this.id;

		this.container.style.position = field.style.position;
		if (field.style.position=='fixed') this.container.style.position = 'fixed';
		
		var centered = (field.getAttribute('anchorLeft')=='center');
		var centeredV = (field.getAttribute('anchorTop')=='center');
			
		this.adjustContainerToNode(field);
		
		this.container.style.width = width + 'px';
		this.container.style.height = height + 'px';
		this.container.style.cursor = 'default';
		this.container.style.zIndex = zIndex;
		this.container.style.opacity = '0.5';
		this.container.style.borderLeftColor = 'black';
		this.container.style.borderLeftStyle = 'none';
		this.container.style.borderLeftWidth = '1px';
		this.container.style.borderTopColor = 'black';
		this.container.style.borderTopStyle = 'none';
		this.container.style.borderTopWidth = '1px';
		this.container.style.borderRightColor = 'black';
		this.container.style.borderRightStyle = 'none';
		this.container.style.borderRightWidth = '1px';
		this.container.style.borderBottomColor = 'black';
		this.container.style.borderBottomStyle = 'none';
		this.container.style.borderBottomWidth = '1px';
		this.container.style.position = field.style.position;
		field.parentNode.appendChild(this.container);
			
		this.containerMouseover = function(event){ if ($('container_' + id)) $('container_' + id).style.backgroundColor = 'grey'; };
		this.containerMouseout = function(event){ if ($('container_' + id)) $('container_' + id).style.backgroundColor = 'transparent'; };
		
		this.enableMouseOver();
		
		document.observe('ws:zIndex_changed',function(event){ if (resizerManager.getResizer(event.memo.fieldId)){ resizerManager.getResizer(event.memo.fieldId).updateZIndex(); } });
		
		this.container.setAttribute("onclick", "event.cancelBubble = true;return false;");
		this.container.setAttribute("onmouseover", "event.cancelBubble = true;return false;");
		this.container.setAttribute("onmouseout", "event.cancelBubble = true;return false;");
		
		//Element.observe(this.container,'mousedown',function(event){ resizerManager.getResizer(id).saveMousePosition(event); });
		//Element.observe(this.container,'mouseup',function(event){ if (!resizerManager.getResizer(id).mouseMoved(event)) { resizerManager.getResizer(id).clickEvent(); } });
		
		var resizer = resizerManager.getResizer(this.id);
		
		Element.observe(this.container,'mousedown',function(event){ resizer.hideHandles(); });
		Element.observe(this.container,'mouseup',function(event){ resizer.showHandles(); });
		
		Element.observe(this.container,'click',function(event){ resizer.clickEvent(); });
		Element.observe(this.container,'dblclick',function(event){ resizer.dblClickEvent(); });
		
			Event.observe(document,'keydown',function(event){ 
				// if (event.keyCode==27) { // Esc
				// 	pageDesigner.clearSelection(); 
				// }
				
				if (!resizerManager.getResizer(id) || !resizerManager.getResizer(id).selected()){
					return;
				}
				
				if (event.keyCode==37){ // Left Arrow
					//alert('left');
					if (event.shiftKey){
						resizerManager.getResizer(id).addCommand('fastleft',resizerManager.getResizer(id).moveLeftFast,resizerManager.getResizer(id).moveRightFast);
						
						//resizerManager.getResizer(id).moveLeftFast();
						//pageDesigner.moveLeftFast();
					}
					else {
						//pageDesigner.moveLeft();
						resizerManager.getResizer(id).addCommand('left',resizerManager.getResizer(id).moveLeft,resizerManager.getResizer(id).moveRight);
						
						//resizerManager.getResizer(id).moveLeft();
					}

				}
				else if (event.keyCode==38){ // Up Arrow
					//alert('up');
					if (event.shiftKey){
						resizerManager.getResizer(id).addCommand('fastup',resizerManager.getResizer(id).moveUpFast,resizerManager.getResizer(id).moveDownFast);
						//resizerManager.getResizer(id).moveUpFast();
					}
					else {
						resizerManager.getResizer(id).addCommand('up',resizerManager.getResizer(id).moveUp,resizerManager.getResizer(id).moveDown);
						//resizerManager.getResizer(id).moveUp();
					}
				}
				else if (event.keyCode==39){ // Right Arrow
					//alert('right');
					if (event.shiftKey){
						//resizerManager.getResizer(id).moveRightFast();	
						resizerManager.getResizer(id).addCommand('fastright',resizerManager.getResizer(id).moveRightFast,resizerManager.getResizer(id).moveLeftFast);
					}
					else {
						resizerManager.getResizer(id).addCommand('right',resizerManager.getResizer(id).moveRight,resizerManager.getResizer(id).moveLeft);
						//resizerManager.getResizer(id).moveRight();
					}
				}
				else if (event.keyCode==40){ // Down Arrow
					//alert('down');
					if (event.shiftKey){
						resizerManager.getResizer(id).addCommand('fastdown',resizerManager.getResizer(id).moveDownFast,resizerManager.getResizer(id).moveUpFast);
						//resizerManager.getResizer(id).moveDownFast();
					}
					else {
						//resizerManager.getResizer(id).moveDown();
						resizerManager.getResizer(id).addCommand('down',resizerManager.getResizer(id).moveDown,resizerManager.getResizer(id).moveUp);
					}
				}
			});
				
		zIndex = parseInt(zIndex) + 10;
		
		if (!centeredV){
			if (!centered){
				this.initTopDragger(field,left,right,top,bottom,w2,h2,zIndex);
				this.initTopLeftDragger(field,left,right,top,bottom,w2,h2,zIndex);
				this.initTopRightDragger(field,left,right,top,bottom,w2,h2,zIndex);
				this.initBottomLeftDragger(field,left,right,top,bottom,w2,h2,zIndex);
				this.initBottomRightDragger(field,left,right,top,bottom,w2,h2,zIndex);
				this.initBottomDragger(field,left,right,top,bottom,w2,h2,zIndex);
				this.initLeftDragger(field,left,right,top,bottom,w2,h2,zIndex);
				this.initRightDragger(field,left,right,top,bottom,w2,h2,zIndex);
				
			}
			else {
				this.initTopDragger(field,left,right,top,bottom,w2,h2,zIndex);
				this.initBottomDragger(field,left,right,top,bottom,w2,h2,zIndex);
			}
		}
		else {
			if (!centered){
				this.initLeftDragger(field,left,right,top,bottom,w2,h2,zIndex);
				this.initRightDragger(field,left,right,top,bottom,w2,h2,zIndex);
			}
		}

		//console.log('draggers created');

		this.handlesVisible = false;
		//this.hideHandles();

		var w = this.draggerWidth;
		var h = this.draggerHeight;
		var w2 = w/2;
		var h2 = h/2;
		
		var container = this.container;
		var field = $(id);
		var dragObserver = this.dragObserver;
		
		var resizer = this;
		
		var containerStartDrag = function(){
			
				if (field.getAttribute('anchorLeft')=='right'){
					container.style.left = pb.core.cssUtils.calculateLeftPosFromRight(container);
					container.style.right = '';
				}
			
				if (field.getAttribute('anchorTop')=='bottom'){ 
					container.style.top = pb.core.cssUtils.calculateTopPosFromBottom(container);
					container.style.bottom = '';
				}
				
				if (field.getAttribute('anchorLeft')=='center'){
					container.style.left = field.style.left;
					container.style.marginLeft = field.style.marginLeft;
				}
								
				//resizerManager.getResizer(id).adjustNodeForDragging(field);
								
				resizer.oldLeft = field.style.left;
				resizer.oldTop = field.style.top;
				
				resizer.startDragEvent();
				
				dragObserver = new ValueObserver('container',0.02,function (){
					//console.log('drag observer. containerleft ' + container.offsetLeft);
					
					if (container.offsetLeft) field.style.left = (container.offsetLeft-pb.core.cssUtils.getMarginLeft(field)) + 'px';
					if (container.offsetTop) field.style.top = (container.offsetTop-pb.core.cssUtils.getMarginTop(field)) + 'px';

					
					// if (!field.getAttribute('anchorLeft') || (field.getAttribute('anchorLeft')=='left')){  // Anclar a izquierda
					// 						if (container.offsetLeft) field.style.left = container.offsetLeft + 'px';
					// 						else {
					// 							field.style.left = pb.core.cssUtils.calculateLeftPosFromRight(field);
					// 							field.style.right = '';
					// 						}
					// 					}
					// 					else if (field.getAttribute('anchorLeft')=='right') {  // Anclar a derecha
					// 						field.style.right = pb.core.cssUtils.calculateRightPosFromLeft(field);
					// 		d				field.style.left = '';
					// 					}
					// 					else { // Anclar a izquierda y a derecha
					// 						if (container.offsetLeft) field.style.left = container.offsetLeft + 'px';
					// 						field.style.right = pb.core.cssUtils.calculateRightPosFromLeft(field);
					// 						field.style.width = '';
					// 					}
					// 
					// 
					// 					if (!field.getAttribute('anchorTop') || field.getAttribute('anchorTop')=='top'){  // Anclar arriba
					// 						if (container.offsetTop) field.style.top = container.offsetTop + 'px';
					// 						else {
					// 							field.style.top = pb.core.cssUtils.calculateTopPosFromBottom(field);
					// 							field.style.bottom = '';
					// 						}
					// 					}
					// 					else if (field.getAttribute('anchorTop')=='bottom') {  // Anclar abajo
					// 						field.style.bottom = pb.core.cssUtils.calculateBottomPosFromTop(field);
					// 						field.style.top = '';
					// 					}
					// 					else { // Anclar a izquierda y a derecha
					// 						
					// 						field.style.height = '';
					// 					}
					
					//resizerManager.getResizer(id).startDragEvent();
					resizer.dragEvent();
				 });
			};
		

		var containerDrag = function(){
							// field.style.left = (container.offsetLeft) + 'px';
							// 							field.style.top = (container.offsetTop) + 'px';
							
							//resizerManager.getResizer(id).update();
							//resizerManager.getResizer(id).showHandles();
							//document.fire('ws:block_moved',{ fieldId: id });
							// resizerManager.getResizer(id).dragEvent();
							dragObserver.currentValue = container.offsetTop + " " + container.offsetLeft;
						};
						
		var containerDragEnd = function(){

							// field.style.left = container.offsetLeft + 'px';
							// field.style.top = container.offsetTop + 'px';
							
							if (field.getAttribute('anchorLeft')!='center'){
								field.style.marginLeft = '';
							}
							
							if (field.getAttribute('anchorTop')!='center'){
								field.style.marginTop = '';
							}
							
							if ((field.getAttribute('anchorLeft')=='both')){  // Anclar a izquierda y derecha
								if (container.offsetLeft) field.style.left = container.offsetLeft + 'px';
								field.style.right = pb.core.cssUtils.calculateRightPosFromLeft(container);
								field.style.width = '';
							}
							else if (field.getAttribute('anchorLeft')=='right') {  // Anclar a derecha
								field.style.right = pb.core.cssUtils.calculateRightPosFromLeft(container);
								field.style.left = '';
							}
							else if (field.getAttribute('anchorLeft')=='center') {  // Anclar al centro
								field.style.left = '50%';
							}
							else { // Anclar a izquierda
								if (container.offsetLeft) field.style.left = container.offsetLeft + 'px';
								else {
									field.style.left = pb.core.cssUtils.calculateLeftPosFromRight(container);
									field.style.right = '';
								}
							}


							if ((field.getAttribute('anchorTop')=='both')){  // Anclar a izquierda y derecha
								if (container.offsetTop) field.style.top = container.offsetTop + 'px';
								field.style.bottom = pb.core.cssUtils.calculateBottomPosFromTop(container);
								field.style.height = '';
							}
							else if (field.getAttribute('anchorTop')=='bottom') {  // Anclar a derecha
								field.style.bottom = pb.core.cssUtils.calculateBottomPosFromTop(container);
								field.style.top = '';
							}
							else if (field.getAttribute('anchorTop')=='center') {  // Anclar al centro
								field.style.top = '50%';
							}
							else { // Anclar a izquierda
								if (container.offsetTop) field.style.top = container.offsetTop + 'px';
								else {
									field.style.top = pb.core.cssUtils.calculateTopPosFromBottom(container);
									field.style.bottom = '';
								}
							}

							if (resizer.undoManager){
								var newLeft = parseInt($('container_' + id).offsetLeft) + 'px';
								var newTop = parseInt($('container_' + id).offsetTop) + 'px';
							
								var callback = function () {
									field.style.left = newLeft;
									field.style.top = newTop;
									resizer.update();
								};
								
								var oldLeft = resizer.oldLeft;
								var oldTop = resizer.oldTop;
								
								var oldCallback = function(){
									field.style.left = oldLeft;
									field.style.top = oldTop;
									resizer.update();
								};
								resizer.undoManager.appendCommand(new CallbackCommand('drag',callback,oldCallback));
							}

							//document.fire('ws:css_changed',{ fieldId: id });
							resizer.update();
							resizer.endDragEvent();
							document.fire('ws:block_css_changed',{ id: id });
						};

		var constraint = null;
		var disabled = false;
		if (centered) {
			if (centeredV){
				disabled = true;
			}
			else {
				constraint = 'vertical';
			}
		}
		else {
			if (centeredV){
				constraint = 'horizontal';				
			}
		}
		
		if (!disabled) this.containerDraggable = new Draggable(this.container,{ onStart: containerStartDrag, onDrag: containerDrag, onEnd: containerDragEnd, scroll: window, constraint: constraint });

			//var field = $(id);
		if (!centered){
			var topLeftStartDrag = function(){

					resizer.prepareForDragging();

					resizer.oldHandleLeft = field.style.left;
					resizer.oldHandleTop = field.style.top;
					resizer.oldHandleWidth = pb.core.cssUtils.getWidth(field) + 'px';
					resizer.oldHandleHeight = pb.core.cssUtils.getHeight(field) + 'px';
					if (resizer.startResizeCallback) resizer.startResizeCallback();
				};
							
			var topLeftDrag = function(){

					var paddingLeft = parseInt(field.style.paddingLeft);
					if (isNaN(paddingLeft)) paddingLeft = 0;
					var paddingRight = parseInt(field.style.paddingRight);
					if (isNaN(paddingRight)) paddingRight = 0;
					var paddingTop = parseInt(field.style.paddingTop);
					if (isNaN(paddingTop)) paddingTop = 0;
					var paddingBottom = parseInt(field.style.paddingBottom);
					if (isNaN(paddingBottom)) paddingBottom = 0;

					var oldLeft = parseInt(field.offsetLeft);
					var oldTop = parseInt(field.offsetTop);

					field.style.left = (parseInt($('topLeftDragger_'+id).style.left) + w2) + 'px';
					field.style.top = (parseInt($('topLeftDragger_'+id).style.top) + h2) + 'px';
											
					field.style.width = (parseInt(field.offsetWidth) - paddingLeft - paddingRight + (oldLeft-parseInt(field.style.left))) + 'px';								
					field.style.height = (parseInt(field.offsetHeight) - paddingTop - paddingBottom + (oldTop-parseInt(field.style.top))) + 'px';								

					resizer.update(true);
				};
							
			var topLeftDragEnd = function(){
				topLeftDrag();
			
				resizer.prepareForStopDragging();
			
				if (resizer.undoManager){
					var oldLeft = resizer.oldHandleLeft;
					var oldTop = resizer.oldHandleTop;
					var oldWidth = resizer.oldHandleWidth;
					var oldHeight = resizer.oldHandleHeight;
				
					var newLeft = field.style.left;
					var newTop = field.style.top;
					var newWidth = field.style.width;
	                var newHeight = field.style.height;

					var callback = function () {
						field.style.left = newLeft;
						field.style.top = newTop;
						field.style.width = newWidth;
						field.style.height = newHeight;
						resizer.update();
					};

					var oldCallback = function(){
						field.style.left = oldLeft;
						field.style.top = oldTop;
						field.style.width = oldWidth;
						field.style.height = oldHeight;
						resizer.update();									
					};
					resizer.undoManager.appendCommand(new CallbackCommand('drag',callback,oldCallback));			
				}
				resizer.update();
				if (resizer.resizeCallback) resizer.resizeCallback();
				document.fire('ws:block_resized',{id:id});
				document.fire('ws:block_css_changed',{ id: id });
			};
		}

		
		var topStartDrag = function(){
				resizer.prepareForDragging();
			
				resizer.oldHandleTop = field.offsetTop;
				resizer.oldHandleHeight = field.offsetHeight;
				if (resizer.startResizeCallback) resizer.startResizeCallback();
			};
							
		var topDrag = function(){

				var paddingTop = parseInt(field.style.paddingTop);
				if (isNaN(paddingTop)) paddingTop = 0;
				var paddingBottom = parseInt(field.style.paddingBottom);
				if (isNaN(paddingBottom)) paddingBottom = 0;

				var oldTop = parseInt(field.offsetTop);
				field.style.top = (parseInt($('topDragger_'+id).offsetTop) + h2) + 'px';
				field.style.height = (parseInt(field.offsetHeight) - paddingTop - paddingBottom + (oldTop-parseInt(field.offsetTop))) + 'px';
				resizer.update(true);
			};
							
		var topDragEnd = function(){
				topDrag();
			
				resizer.prepareForStopDragging();
				
				if (resizer.undoManager){
					var oldTop = resizer.oldHandleTop;
					var oldHeight = resizer.oldHandleHeight;
				
					var newTop = field.offsetTop;
	                var newHeight = field.offsetHeight;

					var callback = function () {
						field.style.top = newTop;
						field.style.height = newHeight;
						resizer.update();
					};

					var oldCallback = function(){
						field.style.top = oldTop;
						field.style.height = oldHeight;
						resizer.update();									
					};
					resizer.undoManager.appendCommand(new CallbackCommand('drag',callback,oldCallback));
				}
				resizer.update();
				if (resizer.resizeCallback) resizer.resizeCallback();
				document.fire('ws:block_resized',{id:id});
				document.fire('ws:block_css_changed',{ id: id });
			};

		if (!centered){
			var topRightStartDrag = function(){
				
					resizer.prepareForDragging();
				
					resizer.oldHandleLeft = field.offsetLeft;
					resizer.oldHandleTop = field.offsetTop;
					resizer.oldHandleWidth = field.offsetWidth;
					resizer.oldHandleHeight = field.offsetHeight;
				
					if (resizer.startResizeCallback) resizer.startResizeCallback();
				};
							
			var topRightDrag = function(){

					var paddingLeft = parseInt(field.style.paddingLeft);
					if (isNaN(paddingLeft)) paddingLeft = 0;
					var paddingRight = parseInt(field.style.paddingRight);
					if (isNaN(paddingRight)) paddingRight = 0;
					var paddingTop = parseInt(field.style.paddingTop);
					if (isNaN(paddingTop)) paddingTop = 0;
					var paddingBottom = parseInt(field.style.paddingBottom);
					if (isNaN(paddingBottom)) paddingBottom = 0;

					var oldRight = parseInt(field.offsetLeft) + parseInt(field.offsetWidth);
					var oldTop = parseInt(field.offsetTop);
					field.style.top = (parseInt($('topRightDragger_'+id).offsetTop) + h2) + 'px';
					field.style.width = (parseInt(field.offsetWidth) - paddingLeft - paddingRight + (parseInt($('topRightDragger_'+id).offsetLeft)-oldRight)) + 'px';
					// field.style.width = (parseInt(field.offsetWidth) + (oldLeft-parseInt(field.style.left))) + 'px';
					field.style.height = (parseInt(field.offsetHeight) - paddingTop - paddingBottom + (oldTop-parseInt(field.offsetTop))) + 'px';
					resizer.update(true);
				};
							
			var topRightDragEnd = function(){
							topRightDrag();
					
							resizer.prepareForStopDragging();
				
							if (resizer.undoManager){
								var oldLeft = resizer.oldHandleLeft;
								var oldTop = resizer.oldHandleTop;
								var oldWidth = resizer.oldHandleWidth;
								var oldHeight = resizer.oldHandleHeight;

								var newLeft = field.offsetLeft;
								var newTop = field.offsetTop;
								var newWidth = field.offsetWidth;
				                var newHeight = field.offsetHeight;

								var callback = function () {
									field.style.left = newLeft;
									field.style.top = newTop;
									field.style.width = newWidth;
									field.style.height = newHeight;
									resizer.update(true);
								};

								var oldCallback = function(){
									field.style.left = oldLeft;
									field.style.top = oldTop;
									field.style.width = oldWidth;
									field.style.height = oldHeight;
									resizer.update(true);									
								};
								resizer.undoManager.appendCommand(new CallbackCommand('drag',callback,oldCallback));
							}
							resizer.update();
							if (resizer.resizeCallback) resizer.resizeCallback();
							document.fire('ws:block_resized',{id:id});
							document.fire('ws:block_css_changed',{ id: id });
						};
					
			var leftStartDrag = function(){
					resizer.prepareForDragging();
					resizer.oldHandleLeft = field.offsetLeft;
					resizer.oldHandleWidth = field.offsetWidth;
					if (resizer.startResizeCallback) resizer.startResizeCallback();
				};
							
			var leftDrag = function(){

									var paddingLeft = parseInt(field.style.paddingLeft);
									if (isNaN(paddingLeft)) paddingLeft = 0;
									var paddingRight = parseInt(field.style.paddingRight);
									if (isNaN(paddingRight)) paddingRight = 0;
								
									var oldLeft = parseInt(field.offsetLeft);
									field.style.left = (parseInt($('leftDragger_'+id).offsetLeft) + w2) + 'px';
									field.style.width = (parseInt(field.offsetWidth) - paddingLeft - paddingRight + (oldLeft-parseInt(field.offsetLeft))) + 'px';
									resizer.update(true);
								};
							
			var leftDragEnd = function(){
							leftDrag();
							resizer.prepareForStopDragging();
							if (resizer.undoManager){
								var oldLeft = resizer.oldHandleLeft;
								var oldWidth = resizer.oldHandleWidth;

								var newLeft = field.offsetLeft;
								var newWidth = field.offsetWidth;

								var callback = function () {
									field.style.left = newLeft;
									field.style.width = newWidth;
									resizer.update(true);
								};

								var oldCallback = function(){
									field.style.left = oldLeft;
									field.style.width = oldWidth;
									resizer.update(true);									
								};
								resizer.undoManager.appendCommand(new CallbackCommand('drag',callback,oldCallback));
							}
							resizer.update();
							if (resizer.resizeCallback) resizer.resizeCallback();
							document.fire('ws:block_resized',{id:id});
							document.fire('ws:block_css_changed',{ id: this.id });
						};
					
			var rightStartDrag = function(){
					resizer.prepareForDragging();
					resizer.oldHandleLeft = field.offsetLeft;
					resizer.oldHandleWidth = field.offsetWidth;
					if (resizer.startResizeCallback) resizer.startResizeCallback();
				};
							
			var rightDrag = function(){

									var paddingLeft = parseInt(field.style.paddingLeft);
									if (isNaN(paddingLeft)) paddingLeft = 0;
									var paddingRight = parseInt(field.style.paddingRight);
									if (isNaN(paddingRight)) paddingRight = 0;
			
									var oldRight = parseInt(field.offsetLeft) + parseInt(field.offsetWidth);
									field.style.width = (parseInt(field.offsetWidth) - paddingLeft - paddingRight + (parseInt($('rightDragger_'+id).offsetLeft)-oldRight)) + 'px';
									resizer.update(true);
								};
							
							
			var rightDragEnd = function(){
					rightDrag();
					resizer.prepareForStopDragging();
					if (resizer.undoManager){
						var oldLeft = resizer.oldHandleLeft;
						var oldWidth = resizer.oldHandleWidth;

						var newLeft = field.offsetLeft;
						var newWidth = field.offsetWidth;

						var callback = function () {
							field.style.left = newLeft;
							field.style.width = newWidth;
							resizer.update();
						};

						var oldCallback = function(){
							field.style.left = oldLeft;
							field.style.width = oldWidth;
							resizer.update();									
						};
						resizer.undoManager.appendCommand(new CallbackCommand('drag',callback,oldCallback));
					}
					resizer.update();
					if (resizer.resizeCallback) resizer.resizeCallback();
					document.fire('ws:block_resized',{id:id});
					document.fire('ws:block_css_changed',{ id: id });
				};
			
			
			var bottomLeftStartDrag = function(){
					resizer.prepareForDragging();
					resizer.oldHandleLeft = field.offsetLeft;
					resizer.oldHandleTop = field.offsetTop;
					resizer.oldHandleWidth = field.offsetWidth;
					resizer.oldHandleHeight = field.offsetHeight;
					if (resizer.startResizeCallback) resizer.startResizeCallback();
				};
														
			var bottomLeftDrag = function(){

									var paddingLeft = parseInt(field.style.paddingLeft);
									if (isNaN(paddingLeft)) paddingLeft = 0;
									var paddingRight = parseInt(field.style.paddingRight);
									if (isNaN(paddingRight)) paddingRight = 0;
									var paddingTop = parseInt(field.style.paddingTop);
									if (isNaN(paddingTop)) paddingTop = 0;
									var paddingBottom = parseInt(field.style.paddingBottom);
									if (isNaN(paddingBottom)) paddingBottom = 0;
								
									var oldLeft = parseInt(field.offsetLeft);
									// var oldTop = parseInt(field.style.top);
									var oldBottom = parseInt(field.offsetTop) + parseInt(field.offsetHeight);
									field.style.left = (parseInt($('bottomLeftDragger_'+id).offsetLeft) + w2) + 'px';
									field.style.width = (parseInt(field.offsetWidth) - paddingLeft - paddingRight + (oldLeft-parseInt(field.offsetLeft))) + 'px';
									field.style.height = (parseInt(field.offsetHeight) - paddingTop - paddingBottom + (parseInt($('bottomLeftDragger_'+id).offsetTop+h2)-oldBottom)) + 'px';
									resizer.update(true);
								};
						
			var bottomLeftDragEnd = function(){
						bottomLeftDrag();
						resizer.prepareForStopDragging();
						if (resizer.undoManager){
							var oldLeft = resizer.oldHandleLeft;
							var oldTop = resizer.oldHandleTop;
							var oldWidth = resizer.oldHandleWidth;
							var oldHeight = resizer.oldHandleHeight;

							var newLeft = field.offsetLeft;
							var newTop = field.offsetTop;
							var newWidth = field.offsetWidth;
			                var newHeight = field.offsetHeight;

							var callback = function () {
								field.style.left = newLeft;
								field.style.top = newTop;
								field.style.width = newWidth;
								field.style.height = newHeight;
								resizer.update();
							};

							var oldCallback = function(){
								field.style.left = oldLeft;
								field.style.top = oldTop;
								field.style.width = oldWidth;
								field.style.height = oldHeight;
								resizer.update();									
							};
							resizer.undoManager.appendCommand(new CallbackCommand('drag',callback,oldCallback));
						}
						resizer.update();
						if (resizer.resizeCallback) resizer.resizeCallback();
						document.fire('ws:block_resized',{id:id});
						document.fire('ws:block_css_changed',{ id: id });
					};
			
			var bottomStartDrag = function(){
				resizer.prepareForDragging();
				resizer.oldHandleTop = field.offsetTop;
				resizer.oldHandleHeight = field.offsetHeight;
				if (resizer.startResizeCallback) resizer.startResizeCallback();
			};	
		}

							
		var bottomDrag = function(){
			
						var paddingTop = parseInt(field.style.paddingTop);
						if (isNaN(paddingTop)) paddingTop = 0;
						var paddingBottom = parseInt(field.style.paddingBottom);
						if (isNaN(paddingBottom)) paddingBottom = 0;
					
						var oldBottom = (field.offsetTop) + field.offsetHeight;
										
						field.style.height = (parseInt(field.offsetHeight) - paddingTop - paddingBottom + (parseInt($('bottomDragger_'+id).offsetTop+h2)-oldBottom)) + 'px';
						resizer.update(true);			

						};
					
		var bottomDragEnd = function(){
			bottomDrag();
			resizer.prepareForStopDragging();
			if (resizer.undoManager){
				var oldTop = resizer.oldHandleTop;
				var oldHeight = resizer.oldHandleHeight;

				var newTop = field.offsetTop;
                var newHeight = field.offsetHeight;

				var callback = function () {
					field.style.top = newTop;
					field.style.height = newHeight;
					resizer.update();
				};

				var oldCallback = function(){
					field.style.top = oldTop;
					field.style.height = oldHeight;
					resizer.update();									
				};
				resizer.undoManager.appendCommand(new CallbackCommand('drag',callback,oldCallback));
			}
			resizer.update();
			if (resizer.resizeCallback) resizer.resizeCallback();
			document.fire('ws:block_resized',{id:id});
			document.fire('ws:block_css_changed',{ id: id });
		};
		
		if (!centered){
			var bottomRightStartDrag = function(){
					resizer.prepareForDragging();
					resizer.oldHandleLeft = field.offsetLeft;
					resizer.oldHandleTop = field.offsetTop;
					resizer.oldHandleWidth = field.offsetWidth + 'px';
					resizer.oldHandleHeight = field.offsetHeight + 'px';
					if (resizer.startResizeCallback) resizer.startResizeCallback();
				};
		
			var bottomRightDrag = function(){

								var paddingLeft = parseInt(field.style.paddingLeft);
								if (isNaN(paddingLeft)) paddingLeft = 0;
								var paddingRight = parseInt(field.style.paddingRight);
								if (isNaN(paddingRight)) paddingRight = 0;
								var paddingTop = parseInt(field.style.paddingTop);
								if (isNaN(paddingTop)) paddingTop = 0;
								var paddingBottom = parseInt(field.style.paddingBottom);
								if (isNaN(paddingBottom)) paddingBottom = 0;
							
								var oldBottom = (field.offsetTop) + field.offsetHeight;
								var oldRight = (field.offsetLeft) + field.offsetWidth;
							
								// alert('bottom ' + oldBottom);
								// alert('right ' + oldRight);
							
								field.style.width = (parseInt(field.offsetWidth)- paddingLeft - paddingRight + (parseInt($('bottomRightDragger_'+id).offsetLeft)-oldRight)) + 'px';
								field.style.height = (parseInt(field.offsetHeight) - paddingTop - paddingBottom + (parseInt($('bottomRightDragger_'+id).offsetTop+h2)-oldBottom)) + 'px';
								resizer.update(true);
							};
						
			var bottomRightDragEnd = function(){
				bottomRightDrag();
				resizer.prepareForStopDragging();
				if (resizer.undoManager){
					var oldLeft = resizer.oldHandleLeft;
					var oldTop = resizer.oldHandleTop;
					var oldWidth = resizer.oldHandleWidth;
					var oldHeight = resizer.oldHandleHeight;

					var newLeft = field.offsetLeft;
					var newTop = field.offsetTop;
					var newWidth = field.offsetWidth + 'px';
	                var newHeight = field.offsetHeight + 'px';

					var callback = function () {
						field.style.left = newLeft;
						field.style.top = newTop;
						field.style.width = newWidth;
						field.style.height = newHeight;
						resizer.update();
					};

					var oldCallback = function(){
						field.style.left = oldLeft;
						field.style.top = oldTop;
						field.style.width = oldWidth;
						field.style.height = oldHeight;
						resizer.update();									
					};
					resizer.undoManager.appendCommand(new CallbackCommand('drag',callback,oldCallback));
				}
				resizer.update();
				if (resizer.resizeCallback) resizer.resizeCallback();
				document.fire('ws:block_resized',{id:id});
				document.fire('ws:block_css_changed',{ id: id });
			};	
		}

		//console.log('updating resizer');
		this.update();
		
		if (this.topDragger) this.topDraggable = new Draggable(this.topDragger, { onStart: topStartDrag,onDrag: topDrag,onEnd: topDragEnd,constraint:'vertical' });
		if (this.bottomDragger) this.bottomDraggable = new Draggable(this.bottomDragger, { onStart: bottomStartDrag,onDrag: bottomDrag,onEnd: bottomDragEnd,constraint:'vertical' });
		

			if (this.topLeftDragger) this.topLeftDraggable = new Draggable(this.topLeftDragger, { onStart: topLeftStartDrag,onDrag: topLeftDrag,onEnd: topLeftDragEnd });
			
			if (this.topRightDragger) this.topRightDraggable = new Draggable(this.topRightDragger, { onStart: topRightStartDrag,onDrag: topRightDrag,onEnd: topRightDragEnd	});
			if (this.leftDragger) this.leftDraggable = new Draggable(this.leftDragger, { onStart: leftStartDrag,onDrag: leftDrag,onEnd: leftDragEnd,constraint:'horizontal' });
			if (this.rightDragger) this.rightDraggable = new Draggable(this.rightDragger, { onStart: rightStartDrag,onDrag: rightDrag,onEnd: rightDragEnd,constraint:'horizontal' });
			if (this.bottomLeftDragger) this.bottomLeftDraggable = new Draggable(this.bottomLeftDragger, { onStart: bottomLeftStartDrag,onDrag: bottomLeftDrag,onEnd: bottomLeftDragEnd	});
			if (this.bottomRightDragger) this.bottomRightDraggable = new Draggable(this.bottomRightDragger, { onStart: bottomRightStartDrag,onDrag: bottomRightDrag,onEnd: bottomRightDragEnd	});			
		//console.log('finished creating draggers');
	},	
	
	toggleHandles: function(){
		// Effect.toggle(this.topLeftDragger, 'appear',{ duration: 0 });
		// 		Effect.toggle(this.topDragger, 'appear',{ duration: 0 });
		// 		Effect.toggle(this.topRightDragger, 'appear',{ duration: 0 });
		// 		Effect.toggle(this.leftDragger, 'appear',{ duration: 0 });
		// 		Effect.toggle(this.rightDragger, 'appear',{ duration: 0 });
		// 		Effect.toggle(this.bottomLeftDragger, 'appear',{ duration: 0 });
		// 		Effect.toggle(this.bottomDragger, 'appear',{ duration: 0 });
		// 		Effect.toggle(this.bottomRightDragger, 'appear',{ duration: 0 });
		
		if (this.handlesVisible){
			this.hideHandles();
		}
		else {
			this.showHandles();
		}
	},
	
	enableHandles: function(){
		this.handlesDisabled = false;
	},
	
	disableHandles: function(){
		this.handlesDisabled = true;
		this.hideHandles();
	},
	
	showHandles: function(){
		
		//console.log('show handles');
		
		if (this.handlesDisabled) return;
		
		if (this.topDragger) this.topDragger.show();
		if (this.bottomDragger) this.bottomDragger.show();
		
		if (this.topLeftDragger) this.topLeftDragger.show();
		if (this.topRightDragger) this.topRightDragger.show();
		if (this.leftDragger) this.leftDragger.show();
		if (this.rightDragger) this.rightDragger.show();
		if (this.bottomLeftDragger) this.bottomLeftDragger.show();
		if (this.bottomRightDragger) this.bottomRightDragger.show();			
		
		if (this.container){
			this.container.style.borderLeftStyle = 'solid';
			this.container.style.borderTopStyle = 'solid';
			this.container.style.borderRightStyle = 'solid';
			this.container.style.borderBottomStyle = 'solid';
			this.handlesVisible = true;
			this.container.focus();			
		}
		//console.log('handles shown');
	},
	
	hideHandles: function(){

		//console.log('hide handles');
		if (this.topDragger) this.topDragger.hide();		
		if (this.bottomDragger) this.bottomDragger.hide();
					
		if (this.topLeftDragger) this.topLeftDragger.hide();
		if (this.topRightDragger) this.topRightDragger.hide();
		if (this.leftDragger) this.leftDragger.hide();
		if (this.rightDragger) this.rightDragger.hide();
		if (this.bottomLeftDragger) this.bottomLeftDragger.hide();
		if (this.bottomRightDragger) this.bottomRightDragger.hide();			

	
		if (this.container){
			this.container.style.borderLeftStyle = 'none';
			this.container.style.borderTopStyle = 'none';
			this.container.style.borderRightStyle = 'none';
			this.container.style.borderBottomStyle = 'none';			
		}
		
		//console.log('handles hidden');
		this.handlesVisible = false;
	},
	
	finish: function(){
		
		if (this.topLeftDragger){
			this.topLeftDragger.remove();
		}
		
		if (this.topDragger && this.topDragger.parentNode){
			this.topDragger.parentNode.removeChild(this.topDragger);			
		}

		if (this.topRightDragger && this.topRightDragger.parentNode){
			this.topRightDragger.parentNode.removeChild(this.topRightDragger);			
		}

		if (this.leftDragger && this.leftDragger.parentNode){
			this.leftDragger.parentNode.removeChild(this.leftDragger);			
		}

		if (this.rightDragger && this.rightDragger.parentNode){
			this.rightDragger.parentNode.removeChild(this.rightDragger);			
		}

		if (this.bottomLeftDragger && this.bottomLeftDragger.parentNode){
			this.bottomLeftDragger.parentNode.removeChild(this.bottomLeftDragger);
		}

		if (this.bottomDragger && this.bottomDragger.parentNode){
			this.bottomDragger.parentNode.removeChild(this.bottomDragger);			
		}

		if (this.bottomRightDragger && this.bottomRightDragger.parentNode){
			this.bottomRightDragger.parentNode.removeChild(this.bottomRightDragger);			
		}
		
		if (this.container && this.container.parentNode){
			this.container.parentNode.removeChild(this.container);
		}

		if (this.topLeftDraggable){
			this.topLeftDraggable.destroy();			
		}

		if (this.topDraggable){
			this.topDraggable.destroy();			
		}

		if (this.topRightDraggable){
			this.topRightDraggable.destroy();			
		}

		if (this.leftDraggable){
			this.leftDraggable.destroy();			
		}

		if (this.rightDraggable){
			this.rightDraggable.destroy();			
		}

		if (this.bottomLeftDraggable) {
			this.bottomLeftDraggable.destroy();			
		}

		if (this.bottomDraggable){
			this.bottomDraggable.destroy();
		}
		
		if (this.bottomRightDraggable){
			this.bottomRightDraggable.destroy();			
		}
		
	}
	
});



var ResizerManager = new Class.create({
	
	resizers: new Object(),
	
	addResizer: function(id,zIndex){
		this.removeResizer(id);
		this.resizers[id] = new Resizer(id,zIndex);
	},
		
	getResizer: function(id){		
		return this.resizers[id];
	},
	
	removeResizer: function(id){
		if (this.resizers[id]){
			this.resizers[id].finish();
			delete this.resizers[id];
		}
	},
	
	disableAllMouseOver: function(){
		for (var key in this.resizers){
			if (this.resizers[key]){
				this.resizers[key].disableMouseOver();				
			}
		}
	},
	
	enableAllMouseOver: function(){
		for (var key in this.resizers){
			if (this.resizers[key]){
				this.resizers[key].enableMouseOver();				
			}
		}
	}
	
});

var resizerManager = new ResizerManager();


var DepthManager = Class.create({
	
	minDepth:0,
	maxDepth:100,
	currentDepth:0,
	currentMinDepth:0,
	currentMaxDepth: 100,
	reverse: false,
	fields:null,
	inc: 1,
	
	initialize: function(minDepth,maxDepth,reverse){
		this.minDepth = minDepth;
		this.maxDepth = maxDepth;
		this.reverse = reverse;
		if (this.reverse){
			this.currentDepth = this.maxDepth;
			this.currentMinDepth = this.maxDepth;
			this.currentMaxDepth = this.maxDepth;
		}
		else {
			this.currentDepth = this.minDepth;

			this.currentMinDepth = this.minDepth;
			this.currentMaxDepth = this.minDepth;
		}
		this.fields = new Object();
	},
	
	addField: function(fieldId,useFieldDepth){
		if (useFieldDepth){
			this.fields[$(fieldId).style.zIndex] = new Array(fieldId);
		}
		else {
			this.fields[this.currentDepth] = new Array(fieldId);
			$(fieldId).style.zIndex = this.currentDepth;
			document.fire('ws:zIndex_changed',{ fieldId: fieldId });
			this.incDepth();			
		}
	},
	
	incDepth: function(){
		this.currentDepth = this.increaseDepth(this.currentDepth);
		if (this.reverse){
			this.currentMinDepth = this.currentDepth;
		}
		else {
			this.currentMaxDepth = this.currentDepth;
		}
	},
	
	increaseDepth: function(depth){
		depth = parseInt(depth);
		if (this.reverse){
			depth = depth - this.inc;
			if (depth<this.minDepth) depth = this.minDepth;
		}
		else {
			depth = depth + this.inc;
			if (depth>this.maxDepth) depth = this.maxDepth;
		}
		
		return depth;
	},
	
	decDepth: function(){
		this.currentDepth = this.decreaseDepth(this.currentDepth);
		if (this.reverse){
			this.currentMaxDepth = this.currentDepth;
		}
		else {
			this.currentMinDepth = this.currentDepth;
		}
	},
	
	decreaseDepth: function(depth){
		depth = parseInt(depth);
		if (this.reverse){
			depth = depth + this.inc;
			if (depth>this.maxDepth){
				depth = this.maxDepth;
			}
		}
		else {
			depth = depth - this.inc;
			if (depth<this.minDepth){
				depth = this.minDepth;
			}
		}
		return depth;
	},
	
	sendBackward: function(fieldId){
		if ($(fieldId) && $(fieldId).style.zIndex){
			var depth = $(fieldId).style.zIndex;
			var newDepth = this.decreaseDepth(depth);
			this.move(depth,newDepth);
		}
	},
	
	sendForward: function(fieldId){
		if ($(fieldId) && $(fieldId).style.zIndex){
			var depth = $(fieldId).style.zIndex;
			var newDepth = this.increaseDepth(depth);
			this.move(depth,newDepth);
		}
	},
	
	sendToBack: function(fieldId){
		if ($(fieldId) && $(fieldId).style.zIndex){
			var depth = $(fieldId).style.zIndex;
			this.move(depth,this.currentMinDepth);
		}		
	},
	
	sendToFront: function(fieldId){
		if ($(fieldId) && $(fieldId).style.zIndex){
			var depth = $(fieldId).style.zIndex;
			this.move(depth,this.currentMaxDepth);
		}		
		
	},
	
	applyDepth: function(objects,depth){
		if (!objects) return;
		depth = parseInt(depth);
		for (var i=0;i<objects.length;i++){
			$(objects[i]).style.zIndex = depth;
			document.fire('ws:zIndex_changed',{ fieldId: objects[i] });
		}
	},
	
	setDepth: function(fieldId,newDepth){
		if (newDepth>this.currentMaxDepth){
			this.currentMaxDepth = newDepth;
		}
		if (newDepth<this.currentMinDepth){
			this.currentMinDepth = newDepth;
		}
		
		if ($(fieldId) && $(fieldId).style.zIndex){
			var depth = $(fieldId).style.zIndex;
			this.move(depth,newDepth);
		}		
	},
	
	move: function(originDepth,destinationDepth){
		
		originDepth = parseInt(originDepth);
		destinationDepth = parseInt(destinationDepth);
		
		var objects = this.fields[originDepth];

		this.applyDepth(objects,destinationDepth);
		
		if (destinationDepth>originDepth){
			for (var j=originDepth+this.inc;j<=destinationDepth;j=j+this.inc){
				this.applyDepth(this.fields[j],j-this.inc);
				this.fields[j-this.inc] = this.fields[j];
			}
			
			this.fields[destinationDepth] = objects;
			
		}
		else {
			for (var j=originDepth-this.inc;j>=destinationDepth;j=j-this.inc){
				this.applyDepth(this.fields[j],j+this.inc);
				this.fields[j+this.inc] = this.fields[j];
			}
			this.fields[destinationDepth] = objects;
		}		
	}
	
});

var TreeViewManager = Class.create({
	toggleItem: function(itemId,groupId) {
		var group = $(groupId);
		var item = $(itemId);
		if (group) {
			if (group.visible()) {
				group.hide();
			}
			else {
				group.show();
			}
		}
		if (item) {
			if (item.className=='treeViewItemParentCollapsed') {
				item.className = 'treeViewItemParentExpanded';
			}
			else if (item.className=='treeViewItemParentExpanded') {
				item.className = 'treeViewItemParentCollapsed';
			}
		}
	}
});


var treeViewManager = new TreeViewManager();
var depthManagers = new Object();
var hudWindowManager = new HUDWindowManager();
var galleryManager = new GalleryManager();