
var js_widgets_Manager = Class.create({
	widgets:new Array(),
	
	addWidget:function(widget) {
		var done = false;
		for (var i=0;i<this.widgets.length;++i) {
			if (this.widgets[i].id==widget.id) {
				this.widgets[i] = widget;	// substituir
				done = true;
				break;
			}
		}
		if (!done) {
			this.widgets.push(widget);
		}
	},
	
	getWidget:function(id) {
		for (var i=0;i<this.widgets.length;++i) {
			if (this.widgets[i].id==id) return this.widgets[i];
		}
		return null;
	}
});

var js_widgets_Menu = Class.create({
	id:'menuContainer',
	container:null,

	show:function(items,x,y) {
		this.initMenuContainer();
		this.container.show();
		if (!x) {
			x = js.core.mouse.getPosition().x;
		}
		if (!y) {
			y = js.core.mouse.getPosition().y;
		}
		// TODO: mostrar los items que tienen la forma
		//{"item1":"accion","item2":"accion"...}
		var dropdownMenu = document.createElement('div');
		Element.extend(dropdownMenu);
		this.container.innerHTML = "";
		this.container.appendChild(dropdownMenu);
		dropdownMenu.style.left = x + 'px';
		dropdownMenu.style.top = y + 'px';
		dropdownMenu.style.position = 'absolute';
		dropdownMenu.style.border = '1px solid gray';
		dropdownMenu.style.backgroundColor = 'white';
		dropdownMenu.style.opacity = 0.9;
		
		for(var item in items) {
			var menuItem = document.createElement('div');
			Element.extend(menuItem);
			menuItem.observe('click',items[item]);
			menuItem.onmousedown = function(event) {event.cancelBubble = false;return false; };
			menuItem.observe('mouseover',function(event) {this.style.backgroundColor = 'black'; this.style.color='white'; });
			menuItem.observe('mouseout',function(event) {this.style.backgroundColor = 'white'; this.style.color='black'; });
			menuItem.innerHTML = item;
			menuItem.style.cursor = 'default';
			menuItem.style.padding = '5px 20px 5px 10px';
			menuItem.style.opacity = 0.7;
			dropdownMenu.appendChild(menuItem);
		}
	},

	hide:function() {
		this.initMenuContainer();
		this.container.hide();
	},
	
	initMenuContainer:function() {
		if (this.container==null) {
			var menuContainer = document.createElement('div');
			Element.extend(menuContainer);
			menuContainer.id = this.id;
			menuContainer.style.position = 'fixed';
			menuContainer.style.left = '0px';
			menuContainer.style.right = '0px';
			menuContainer.style.top = '0px';
			menuContainer.style.bottom = '0px';
			menuContainer.observe('click',function(event) { js.widgets.menu.hide();});
			document.body.appendChild(menuContainer);
			this.container = menuContainer;
		}
	}
});


var js_widgets_Widget = Class.create({
	id:'',
	container:null,

	initialize:function(id) {
		this.id = id;
		this.container = $(id);
		js.widgets.manager.addWidget(this);
	},
	
	getFontFamily:function() {
		return 'helvetica,arial,sans-sherif';
	},
	
	getFontSize:function() {
		return '11px';
	}
});

var js_widgets_Field = Class.create(js_widgets_Widget,{
	containerId:'',

	onChange:null,

	initialize:function($super,id,containerId) {
		$super(id);
		this.container = $(containerId);
		this.containerId = containerId;
	},
	
	getValue:function() {
		var field = $(this.id);
		if (field && field.value) return field.value;
		else return '';
	},
	
	setValue:function(newValue) {
		var field = $(this.id);
		if (field && field.value) field.value = newValue;
	},
	
	callOnChange:function() {
		if (this.onChange) {
			this.onChange(this);
		}
	},
	
	show:function() {
		if (this.container) this.container.show();
	},
	
	hide:function() {
		if (this.container) this.container.hide();
	}
});

var js_widgets_SimpleFormField = Class.create(js_widgets_Field,{
	label:'',
	field:'',
	hint:'',

	initialize:function($super,id,containerId,label,value,hint,disabled) {
		$super(id, containerId);
		if (this.container) {
			this.label = this.createLabel(label);
			this.container.appendChild(this.label);
			this.field = this.createField(value,disabled);
			this.container.appendChild(this.field);
			this.hint = this.createHint(hint);
			this.container.appendChild(this.hint);
			var containerHeight = this.container.getHeight();
			this.container.style.height = containerHeight + 'px';
			this.applyStyles(containerHeight);
		}
	},
	
	createLabel:function(labelText) {
		var label = document.createElement('label');
		Element.extend(label);
		label.id = this.id + '_label';
		label.setAttribute('for',this.id);
		label.innerHTML = labelText + ':';
		return label;
	},
	
	createField:function(value,disabled) {
		var field = document.createElement('input');
		Element.extend(field);
		field.id = this.id;
		field.name = this.id;
		field.type = 'text';
		field.value = value;
		if (disabled) field.disabled = 'disabled';
		return field;
	},
	
	createHint:function(hintText) {
		var hint = document.createElement('span');
		Element.extend(hint);
		hint.id = this.id + '_hint';
		hint.innerHTML = hintText;
		return hint;
	},
	
	applyStyles:function(containerHeight) {
		this.label.style.cssFloat = 'left';
		this.label.style.width = '15%';
		this.label.style.display = 'block';
		this.label.style.height = containerHeight + 'px';
		this.label.style.paddingTop = '5px;';
		this.label.style.lineHeight = '20px';
		this.label.style.textAlign = 'right';
		
		this.field.style.cssFloat = 'left';
		this.field.style.width = '45%';
		this.field.style.display = 'block';
		
		this.hint.style.cssFloat = 'left';
		this.hint.style.width = '35%';
		this.hint.style.display = 'block';
		this.hint.style.height = containerHeight + 'px';
		this.hint.style.lineHeight = '20px';
		this.hint.style.paddingLeft = '3px';
		this.hint.style.color = "#7f7f7f";
	}
});

var js_widgets_TextField = Class.create(js_widgets_SimpleFormField,{
	initialize:function($super,id,containerId,label,value,hint,disabled) {
		$super(id,containerId,label,value,hint,disabled);
	},

	createField:function($super,value,disabled) {
		return $super(value,disabled);
	}
});

var js_widgets_TextArea = Class.create(js_widgets_SimpleFormField,{
	rows:'',

	initialize:function($super,id,containerId,label,value,hint,rows,disabled) {
		this.rows = rows;
		$super(id,containerId,label,value,hint,disabled);
	},

	createField:function($super,value,disabled) {
		var field = document.createElement('textarea');
		Element.extend(field);
		field.id = this.id;
		field.name = this.id;
		field.rows = this.rows;
		if (disabled) field.disabled = 'disabled';
		field.innerHTML = value;
		return field;
	}
});

var js_widgets_CheckBox = Class.create(js_widgets_SimpleFormField,{
	initialize:function($super,id,containerId,label,value,hint,disabled) {
		$super(id,containerId,label,value,hint,disabled);
	},

	createField:function($super,value,disabled) {
		var field = document.createElement('input');
		Element.extend(field);
		field.id = this.id;
		field.type = 'checkbox';
		field.name = this.id;
		field.rows = this.rows;
		if (disabled) field.disabled = 'disabled';
		field.checked = value;
		return field;
	}
});

var js_widgets_OptionSelector = Class.create(js_widgets_SimpleFormField,{
	selected:'',

	initialize:function($super,id,containerId,label,options,hint,selected,disabled) {
		this.selected = selected;
		$super(id,containerId,label,options,hint,disabled);
		// Los estilos que se pongan aquí tendrán preferencia sobre los estilos por defecto
		this.field.style.width = "";
	},

	createField:function($super,value,disabled) {
		var id = this.id;
		var field = document.createElement('select');
		Element.extend(field);
		field.id = id;
		field.name = id;
		field.observe('change',function(event) { js.W(id).callOnChange(); });
		for(var optionId in value) {
			var option = document.createElement('option');
			Element.extend(option);
			option.label = value[optionId];
			option.value = optionId;
			if (this.selected==optionId) option.selected = 'selected';
			field.appendChild(option);
		}
		return field;
	}
});

var js_widgets_ItemList = Class.create(js_widgets_Field,{
	dataSource:'',
	dataSourceCommand:'',
	dataSourceParams:'',
	data:'',
	previousItem:'',

	initialize:function($super,id,containerId,title,dataSource,data,width,height,dataSourceCommand,dataSourceParams) {
		$super(id, containerId);
		this.dataSource = dataSource;
		this.dataSourceCommand = dataSourceCommand;
		this.dataSourceParams = dataSourceParams;
		this.data = data;
		var container = this.container;
		if (container) {
			var field = document.createElement('input');
			field.id = id;
			field.name = id;
			field.type = 'hidden';
			field.value = '';
			container.appendChild(field);
			var titleBar = this.getTitleBar(width);
			titleBar.innerHTML = title;
			container.appendChild(titleBar);
			var itemList = this.getItemList(width,height);
			container.appendChild(itemList);
			if (data=='') {
				this.reload();
			}
			else {
				this.setData(data);
			}
			container.observe('click',function(event) { js.widgets.manager.getWidget(id).select();});
			itemList.onmousedown = function(event) { return false; };
		}
	},
	
	getTitleBar:function(width) {
		var titleBar = document.createElement('div');
		Element.extend(titleBar);
		titleBar.id = this.id + '_titleBar';
		titleBar.style.width = width;
		titleBar.style.height = '18px';
		titleBar.style.backgroundColor = '#EEE';
		titleBar.style.borderBottom = 'solid 1px #7E7E7E';
		titleBar.style.color = '';
		titleBar.style.fontFamily = this.getFontFamily();
		titleBar.style.fontSize = this.getFontSize();
		titleBar.style.lineHeight = '18px';
		titleBar.style.textAlign = 'center';
		return titleBar;
	},
	
	getItemList:function(width,height) {
		var itemList = document.createElement('div');
		Element.extend(itemList);
		itemList.id = this.id + '_list';
		itemList.style.width = width;
		itemList.style.height = height;
		itemList.style.backgroundColor = 'white';
		itemList.style.overflow = 'auto';
		itemList.style.fontFamily = this.getFontFamily();
		itemList.style.fontSize = this.getFontSize();
		return itemList;
	},
	
	reload:function() {
		if (this.dataSource) {
			var itemList = this;
			var parameters = {};
			if (this.dataSourceParams) {
				parameters = this.dataSourceParams();
			}
			js.core.actions.load(this.dataSource,this.dataSourceCommand,parameters,
				function(response) {
					itemList.setData(response);
				}
			);
		}
	},
	
	setData:function(dataAsString) {
		var container = $(this.id + '_list');
		if (container) {
			container.innerHTML = '';
			var data = JSON.parse(dataAsString);
			var id = this.id;
			for(var itemData in data) {
				if (itemData=='itemId') continue;
				var item = document.createElement('div');
				var image = data[itemData].icon;
				var iconTitle = data[itemData].iconTitle;
				Element.extend(item);
				if (iconTitle) {
					iconTitle = ' title="' + iconTitle + '"';
				}
				if (image) {
					item.innerHTML = '<span style="display:block;float:left;height:20px;line-height:20px;margin-right:5px;">' + data[itemData].title + '</span> <img src="' + image + '" alt="" height="16" style="margin-top:1px;"' + iconTitle + '/>';
				}
				else {
					item.innerHTML = data[itemData].title;
				}
				item.value = data[itemData].id;
				item.style.height = '18px';
				item.style.lineHeight = '18px';
				item.style.paddingLeft = '10px';
				item.style.paddingTop = '1px';
				item.style.paddingBottom = '1px';
				item.style.borderBottom = 'solid lightgray 1px';
				item.style.cursor = 'default';
				var itemId = itemData;
				item.observe('click',function(event) { js.widgets.manager.getWidget(id).select(this); event.cancelBubble = true; return false;});
				item.onmousedown = function(event) { return false; };
				container.appendChild(item);
			}	
		}
	},
	
	select:function(item) {
		var field = $(this.id);
		if (field) {
			if (item) {
				field.value = item.value;				
			}
			else {
				field.value = '';
			}
			this.updateSelected(item);
		}
	},

	updateSelected:function(item) {
		if (this.previousItem) {
			this.previousItem.style.backgroundColor = '';
			this.previousItem.style.color = '';
			this.previousItem.style.opacity = "";
		}
		if (item) {
			item.style.backgroundColor = 'black';
			item.style.color = 'white';	
			item.style.opacity = '0.5';
		}
		this.previousItem = item;
		this.callOnChange();
	}
});

var js_widgets_ActionBar = Class.create(js_widgets_Widget,{
	initialize:function($super,id) {
		$super(id);
		if (this.container) {
			var container = this.container;
			var bkgUrl = js.resources.getItemPath('widgets','action_bar_bkg.png');
			var bkgImage = new Image();
			bkgImage.src = bkgUrl;
			bkgImage.observe('load',function(event) {
				container.style.backgroundImage = 'url(' + bkgUrl + ')';
				container.style.height = bkgImage.height + 'px';
				container.style.borderTop = 'solid 1px #7e7e7e';
				container.style.borderBottom = 'solid 1px #7e7e7e';
			});
			container.style.width = '100%';
			// Cancelar el modo seleccion. No hacer esto con un observe
			container.onmousedown = function(event) { return false; };
		}
	}
});

var js_widgets_IconButton = Class.create(js_widgets_Widget,{
	initialize:function($super,id,action,icon,pkg) {
		$super(id);
		if (!pkg) pkg = 'images';
		if (this.container) {
			var container = this.container;
			js.resources.loadImage(pkg,icon,
				function(event,imageUrl,image) {
					var iconWidth = js.resources.getItemWidth(image);
					var hoverOffset = js.resources.getItemOffset(image,'hover');
					var activeOffset = js.resources.getItemOffset(image,'active');
					container.style.width = iconWidth + 'px';
					container.style.height = image.height + 'px';
					container.style.display = 'block';
					container.style.width = iconWidth + 'px';
					container.style.height = image.height + 'px';
					container.style.cssFloat = 'left';
					container.style.backgroundImage = 'url(' + imageUrl + ')';
					container.style.backgroundRepeat = 'no-repeat';
					container.style.backgroundPosition = '0px 0px';
					Event.observe(id,'click',action);
					Event.observe(id,'mouseover',function(event) { this.style.backgroundPosition = -hoverOffset + 'px 0px'; });
					Event.observe(id,'mouseout',function(event) { this.style.backgroundPosition = '0px 0px'; });
					// Importante: no hacer un observe. Es necesario llamar a onmousedown así para que no funcione el modo seleccion. Por eso se devuelve false al final
					container.onmousedown = function(event) {this.style.backgroundPosition = -activeOffset + 'px 0px'; return false;};
					Event.observe(id,'mouseup',function(event) { this.style.backgroundPosition = '0px 0px'; });
				}
			);
		}
	}
});

var js_widgets_ItemPicker = Class.create(js_widgets_Field,{
	previewContainer:null,
	button:null,
	useFileName:false,

	initialize:function($super,id,containerId,label,value,hint,useFileName,disabled) {
		$super(id,containerId);
		container = this.container;
		this.useFileName = useFileName;
		if (container) {
			var previewContainer = document.createElement('div');
			Element.extend(previewContainer);
			previewContainer.id = id + '_peview';
			this.previewContainer = previewContainer;
			container.appendChild(previewContainer);

			var field = document.createElement('input');
			Element.extend(field);
			field.id = id;
			field.name = id;
			field.type = 'hidden';
			field.value = value;
			container.appendChild(field);
			
			var button = document.createElement('input');
			Element.extend(button);
			button.id = id + '_button';
			button.type = 'button';
			button.value = label;
			if (disabled) {
				button.disabled = 'disabled';
			}
			button.observe('click',function(event) { js.W(id).openSelectDialog(); });
			container.appendChild(button);
			this.button = button;
			
			if (hint) {
				var labelField = document.createElement('span');
				Element.extend(labelField);
				labelField.innerHTML = hint;
				container.appendChild(labelField);
			}
			this.container.style.marginLeft = '15%';
		}
	},
	
	openSelectDialog:function() {
		var pickerWindow = js.windows.modalManager.createAndOpen('itemPickerWindow','',10,100,800,650,1000,650);
		js.windows.modalManager.setLoading(pickerWindow);
		return pickerWindow;
	},
	
	reloadPreview:function() {
	}
});

var js_widgets_ImagePicker = Class.create(js_widgets_ItemPicker,{
	initialize:function($super,id,containerId,label,value,hint,useFileName,disabled) {
		$super(id,containerId,label,value,hint,useFileName,disabled);
		if (this.previewContainer) {
			this.previewContainer.style.width = "400px";
			this.previewContainer.style.height = "100px";
			this.previewContainer.style.overflow = 'auto';
			this.previewContainer.style.display = 'block';
			this.previewContainer.style.border = '1px solid #7e7e7e';
			this.previewContainer.style.textAlign = 'center';
			this.previewContainer.style.paddingTop = '20px';
			
			var image = document.createElement('img');
			Element.extend(image);
			image.src = value;
			image.alt = "";
			image.height = 80;
			this.previewContainer.appendChild(image);
		}
	},
	
	openSelectDialog:function($super) {
		var pickerWindow = $super();
		var params = {};
		params.fieldId = this.id;
		params.windowId = pickerWindow.identifier;
		if (this.useFileName) {
			params.fileName = this.getValue();			
		}
		else {
			params.itemId = this.getValue();
		}
		pickerWindow.setContentWithURL(js.system.actionsPath + '_htmlWidgets_image_picker_actions.php',
									'openImageSelectorPopUp',params,
									new pb_core_Task('openSelectDialog','Loading image select dialog',false));
	},
	
	reloadPreview:function($super) {
		var thisWidget = this;
		js.core.actions.load(js.system.actionsPath + '_htmlWidgets_image_picker_actions.php','getImageFileUrl',{imageId:this.getValue()},
			function(response) {
				thisWidget.previewContainer.innerHTML = '';
				var image = document.createElement('img');
				Element.extend(image);
				image.src = response;
				image.alt = "";
				image.height = 80;
				thisWidget.previewContainer.appendChild(image);
				
				if (thisWidget.useFileName) {
					thisWidget.setValue(response);
				}
			}
		);
	}
});

var js_widgets_VideoPicker = Class.create(js_widgets_ItemPicker,{
	initialize:function($super,id,containerId,label,value,hint,useFileName,disabled) {
		$super(id,containerId,label,value,hint,useFileName,disabled);
		if (this.previewContainer) {
			this.previewContainer.style.width = "400px";
			this.previewContainer.style.height = "60px";
			this.previewContainer.style.paddingLeft = '10px';
			this.previewContainer.style.paddingTop = '10px';
			this.previewContainer.style.overflow = 'auto';
			this.previewContainer.style.display = 'block';
			this.previewContainer.style.border = '1px solid #7e7e7e';
			this.previewContainer.style.textAlign = 'left';
			this.previewContainer.innerHTML = value;
			this.previewContainer.appendChild(image);
		}
	},
	
	openSelectDialog:function($super) {
		var pickerWindow = $super();
		var params = {};
		params.fieldId = this.id;
		params.windowId = pickerWindow.identifier;
		if (this.useFileName) {
			params.fileName = this.getValue();			
		}
		else {
			params.itemId = this.getValue();
		}
		pickerWindow.setContentWithURL(js.system.actionsPath + '_htmlWidgets_video_picker_actions.php',
									'openVideoSelectorPopUp',params,
									new pb_core_Task('openSelectDialog','Loading video select dialog',false));
	},
	
	reloadPreview:function($super) {
		var thisWidget = this;
		js.core.actions.load(js.system.actionsPath + '_htmlWidgets_video_picker_actions.php','getVideoFileUrl',{videoId:this.getValue()},
			function(response) {
				thisWidget.previewContainer.innerHTML = response;
				
				if (thisWidget.useFileName) {
					thisWidget.setValue(response);
				}
			}
		);
	}
});

var js_widgets_FilePicker = Class.create(js_widgets_ItemPicker,{
	initialize:function($super,id,containerId,label,value,hint,useFileName,disabled) {
		$super(id,containerId,label,value,hint,useFileName,disabled);
		if (this.previewContainer) {
			this.previewContainer.style.width = "400px";
			this.previewContainer.style.height = "60px";
			this.previewContainer.style.paddingLeft = '10px';
			this.previewContainer.style.paddingTop = '10px';
			this.previewContainer.style.overflow = 'auto';
			this.previewContainer.style.display = 'block';
			this.previewContainer.style.border = '1px solid #7e7e7e';
			this.previewContainer.style.textAlign = 'left';
			this.previewContainer.innerHTML = value;
			this.previewContainer.appendChild(image);
		}
	},
	
	openSelectDialog:function($super) {
		var pickerWindow = $super();
		var params = {};
		params.fieldId = this.id;
		params.windowId = pickerWindow.identifier;
		if (this.useFileName) {
			params.fileName = this.getValue();			
		}
		else {
			params.itemId = this.getValue();
		}
		pickerWindow.setContentWithURL(js.system.actionsPath + '_htmlWidgets_file_picker_actions.php',
									'openFileSelectorPopUp',params,
									new pb_core_Task('openSelectDialog','Loading file select dialog',false));
	},
	
	reloadPreview:function($super) {
		var thisWidget = this;
		js.core.actions.load(js.system.actionsPath + '_htmlWidgets_file_picker_actions.php','getFileUrl',{fileId:this.getValue()},
			function(response) {
				thisWidget.previewContainer.innerHTML = response;
				
				if (thisWidget.useFileName) {
					thisWidget.setValue(response);
				}
			}
		);
	}
});

var js_widgets_TextFontManager = Class.create({
	currentField:null,
	dataSource:'',
	dataSourceCommand:'',
	dataSourceParams:'',
	selectedFont:'arial',
	selectedFontName:'Arial',
	sampleText:'abcdefg',
	fonts: null,

	initialize:function() {
		// Inicializar los textos que se van a usar para los selectores de texto
		var keys = "Sample Text|Font Size|Select|Cancel|Other options|Open font selector";
		js.dictionary.initKeys(keys);
		this.loadFonts();
	},

	loadFonts: function() {
		var obj = this;
		js.core.actions.load(js.system.actionsPath + '_font_actions.php','loadFonts',{},
			function(response) {
				obj.fonts = response.evalJSON();
			}
		);	
	},

	setSampleText:function(text) {
		this.sampleText = text;
	},
	
	setDataSource:function(dataSource,dataSourceCommand,dataSourceParams) {
		this.dataSource = dataSource;
		this.dataSourceCommand = dataSourceCommand;
		this.dataSourceParams = dataSourceParams;
	},

	openFontWindow:function(fontWidget) {
		this.currentField = fontWidget;
		
		var pickerWindow = js.windows.modalManager.createAndOpen('fontSelectorWindow','',10,100,1000,510,1000,510);
		js.windows.modalManager.setLoading(pickerWindow);
		this.reloadWindowContent();

		// if (fontWidget) {
		// 			this.setSelectedFont(fontWidget.getValue());
		// 		}

		return pickerWindow;
	},
	
	closeFontWindow:function() {
		var fontSelectorWindow = pb.applications.modalWindowManager.getItem('fontSelectorWindow');
		fontSelectorWindow.close();
	},

	applySelectedFont:function() {
		if (this.currentField) {
			selectedFont = null;
			for (var i=0;i<this.fonts.length;i++) {
				if (this.fonts[i]['name']==this.selectedFontName) {
					selectedFont = this.fonts[i];
					break;
				}
			}
			this.currentField.setValue(selectedFont['family']);
		}
	},

	reloadWindowContent:function() {
		var fontSelectorWindow = pb.applications.modalWindowManager.getItem('fontSelectorWindow');
		if (fontSelectorWindow) {
			var mainContainer = document.createElement('div');
			Element.extend(mainContainer);
			// mainContainer.appendChild(this.getFontListContainer());
			mainContainer.appendChild(this.getSampleContainer());
			mainContainer.appendChild(this.getBottomContainer());

			fontSelectorWindow.setContentDom(mainContainer);
			
			this.createSampleFormatContainer(mainContainer);
		}
	},

	createSampleFormatContainer: function(mainContainer) {
		var filterContainer = document.createElement('div');
		Element.extend(filterContainer);
		filterContainer.id = 'filterContainer';
		filterContainer.style.display = 'block';
		filterContainer.style.position = 'absolute';
		filterContainer.style.width = '100%';
		filterContainer.style.height = '30px';
		filterContainer.style.marginTop = '2px';
		mainContainer.appendChild(filterContainer);
		
		// Sample Text Field
		var textFieldContainer = document.createElement('div');
		Element.extend(textFieldContainer);
		textFieldContainer.id = 'sample_container';
		textFieldContainer.style.cssFloat = 'left';
		
		filterContainer.appendChild(textFieldContainer);
		
		var sampleTextField = document.createElement('div');
		Element.extend(sampleTextField);
		sampleTextField.id = 'sample_textfield';
		filterContainer.appendChild(sampleTextField);
		var textFieldNode = new js_widgets_TextField('sample','sample_container',js.dictionary.translate('Sample Text'),this.sampleText,'',false);
		
		textFieldNode.field.setAttribute('onkeyup','js.widgets.textFontManager.updateSample(this.value);');
		textFieldNode.label.style.marginTop = '1px';
		textFieldNode.label.style.width = '120px';
		textFieldNode.field.style.width = '400px';
		
		// Font Size
		var fontSizeContainer = document.createElement('div');
		Element.extend(fontSizeContainer);
		fontSizeContainer.id = 'fontsize_container';
		fontSizeContainer.style.cssFloat = 'left';
		
		filterContainer.appendChild(fontSizeContainer);
		
		var fontSizeField = document.createElement('div');
		Element.extend(fontSizeField);
		fontSizeField.id = 'fontsize_sample_textfield';
		fontSizeContainer.appendChild(fontSizeField);
		textFieldNode = new js_widgets_TextField('fontsize','fontsize_container',js.dictionary.translate('Font Size'),'14px','',false);
		
		textFieldNode.field.setAttribute('onkeyup','js.widgets.textFontManager.updateFontSize(this.value);');
		textFieldNode.label.style.marginTop = '1px';
		textFieldNode.label.style.width = '100px';
		textFieldNode.field.style.width = '50px';		
		
		return filterContainer;
	},
	
	getBottomContainer:function() {
		var bottomContainer = document.createElement('div');
		Element.extend(bottomContainer);
		bottomContainer.style.display = 'block';
		bottomContainer.style.position = 'absolute';
		bottomContainer.style.bottom = '0px';
		bottomContainer.style.width = '100%';
		bottomContainer.style.height = '30px';
		
		var selectButton = document.createElement('input');
		selectButton.setAttribute('value',js.dictionary.translate("Select"));
		selectButton.setAttribute('type','button');
		selectButton.style.cssFloat = 'right';
		selectButton.setAttribute('onclick',"js.widgets.textFontManager.applySelectedFont(); js.widgets.textFontManager.closeFontWindow();");
		bottomContainer.appendChild(selectButton);
		
		var cancelButton = document.createElement('input');
		cancelButton.setAttribute('value',js.dictionary.translate("Cancel"));
		cancelButton.setAttribute('type','button');
		cancelButton.style.cssFloat = 'right';
		cancelButton.setAttribute('onclick',"js.widgets.textFontManager.closeFontWindow()");
		bottomContainer.appendChild(cancelButton);
		
		return bottomContainer;
	},
	
	getFontListContainer:function() {
		var fontListContainerScroll = document.createElement('div');
		Element.extend(fontListContainerScroll);
		fontListContainerScroll.style.overflow = "auto";
		fontListContainerScroll.style.width = "20%";
		fontListContainerScroll.style.height = "430px";
		fontListContainerScroll.style.position = 'absolute';
		fontListContainerScroll.style.borderRight = "1px solid #8d8d8d";
		fontListContainerScroll.style.left = '0px';
		fontListContainerScroll.style.top = '25px';
		fontListContainerScroll.style.borderBottom = "1px solid #8d8d8d";
		fontListContainerScroll.style.borderTop = "1px solid #8d8d8d";
		fontListContainerScroll.style.backgroundColor = "white";

		var fontList = this.getFontList();
		for (var font in fontList) {
			var fontItem = fontList[font];
			var selected = false;
			if (fontItem.display.toLowerCase()==this.selectedFontName.toLowerCase()) {
				selected = true;
			}
			var fontItemContainer = document.createElement('div');
			Element.extend(fontItemContainer);
			fontItemContainer.id = this.getFontId(fontItem.display);
			fontItemContainer.innerHTML = fontItem.display;
			fontItemContainer.style.height = "20px";
			fontItemContainer.style.lineHeight = "20px";
			fontItemContainer.style.fontFamily = font;
			fontItemContainer.style.fontSize = "14px";
			fontItemContainer.style.paddingLeft = "20px";
			fontItemContainer.style.cursor = "pointer";
			if (selected) {
				fontItemContainer.style.backgroundColor = 'black';
				fontItemContainer.style.color = 'white';
			}
			fontListContainerScroll.appendChild(fontItemContainer);
			fontItemContainer.setAttribute('onclick',"js.widgets.textFontManager.setSelectedFont('" + font + "');");
		}

		return fontListContainerScroll;
	},

	getSampleContainer:function() {
		var sampleContainerScroll = document.createElement('div');
		Element.extend(sampleContainerScroll);
		sampleContainerScroll.style.overflow = "auto";
		sampleContainerScroll.style.width = "100%";
		sampleContainerScroll.style.height = "430px";
		sampleContainerScroll.style.position = "absolute";
		sampleContainerScroll.style.fontSize = '14px';
		sampleContainerScroll.style.top = "25px";
		sampleContainerScroll.style.right = "0px";
		sampleContainerScroll.style.borderBottom = "1px solid #8d8d8d";
		sampleContainerScroll.style.borderTop = "1px solid #8d8d8d";
		sampleContainerScroll.style.backgroundColor = "white";
		
		var sampleContainer = document.createElement('div');
		Element.extend(sampleContainer);
		sampleContainer.id = 'textFontSelector_sampleContainer';
		sampleContainer.style.fontFamily = this.selectedFont;
		// sampleContainer.style.width = "2000px";
		sampleContainerScroll.appendChild(sampleContainer);

		var sampleTextContainer;
		//for( var i = 6; i<=34; i+=2) {
		// for (var font in this.fonts) {
		var obj = this;
		this.fonts.each(function(font) {
			sampleTextContainer = document.createElement('div');
			Element.extend(sampleTextContainer);
			sampleTextContainer.id = 'textFontSelector_sampleText_' + font['name'];
			sampleTextContainer.style.minHeight = '40px';
			sampleTextContainer.style.cursor = 'pointer';
			sampleTextContainer.style.padding = '10px';
			sampleTextContainer.style.fontFamily = font['family'];
			sampleTextContainer.style.borderBottom = '1px solid #ccc';
			sampleTextContainer.style.overflow = 'hidden';
			sampleTextContainer.setAttribute('onclick',"js.widgets.textFontManager.setSelectedFont('" + font['name'] + "');");
			sampleContainer.appendChild(sampleTextContainer);
			
			var sampleTextValueContainer = document.createElement('div');
			Element.extend(sampleTextValueContainer);
			sampleTextValueContainer.className = 'textFontSelector_sampleText';
			sampleTextValueContainer.innerHTML = obj.sampleText;
			sampleTextContainer.appendChild(sampleTextValueContainer);
			
			var sampleFontName = document.createElement('div');
			Element.extend(sampleFontName);
			sampleTextContainer.appendChild(sampleFontName);
			sampleFontName.id = 'textFontSelector_sampleText_' + font['name'] + '_name';
			sampleFontName.style.fontSize = '12px';
			sampleFontName.style.marginLeft = '200px';
			sampleFontName.style.color = '#666';
			sampleFontName.style.height = '20px';
			// sampleFontName.style.padding = '5px';
			sampleFontName.style.fontFamily = 'Lucida Grande,helvetica,sans-serif';
			sampleFontName.style.overflow = 'hidden';
			sampleFontName.innerHTML = font['name'];
		});

		return sampleContainerScroll;
	},
	
	chooseCurrentFont:function() {
		if (this.currentField && this.currentField.callOnChange) {
			this.currentField.callOnChange();
		}
	},
	
	getFontContainer: function(fontName) {
		return $('textFontSelector_sampleText_'+fontName);
	},
	
	updateSample: function(sampleText) {
		$('textFontSelector_sampleContainer').select('.textFontSelector_sampleText').each(function(item){
			item.innerHTML = sampleText;			
		});
	},
	
	updateFontSize: function(size) {
		size = pb.core.cssUtils.addPx(size);
		$('textFontSelector_sampleContainer').style.fontSize = size;
	},
	
	setSelectedFont:function(fontName) {
		
		if (this.selectedFontName) {
			var fontContainer = this.getFontContainer(this.selectedFontName);
			fontContainer.style.backgroundColor = '';
		}
		
		var fontContainer = this.getFontContainer(fontName);
		fontContainer.style.backgroundColor = '#ccc';
		
		this.selectedFontName = fontName;
		
	},
	
	oldSetSelectedFont:function(fontName) {
		// Aquí aplicamos la fuente seleccionada al texto de muestra
		var sampleContainer = $('textFontSelector_sampleContainer');
		var lastId = this.getFontId(this.selectedFontName);
		var lastItem = $(lastId);
		if (lastItem) {
			lastItem.style.backgroundColor = "";
			lastItem.style.color = "";
		}
		if (sampleContainer) {
			var fontList = this.getFontList();
			var selectedFontName = "";
			var selectedFont = "";
			for (var font in fontList) {
				var fontItem = fontList[font];
				if (font.toLowerCase()==fontName.toLowerCase()) {
					selectedFontName = fontItem.display;
					selectedFont = font;
					break;
				}
				else if (selectedFont=="") {	// Si no hay selected, haciendo esto cogerá la primera de la lista
					selectedFontName = fontItem.display;
					selectedFont = font;
				}
			}
			sampleContainer.style.fontFamily = selectedFont;
			this.selectedFontName = selectedFontName;
			this.selectedFont = selectedFont;
			
			var newId = this.getFontId(this.selectedFontName);
			var newItem = $(newId);
			if (newItem) {
				newItem.style.backgroundColor = "black";
				newItem.style.color = "white";
			}
		}
	},

	getFontList:function(data) {
		var fontString = "";
		if (data) {
			fontString = data;
		}
		else {
			fontString = "{";
			fontString += '"Verdana":{"display":"Verdana"},';
			fontString += '"Arial":{"display":"Arial"},';
			fontString += '"Helvetica, Arial":{"display":"Helvetica"},';
			fontString += '"Times New Roman":{"display":"Times New Roman"},';
			fontString += '"Georgia":{"display":"Georgia"},';
			fontString += '"Lucida Sans,sans-serif":{"display":"Lucida Sans"},';
			fontString += '"Gill Sans,verdana,sans-serif":{"display":"Gill Sans"},';
			fontString += '"Trebuchet MS":{"display":"Trebuchet MS"},';
			fontString += '"Courier New":{"display":"Courier New"},';
			fontString += '"Tahoma":{"display":"Tahoma"},';
			fontString += '"Cardo,Georgia,serif":{"display":"Cardo"},';
			fontString += '"Josefin Sans Std Light, Futura,arial, sans-serif":{"display":"Josefin Sans Std Light"},';
			fontString += '"Lobster,Georgia,serif":{"display":"Lobster"},';
			fontString += '"Tangerine":{"display":"Tangerine"},';
			fontString += '"Nobile,arial,sans-serif":{"display":"Nobile"},';
			fontString += '"Reenie Beanie, arial, sans-serif":{"display":"Reenie Beanie"}';
			fontString += "}";
		}
		return JSON.parse(fontString);
	},
	
	getFontId:function(fontName) {
		var text = fontName;
		var search = " ";
		var replace = "_";
		while(text.indexOf(search)!=-1) {
			text = text.replace(search,replace);
		}
		return text + '_item';
	}
});

var js_widgets_TextFontSelector = Class.create(js_widgets_Field,{
	selectedIndex:0,	// Esto es para restaurar la lista si se selecciona una acción

	initialize:function($super,id,containerId,selected) {
		$super(id,containerId);
		var container = this.container;
		if (container) {
			this.createFontSelector(container,selected);
		}
	},
	
	setValue:function($super,newValue) {
		// Si la selección es para ejecutar una acción, tendremos que cancelar esto
		if (newValue!='openFontSelector') {
			$super(newValue);
		//	$(this.id + '_button').value = js.widgets.textFontManager.selectedFontName;
			var cbox = $(this.id);
			if (cbox) {
				// Actualizar el índice seleccionado
				this.selectedIndex = cbox.selectedIndex;				
			}
			this.callOnChange();
		}
	},

	selectFieldChanged:function() {
		var selectField = $(this.id);
		if (selectField) {
			if (selectField.value=='openFontSelector') {
				selectField.selectedIndex = this.selectedIndex;
				js.widgets.textFontManager.openFontWindow(this);
			}
			else {
				this.callOnChange();
			}
		}
	},

	createFontSelector:function(container,selectedFontKey) {
		if (!container) return;
		else container.innerHTML = "";
		
		var selectField = document.createElement('select');
		Element.extend(selectField);
		selectField.id = this.id;
		selectField.name = this.id;
		var thisClass = this;
//		selectField.onchange = function(event) { js.widgets.textFontManager.openFontWindow(thisClass); };
		selectField.onchange = function(event) { thisClass.selectFieldChanged(); };
		container.appendChild(selectField);
		
		var fontList = js.widgets.textFontManager.getFontList();
		
//		var selectedFontName = "";
//		var selectedFont = "";
		var isSelected = false;
		var i = 0;
		for (var font in fontList) {
			var option = document.createElement('option');
			var fontItem = fontList[font];
			option.value = font;
			option.innerHTML = fontList[font].display;
			selectField.appendChild(option);
			if (fontItem.display.toLowerCase()==selectedFontKey.toLowerCase()) {
				selectedFontName = fontItem.display;
				selectedFont = font;
				option.setAttribute('selected','selected');
				this.selectedIndex = i;
			}
//			else if (selectedFont=="") {	// Si no hay selected, haciendo esto cogerá la primera de la lista
//				selectedFontName = fontItem.display;
//				selectedFont = font;
//			}
			++i;
		}
		
		var optionGroup = document.createElement('optgroup');
		Element.extend(optionGroup);
		optionGroup.label = js.dictionary.translate('Other options');
		selectField.appendChild(optionGroup);
		
		// CUIDADO con las opciones que se pongan aquí, en el setValue hay que hacer que no se establezca
		// el nuevo valor si la selección es una opción de esta lista, y restaurar el valor anterior de la selección
		// Ver la función setValue() más arriba
		var previewOption = document.createElement('option');
		previewOption.value = 'openFontSelector';
		previewOption.innerHTML = js.dictionary.translate('Open font selector');
		optionGroup.appendChild(previewOption);

		
		
//		var hiddenField = document.createElement('input');
//		hiddenField.type = 'hidden';
//		hiddenField.id = this.id;
//		hiddenField.name = this.id;
//		hiddenField.value = selectedFont;
//		container.appendChild(hiddenField);

//		var selector = document.createElement('input');
//		selector.id = this.id + '_button';
//		selector.type = 'button';
//		selector.value = selectedFontName;
//		var thisClass = this;
//		selector.onclick = function(event) { js.widgets.textFontManager.openFontWindow(thisClass); }
//		container.appendChild(selector);
	}
});

