var richHtmlEditorLocalizedTexts = new Array();

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};

String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
};

String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
};

function evalAllScripts(elementId,context){
	var scripts = $(elementId).getElementsByTagName('script');
	var x;
	for (x in scripts){
		try {
			if (scripts[x]){
				var result = eval(scripts[x].innerHTML);				
			}
		}
		catch(err){
			alert(err);
		}
	}	
}

var ContextManager = Class.create({
	hash: null,
	contextVariables: { },
	history: null,
	pe: null,
	timerStarted: false,
	iframe: null,
	
	initialize: function(){
		this.history = new Array();
	},
	
	initializeHash: function() {
		return;
		// var hash = window.location.hash;
		// window.location.hash = "";
		// this.contextVariables = {};
		// return hash;
	},
	
	loadHash: function(newhash) {
		var hash = '';
		if (newhash) hash=newhash;
		else hash = this.getHash();
		
		if( hash ) {
			hash = hash.replace('#','');
			hash = hash.replace('%7B','{');
			hash = hash.replace('%7D','}');
			var hashString = hash;
			do {
				hash = hashString;
				hashString = hash.replace('%27',"'");
			} while( hash!=hashString );

			do {
				hash = hashString;
				hashString = hashString.replace('%22',"'");
			} while( hash!=hashString );
			
			do {
				hash = hashString;
				hashString = hashString.replace('%3A',":");
			} while( hash!=hashString );
            
            do {
				hash = hashString;
				hashString = hashString.replace('%2C',",");
			} while( hash!=hashString );

            do {
				hash = hashString;
				hashString = hashString.replace("\\'","'");
			} while( hash!=hashString );
            
            do {
				hash = hashString;
				hashString = hashString.replace('\\"','"');
			} while( hash!=hashString );

			this.contextVariables = hash.evalJSON();
			//this.saveState();
			this.hash = hash;
		}
		else {
			this.contextVariables = new Object();
			this.contextVariables['pageId'] = system.defaultPageId;
			this.contextVariables['sectionId'] = system.defaultSectionId;
			this.hash = '';
		}
	},
	
	getHash: function () {
    	var index = location.href.indexOf('#');
    	return (index == -1 ? '' : location.href.substr(index + 1));
	},

	saveState: function(){
		var state = new Object();
		state['hash'] = this.getHash(); //window.location.hash;
		state['variables'] = Object.clone(this.contextVariables);
		
		//if (!this.history) this.history = new Array();
		this.history.push(state);
		this.hash = this.getHash();
		this.startTimer();
	},
	
	checkHashChanged: function(newhash){
		if (newhash!=this.hash){
			if (!newhash) newhash = '';
			this.loadHash(newhash);
			
			system.getPageManager().openPageFromDatabase();			
		}
	},
	
	startTimer: function(){
		if (this.timerStarted) return;
		LocationHash.init(this.checkHashChanged.bind(this),$('IEContextHistory'));
		this.timerStarted = true;
		
		// var runFun = this.checkHashChanged.bind(this);
		// 		this.pe = new PeriodicalExecuter(runFun,1);
		// 		this.timerStarted = true;
	},
	
	back: function(){
		// if (this.history) {
		// 		this.history.pop(); // Quitar la página actual
		// 		var state = this.history.pop();
		// 		if (state){
		// 			window.location.hash = state['hash'];
		// 			this.contextVariables = state['variables'];
		// 			system.getPageManager().openPageFromDatabase();				
		// 		}
		// 
		// 	}
		history.back();
	},
	
	go: function(hash){
		LocationHash.go(newHash);
	},
	
	updateHash: function() {
		//console.log('update hash');
		var newHash = '';
		for( var param in this.contextVariables ) {
			if( newHash.length==0 ) {
				newHash = '%7B';	// {
			}
			else {
				newHash += '%2C';	// ,
			}
								// :' 				'
			newHash += param + "%3A'" + this.contextVariables[param] + "'";
		}
		newHash += '%7D'; // }
		
		
		//console.log('new hash: ' + newHash);
		LocationHash.go(newHash);
		//window.location.hash = newHash;
		//this.saveState();
	},

	traceVariables: function() {
		var result = '';
		for( var parameter in this.contextVariables ) {
			result += parameter;
			result += ':';
			result += this.contextVariables[parameter];
			result += ', ';
		}
		alert(result);
	},
	
	getVariable: function(varName) {
		return this.contextVariables[varName];
	},
	
	getContextVariables: function() {
		return this.contextVariables;
	},
	
	setVariable: function(key,value) {
		this.contextVariables[key] = value;
	}
});

var contextManager = new ContextManager();

var PageManager = Class.create({
	useAjax:false,
	destinationURL:'_index.php',
	ajaxContainer:'pageContainer',
	firstLoad:false,

	configureAjax:function(destinationURL,ajaxContainer) {
		this.useAjax = true;
		this.destinationURL = destinationURL;
		this.ajaxContainer = ajaxContainer;
	},
	
	/* deprecated */
	configureReload:function(pageURL) {
		this.useAjax = false;
		this.pageURL = pageURL;
	},

	/* Si no queremos recargar el menú, usar new Page(...)*/
	openPageFromDatabase:function(pageId,doNotUpdateMenu){
		var containerId = this.ajaxContainer;
		contextManager.loadHash();
		var parameters = contextManager.getContextVariables();
		parameters.command = 'printPage';
		parameters.style = system.getCurrentStyle();
		if( parameters.pageId==undefined ) {
			parameters.pageId = pageId;
		}
		
		var section = contextManager.getVariable('sectionId');
		var page = contextManager.getVariable('pageId');
		if( section && page && !doNotUpdateMenu ) {
			system.getMenuManager().loadMenu(section, page);
		}
		
		this.fixPageContainerVisibility();
		contextManager.saveState();

		var loader = pb.core.loaderAnimation.getLoaderContainerText('pageLoader');
		$('pageContainer').innerHTML = loader;
		new Ajax.Request(this.destinationURL,{
			method:'post',
			parameters:parameters,
			onSuccess:function(transport){
				var container = $(containerId);
				if( container ) {
					container.innerHTML = transport.responseText;
					system.evalAllScripts(containerId,'openPageFromDatabase');

					document.fire("ws:page_printed",{ pageId: pageId });
					document.fire("ws:init");
					
					if (window.pageTracker){
						pageTracker._trackPageview(pageId);
					}

				}
			}
		});
	},
	
	fixPageContainerVisibility: function() {
		var winHeight;
		if (!this.firstLoad) {
			this.firstLoad = true;
		}
		else {
			if (system.Browser.IE) {
				winHeight = window.innerHeight;
			}
			else {
				winHeight = document.documentElement.clientHeight;
			}
	
			var pageContainerTop = $('pageContainerPositioner').offsetTop - (new ScrollManager()).currentOffset();
			if (pageContainerTop>winHeight || pageContainerTop<0 ) {
				window.scrollTo(0,$('pageContainerPositioner').offsetTop - 200);
			}
		}
	}
});

var MenuManager = Class.create({
	activeMenuItem:0,
	activeMenuSubItem:0,
	designMode: false,
	
	setDesignMode: function(designMode){
		this.designMode = designMode;
	},

	loadMenu: function(sectionId,pageId) {
		var menuItem = $('menuItem_'+this.activeMenuItem+'_content');
		var subMenu = $('subMenu_'+this.activeMenuItem);
		var subMenuItem = $('subMenuItem_s'+this.activeMenuItem+'_p'+this.activeMenuSubItem+'_content');
		this.deselectMenuItem(menuItem);
		this.deselectMenuSubItem(subMenuItem);
		
		// TODO: Refactorizar métodos de mostrar/ocultar sumbmenús
		if( subMenu ) {
			subMenu.hide();
		}
		this.activeMenuSubItem = pageId;
		this.activeMenuItem = sectionId;

		var menuItem = $('menuItem_'+this.activeMenuItem+'_content');
		var subMenu = $('subMenu_'+this.activeMenuItem);
		var subMenuItem = $('subMenuItem_s'+this.activeMenuItem+'_p'+this.activeMenuSubItem+'_content');
		this.selectMenuItem(menuItem);
		this.selectMenuSubItem(subMenuItem);
			
		// TODO: Refactorizar métodos de mostrar/ocultar submenú
		if( subMenu ) {
			subMenu.show();
		}
	},

	subMenuItemClick: function(id,automatic) { // automatic es true si se llama al pulsar un menú
		var subMenuItem = $('subMenuItem_s'+this.activeMenuItem+'_p'+this.activeMenuSubItem+'_content');
		this.deselectMenuSubItem(subMenuItem);
		this.activeMenuSubItem = id;
		subMenuItem = $('subMenuItem_s'+this.activeMenuItem+'_p'+this.activeMenuSubItem+'_content');
		this.selectMenuSubItem(subMenuItem);
		
		if (!this.designMode){
			contextManager.initializeHash();
			contextManager.setVariable('sectionId',this.activeMenuItem);
			contextManager.setVariable('pageId',this.activeMenuSubItem);
			contextManager.updateHash();
			system.getPageManager().openPageFromDatabase(id);			
		}
		
		document.fire('ws:submenu_clicked',{ id: id, sectionId: this.activeMenuItem,automatic: automatic });
	},

	menuItemClick: function(id,firstPageId,numberOfPages) {
		var menuItem = $('menuItem_'+this.activeMenuItem+'_content');
		var subMenu = $('subMenu_'+this.activeMenuItem);
		var subMenuItem = $('subMenuItem_s'+this.activeMenuItem+'_p'+this.activeMenuSubItem+'_content');
		this.deselectMenuItem(menuItem);
		
		
		// TODO: Refactorizar los métodos de mostrar y ocultar sub menú
		if( subMenu ) {
			subMenu.hide();
		}
		
		
		this.deselectMenuSubItem(subMenuItem);

		this.activeMenuItem = id;
		menuItem = $('menuItem_'+this.activeMenuItem+'_content');
		subMenu = $('subMenu_'+this.activeMenuItem);
		this.selectMenuItem(menuItem);
		
		// TODO: Refactorizar los métodos de mostrar y ocultar sub menú
		if( subMenu ) {
			subMenu.show();
		}
		
		document.fire('ws:menu_clicked',{ id: id, pageId: firstPageId });
		
		this.subMenuItemClick(firstPageId,true);
	},
	
	selectMenuItem: function(menuItem) {
		if( menuItem ) {
			menuItem.className = 'menuItemContentSelected';
		}
	},
	
	deselectMenuItem: function(menuItem) {
		if( menuItem ) {
			menuItem.className = 'menuItemContent';
		}
	},
	
	selectMenuSubItem: function(menuItem) {
		if( menuItem ) {
			menuItem.className = 'menuItemContentSelected_submenu';
		}
	},
	
	deselectMenuSubItem: function(menuItem) {
		if( menuItem ) {
			menuItem.className = 'menuItemContent_submenu';
		}
	},

	setActiveMenuItem: function(id) { this.activeMenuItem = id; },
	setActiveMenuSubItem: function(id) { this.activeMenuSubItem = id; }
});

var Session = Class.create({
	loginFormPopUp: null,
	loginFormPopUpId: 'loginFormPopUp',
	reloadParameters: '',
	currentPage: 0,

	createNewAccount: function(formId) {
		var params = $(formId).serialize(true);
		params.command="createAccount";
		params.style=system.getCurrentStyle();
		var currentPage = this.currentPage;

		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_current_user_utils.php', {
			method:'post',
			parameters:params,
			onSuccess: function(transport) {
				if( transport.responseText=='OK' ) {
					$('submitButton').hide();
					$('closePopUpButton').value = 'Ok';
					system.getSession().currentPage=0;
					if( currentPage!=0 ) {
						system.getMessageManager().showMessage('Cuenta creada con éxito (redireccionando a la ventana de login)',{color:'green'});
						setTimeout('system.getSession().showDatabaseLoginPopUp(' + currentPage + ')',1500);						
					}
					else {
						system.getMessageManager().showMessage('Cuenta creada con éxito',{color:'green'});
						setTimeout('system.getSession().hideLoginPopUp()',2000);
					}
				}
				else {
					system.getMessageManager().showMessage(transport.responseText,{color:'red'});
				}
			}
		}); 
	},

	signMe: function() {
		system.getPopUp().setContent('cargando formulario...');
		system.getPopUp().open();
		system.getPopUp().setContentWithURL(system.getLibraryPath() + 'plasticbriqFramework/actions/_current_user_utils.php',
							{command:'printSignUpForm',style:system.getCurrentStyle(),destinationLibraryPath:system.getLibraryPath()});
	},

	modifyUserData: function() {
		system.getPopUp().setContent('Loading data...');
		system.getPopUp().setContentWithURL(system.getLibraryPath()+'plasticbriqFramework/actions/_current_user_utils.php',
											{command:'modifyUserData',style:system.getCurrentStyle()});
		system.getPopUp().open();
	},

	getLoginFormPopUp: function() {
		if( this.loginFormPopUp==null ) {
			this.loginFormPopUp = $(this.loginFormPopUpId);
		}
		return this.loginFormPopUp;
	},
	
	getLoginFormPopUpId: function() {
		return this.loginFormPopUpId;
	},

	initialize: function() {
	},
	
	configureLoginForm: function(itemId,itemType) {
		var loginForm = $('mainLoginForm');
		if( loginForm ) {
			switch(itemType) {
				case 'web_page':
					this.reloadParameters = '?pageId=' + itemId;
					break;
				case 'web_section':
					this.reloadParameters = '?sectionId=' + itemId;
					break;
				case 'web_site':
					this.reloadParameters = '?siteId=' + itemId;
					break;
			}
		}
	},

	logIn: function(user,password,acl,aclType,responseContainer) {
		var actionFile = system.getLibraryPath() + 'plasticbriqFramework/actions/_session.php';
		// Si el login es a una página de la base de datos, esto hará que al recargar la página
		// el sistema entre al lugar que toca
		this.configureLoginForm(acl,aclType);

		new Ajax.Request(actionFile,{
			method: 'post',
			parameters: { command:'logIn', user:user, password:password, acl:acl, aclType:aclType },
			onSuccess: function(transport) {
				if( transport.responseText=='OK' ) {
					window.location.reload();
				}
				else {
					$(responseContainer).innerHTML = transport.responseText;
				}
			}
		});
	},
	
	logInUsingAjax: function(user,password,acl,aclType,responseContainer,pageURL,pageParams,pageContainer) {
		var actionFile = system.getLibraryPath() + 'plasticbriqFramework/actions/_session.php';
		var popUp = this.getLoginFormPopUp();
		var closeSessionControl = $('closeSessionControl');

		new Ajax.Request(actionFile,{
			method: 'post',
			parameters: { command:'logIn', user:user, password:password, acl:acl, aclType:aclType },
			onSuccess: function(transport) {
				if( transport.responseText=='OK' ) {
					system.getSession().currentPage = 0;
					new Page(pageURL,pageParams,pageContainer);
					popUp.hide();
					closeSessionControl.show();
				}
				else {
					$(responseContainer).innerHTML = transport.responseText;
				}
			}
		});
	},
	
	close: function() {
		var actionFile = system.getLibraryPath() + 'plasticbriqFramework/actions/_session.php';

		new Ajax.Request(actionFile,{
			method: 'get',
			parameters: { command:'close' },
			onSuccess: function(transport) {
				if( transport.responseText=='OK' ) {
					system.getSession().currentPage = 0;
					window.location.reload();
				}
				else {
					alert(transport.responseText);
				}
			},
			onFailure: function(transport) {
				alert('error en la carga');
			}
		});
	},

	showLoginPopUp: function() {
		system.hideElementsWithTagName('object');
		system.hideElementsWithTagName('embed');
		this.getLoginFormPopUp().show();
	},
	
	hideLoginPopUp: function() {
		system.showElementsWithTagName('object');
		system.showElementsWithTagName('embed');
		system.getSession().currentPage = 0;
		this.getLoginFormPopUp().hide();
	},
	
	showDatabaseLoginPopUp: function(page) {
		var popUp = this.getLoginFormPopUp();
		popUp.innerHTML = 'cargando formulario...';
		popUp.show();
		this.currentPage = page;
		system.hideElementsWithTagName('object');
		system.hideElementsWithTagName('embed');
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_session.php',{
			method:'post',
			parameters:{command:'printDatabaseLogin',style:system.getCurrentStyle(),pageId:page},
			onSuccess: function(transport) {
				popUp.innerHTML = transport.responseText;
			}
		});
	}
});

var ScrollManager = Class.create({
	currentOffset: function() {
		if (Prototype.Browser.IE) {
			return (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
		}
		else if( navigator.appName=='Netscape' ) {
			return window.pageYOffset;
		}
		else {
			return document.body.scrollTop;
		}
	}
});

var DynamicPopUp = Class.create({
	id : null,
	zIndex: 10000,
	initialize: function(id) {

		this.id = id;

		var popUp = new Element('div',{ 'id': 'popUp_' + this.id, 'class' : 'popUp','style':'display: none' });
		// popUp.style.position = 'absolute';
		// 	popUp.style.top = 0;
		var previousPopUp = $('popUp_'+this.id);
		
		if (previousPopUp) {
			previousPopUp.parentNode.removeChild(previousPopUp);
		}
		
		document.body.appendChild(popUp);
		
		var paddingLeft = '10px';
		var paddingTop = '10px';
		
		popUp.innerHTML = '<div id="popUpContainerBackground_' + this.id + '" class="popUpContainerBackground" onclick="system.getDynamicPopUp(\'' + this.id + '\').close();event.cancelBubble = true;return false;">\n\
					</div>\n\
					<div id="popUpContainer_' + this.id + '" class="popUpContainer" onclick="system.getDynamicPopUp(\'' + this.id + '\').close();event.cancelBubble = true;return false;">\n\
					<div class="popUpWindow" id="popUpWindow_' + this.id + '">\
						<div class="popUpTopContainer" style="padding-left: ' + paddingLeft + ';padding-top: ' + paddingTop + '">\n\
							<div class="popUpTopLeft"></div>\n\
							<div class="popUpTopHorizontal"></div>\n\
							<div class="popUpTopRight"></div>\n\
						</div> <!-- popUpTopContainer -->\n\
						<div class="popUpCenterContainer" style="padding-left: ' + paddingLeft + '">\n\
							<div id="popUpContent_' + this.id + '" class="popUpContent" onclick="event.cancelBubble = true">loading...\n\
							</div>\n\
						</div>\n\
						<div class="popUpBottomContainer" style="padding-left: ' + paddingLeft + '">\n\
							<div class="popUpBottomLeft"></div>\n\
							<div class="popUpBottomHorizontal"></div>\n\
							<div class="popUpBottomRight"></div>\n\
						</div> <!-- popUpBottomContainer -->\n\
						</div>\
					</div>';
					
		//new Draggable('popUpWindow_' + this.id);
	},	
	open: function(zIndex,keepPreviousData,keepFlashClips) {
		
		// if (!keepPreviousData){
		// 			this.setContent(localizedString.get('Loading data...'));
		// 		}
		
		if (!keepFlashClips){
			if (system.browserIgnoresEmbeddedZIndex()) {
				system.hideFlashClips(new Array('popUpContainer_' + this.id));
			}
		}
				
		if (!zIndex){
			zIndex = this.zIndex;
		}
		else {
			this.zIndex = zIndex;
		}
		
		$('popUpContainerBackground_' + this.id).style.zIndex = zIndex;
		$('popUpContainer_' + this.id).style.zIndex = zIndex + 10;
		
		document.fire('ws:popup_opening',{ dynamic: true });
		
		var scrollManager = new ScrollManager();
		var marginBase = 5;
		var margin = marginBase + scrollManager.currentOffset();
		
		$('popUpContainer_' + this.id).setStyle({ marginTop:margin + 'px'});

		Effect.Appear($('popUp_' + this.id), {duration:0.4});
		
		document.fire('ws:popup_opened',{ dynamic: true });
	},
	
	setZIndex: function(zIndex){
		$('popUpContainerBackground_' + this.id).style.zIndex = zIndex;
		$('popUpContainer_' + this.id).style.zIndex = zIndex + 10;
	},
	
	hide: function(){
		document.fire('ws:popup_closing',{ dynamic: true });
		Effect.Fade($('popUp_' + this.id), {duration:0.4});
		document.fire('ws:popup_closed',{ dynamic: true });
		
		if (system.browserIgnoresEmbeddedZIndex()) {
			system.showElementsWithTagName('object');
			system.showElementsWithTagName('embed');
		}
	},
	
	close: function() {
		this.hide();
		this.clear();
	},
	
	clear: function(){
		this.setContent('');
	},
	
	
	setContent: function(content) {
		$('popUpContent_' + this.id).innerHTML = content;
	},

	setContentWithURL: function(url,parameters) {
		
		var progressIcon = system.getLoadingIcon();
		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) {
				$('popUpContent_' + popUpId).innerHTML = transport.responseText;
				system.evalAllScripts('popUpContent_' + popUpId);
				document.fire('ws:init');
			}
		});
	}
}); 


var PopUp = Class.create({
	open: function(keepPreviousData,keepFlashClips) {
		
		if (!keepFlashClips){
			if (system.browserIgnoresEmbeddedZIndex()) {
				system.hideFlashClips(new Array('popUpContainer'));
			}
		}

		/*if (!keepPreviousData){
			this.setContent(localizedString.get('Loading data...'));
		}*/
		
		document.fire('ws:popup_opening');
		
		var scrollManager = new ScrollManager();
		var marginBase = 5;
		var margin = marginBase + scrollManager.currentOffset();
		$('popUpContainer').setStyle({ marginTop:margin + 'px'});
		Effect.Appear('popUp', {duration:0.4});
		
		document.fire('ws:popup_opened');
		//new Draggable('popUpWindow');
	//	$('popUp').show();
	},
	
	close: function() {
		
		if (system.browserIgnoresEmbeddedZIndex()) {
			system.showElementsWithTagName('object');
			system.showElementsWithTagName('embed');
		}

		//$('popUp').hide();
		document.fire('ws:popup_closing');
		Effect.Fade('popUp', {duration:0.4});
		document.fire('ws:popup_closed');
	},
	
	setContent: function(content) {
		$('popUpContent').innerHTML = content;
	},

	setContentWithURL: function(url,parameters) {
		
		var progressIcon = system.getLoadingIcon();
		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>');

		new Ajax.Request(url, {
				method:'post',
				parameters:parameters,
				onSuccess: function(transport) {
					$('popUpContent').innerHTML = transport.responseText;
					system.evalAllScripts('popUpContent');
					document.fire('ws:init');
				}
			});	
	}
}); 

var MessageManager = Class.create({
	pageMessageContainerId:'requestResult',
	popUpMessageContainerId:'popUpResult',

	setPageMessageContainerId: function(containerId) {
		this.pageMessageContainerId = containerId;
	},

	setPopUpMessageContainerId: function(containerId) {
		this.popUpMessageContainerId = containerId;
	},

	showMessage: function(message,style) {
		var pageMessageContainer = $(this.pageMessageContainerId);
		var popUpMessageContainer = $(this.popUpMessageContainerId);
		
		if( (pageMessageContainer!=null) && message) {
			pageMessageContainer.show();
			pageMessageContainer.innerHTML = message;
			if( style!=null ) {
				pageMessageContainer.setStyle(style);
			}
		}
		if( (popUpMessageContainer!=null) && message ) {
			popUpMessageContainer.show();
			popUpMessageContainer.innerHTML = message;
			if( style!=null ) {
				popUpMessageContainer.setStyle(style);
			}
		}
	},
	
	hideMessage: function() {
		var pageMessageContainer = $(this.pageMessageContainerId);
		var popUpMessageContainer = $(this.popUpMessageContainerId);
		
		if( pageMessageContainer!=null ) {
			pageMessageContainer.hide();
		}
		if( popUpMessageContainer!=null ) {
			popUpMessageContainer.hide();
		}
	}
});

var FormManager = Class.create({
	sendFieldValue: function(actionURL,command,fieldId) {
		var fieldValue = $(fieldId).value;
		var currentStyle = system.getCurrentStyle();

		new Ajax.Request(actionURL, {
			method:'post',
			parameters: { command:command, newValue:fieldValue, style:currentStyle },
			onSuccess: function(transport) {
				if( transport.responseText!='OK' && transport.responseText!='RELOAD' ) {
					system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
				}
				else if( transport.responseText=='RELOAD' ) {
					window.location.reload();
				}
				else {
					system.getMessageManager().hideMessage();
				}
			}
		});
	},
	
	sendForm: function(actionURL,command,formId) {
		var currentStyle = system.getCurrentStyle();
		var params = $(formId).serialize(true);
		params.style = currentStyle;
		params.command = command;

		new Ajax.Request(actionURL, {
			method:'post',
			parameters: params,
			onSuccess: function(transport) {
				if( transport.responseText!='OK' && transport.responseText!='RELOAD' ) {
					system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
				}
				else if( transport.responseText=='RELOAD' ) {
					window.location.reload();
				}
				else {
					system.getMessageManager().hideMessage();
				}
			}
		});
	},
	
	sendFormAndHideDynamicPopUp: function(actionURL,command,formId,dynamicPopUpId,afterHidePopUp) {
		var currentStyle = system.getCurrentStyle();
		var params = $(formId).serialize(true);
		params.style = currentStyle;
		params.command = command;

		new Ajax.Request(actionURL, {
			method:'post',
			parameters: params,
			onSuccess: function(transport) {
				if( transport.responseText!='OK' ) {
					system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
				}
				else {
					system.getDynamicPopUp(dynamicPopUpId).close();
					if (afterHidePopUp) {
						afterHidePopUp(formId);
					}
				}
			}
		});
		
	},
	
	sendFormAndHidePopUp: function(actionURL,command,formId,afterHidePopUp) {
		var currentStyle = system.getCurrentStyle();
		var params = $(formId).serialize(true);
		params.style = currentStyle;
		params.command = command;

		new Ajax.Request(actionURL, {
			method:'post',
			parameters: params,
			onSuccess: function(transport) {
				if( transport.responseText!='OK' ) {
					system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
				}
				else {
					system.getPopUp().close();
					if (afterHidePopUp) {
						afterHidePopUp(formId);
					}
				}
			}
		});
	},
	
	sendFormReloadContent: function(actionURL,command,formId,reloadPage,parameters,reloadPageParameters,customContainer) {
		var currentStyle = system.getCurrentStyle();
		var params = $(formId).serialize(true);
		params.style = currentStyle;
		params.command = command;
		var container = 'pageContainer';
		
		if (customContainer){
			container = customContainer;
		}
		
		if (parameters) {
			for (var key in parameters) {
				params[key] = parameters[key];
			}
		}

		new Ajax.Request(actionURL, {
			method:'post',
			parameters: params,
			onSuccess: function(transport) {
				if( transport.responseText!='OK' && transport.responseText!='RELOAD' ) {
					system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
				}
				else if( transport.responseText=='RELOAD' ) {
					system.getPopUp().close();	// Por si acaso se ha llamado desde un popUp
					var reloadParams = null;
					if (reloadPageParameters) {
						reloadParams = reloadPageParameters;
						if (!reloadParams.command){
							reloadParams.command = 'printPage';							
						}
						if (!reloadParams.style){
							reloadParams.style = system.getCurrentStyle();							
						}
						
					}
					else {
						reloadParams = { command:'printPage', style:system.getCurrentStyle() };
					}
					new Page(reloadPage, reloadParams, container);
				}
				else {
					system.getMessageManager().hideMessage();
				}
			}
		});
	},
		
	sendFormReloadContentCustom: function(actionURL,command,formId,reloadPage,parameters,reloadPageParameters,customContainer) {
		var currentStyle = system.getCurrentStyle();
		var params = $(formId).serialize(true);
		params.style = currentStyle;
		params.command = command;
		var container = 'pageContainer';
		
		if (customContainer){
			container = customContainer;
		}
		
		if (parameters) {
			for (var key in parameters) {
				params[key] = parameters[key];
			}
		}

		new Ajax.Request(actionURL, {
			method:'post',
			parameters: params,
			onSuccess: function(transport) {
				if( transport.responseText!='OK' && transport.responseText!='RELOAD' ) {
					system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
				}
				else if( transport.responseText=='RELOAD' ) {
					var reloadParams = null;
					if (reloadPageParameters) {
						reloadParams = reloadPageParameters;
						if (!reloadParams.command){
							reloadParams.command = 'printPage';							
						}
						if (!reloadParams.style){
							reloadParams.style = system.getCurrentStyle();							
						}
						
					}
					else {
						reloadParams = { command:'printPage', style:system.getCurrentStyle() };
					}
					new Page(reloadPage, reloadParams, container);
				}
				else {
					system.getMessageManager().hideMessage();
				}
			}
		});
	}
});

var ActionManager = Class.create({
	execute: function(actionURL,parameters) {
		new Ajax.Request(actionURL, {
			method:'post',
			parameters: parameters,
			onSuccess: function(transport) {
				if( transport.responseText!='OK' ) {
					system.getMessageManager().showMessage(transport.responseText,{ color:'red' });
				}
				else {
					system.getMessageManager().hideMessage();
				}
			}
		});
	},
	
	executeAndReloadPage: function(actionURL,parameters) {
		new Ajax.Request(actionURL, {
			method:'post',
			parameters: parameters,
			onSuccess: function(transport) {
				if( transport.responseText!='OK' ) {
					system.getMessageManager().showMessage(transport.responseText, { color:'red' });
				}
				else {
					window.location.reload();
				}
			}
		});
	},
	
	executeAndReloadContent: function(actionURL,parameters,reloadPage) {
		var reloadParameters = { command:'printPage', style:system.getCurrentStyle() };
		var container = 'pageContainer';

		this.executeAndReloadContentCustom(actionURL,parameters,reloadPage,reloadParameters,container);
	},

	executeAndReloadContentCustom: function(actionURL,parameters,reloadPage,reloadParameters,container) {
		new Ajax.Request(actionURL, {
			method:'post',
			parameters: parameters,
			onSuccess: function(transport) {
				if( transport.responseText!='OK' ) {
					system.getMessageManager().showMessage(transport.responseText, { color:'red' });
				}
				else {
					new Page(reloadPage,reloadParameters,container);
				}
			}
		});
	},
	
	executeAndPutResultIntoContainer: function(actionURL,parameters,containerId,useInnerHTML,append) {
		var container = $(containerId);
		if( container ) {
			document.fire("ws:reloading_container",{ name: containerId });
			new Ajax.Request(actionURL,{
				parameters:parameters,
				onSuccess:function(transport) {
					if( useInnerHTML ) {
						//betterInnerHTML(container,transport.responseText);
						if (append){
							container.innerHTML = container.innerHTML + transport.responseText;
						}
						else {
							container.innerHTML = transport.responseText;							
						}

						//container.update(transport.responseText);
					}
					else {
						if (append){
							container.value = container.value + transport.responseText;
						}
						else {
							container.value = transport.responseText;							
						}

					}
					system.evalAllScripts(containerId);
					document.fire('ws:init');
				}
			});
		}
	}
});

var Trash = Class.create({
	open: function(actionFile, printTrashCommand) {
		system.getPopUp().setContentWithURL(actionFile,{ command:printTrashCommand, style:system.getCurrentStyle() });
		system.getPopUp().open();
	},

	recoverItem: function(actionFile,command,itemId,printTrashCommand,commandParameters) {
		this.executeTrashAction(actionFile,command,itemId,printTrashCommand,commandParameters);
	},

	removeFromTrash: function(actionFile,deleteCommand,itemId,trashCommand,deleteCommandParameters) {
		this.executeTrashAction(actionFile,deleteCommand,itemId,trashCommand,deleteCommandParameters);
	},
	
	emptyTrash: function(actionFile){

		var loadPageParameters = { command:'printPage', style:system.getCurrentStyle() };
		var actionParameters = { command: 'emptyTrash',style: system.getCurrentStyle() };
		var pageContainerId = 'pageContainer';
		
		new Ajax.Request(actionFile, {
			method:'post',
			parameters: actionParameters,
			onSuccess: function(transport) {
				if( transport.responseText!='OK' ) {
					system.getMessageManager().showMessage(transport.responseText, { color:'red' });
				}
				else {
					new Ajax.Request(actionFile,{
						method:'post',
						parameters: loadPageParameters,
						onSuccess: function(transport) {
							$(pageContainerId).innerHTML = transport.responseText;
							//system.getPopUp().setContent('Loading data...'); 
							//system.getPopUp().setContentWithURL(actionFile, { command:printTrashCommand, style:system.getCurrentStyle() });
							document.fire('ws:init');
							system.getPopUp().close();
						}
					});
				}
			}
		});
	},
	
	executeTrashAction: function(actionFile,actionCommand,itemId,printTrashCommand,actionCommandParameters) {
		var loadPageParameters = { command:'printPage', style:system.getCurrentStyle() };
		var actionParameters = { command:actionCommand, id:itemId };
		
		for (var key in actionCommandParameters) {
			actionCommandParameters[key] = actionCommandParameters[key];
		}
		
		var pageContainerId = 'pageContainer';

		new Ajax.Request(actionFile, {
			method:'post',
			parameters: actionParameters,
			onSuccess: function(transport) {
				if( transport.responseText!='OK' ) {
					system.getMessageManager().showMessage(transport.responseText, { color:'red' });
				}
				else {
					new Ajax.Request(actionFile,{
						method:'post',
						parameters: loadPageParameters,
						onSuccess: function(transport) {
							$(pageContainerId).innerHTML = transport.responseText;
							system.getPopUp().setContent('Loading data...'); 
							system.getPopUp().setContentWithURL(actionFile, { command:printTrashCommand, style:system.getCurrentStyle() });
							document.fire('ws:init');
						}
					});
				}
			}
		});
	}
});

var Media = Class.create({
	
	getProportionalWidth: function(oldWidth,oldHeight,newHeight){
		if (oldHeight>0) return Math.floor((newHeight*oldWidth)/oldHeight);
		return Math.floor(newHeight*oldWidth);
	},
	
	getProportionalHeight: function(oldWidth,oldHeight,newWidth){
		if (oldWidth>0) return Math.floor((newWidth*oldHeight)/oldWidth);
		return Math.floor(newWidth*oldHeight);

	},
	
	getSizeForFrame: function(width,height,imageSize) {
		// var aux = new Image();
		// 		aux.src = imageUrl;
		
		var result = new Array(0,0);
		
		if ((imageSize[0]==0) || (imageSize[1]==0)) return result;
		
		//var imageSize = new Array(imageSize[0],imageSize[1]);
		
		if ((width==0) && (height==0)) return imageSize;
		
		if (width==0){
			if (imageSize[1]<height){
				return imageSize;
			}
			
			result[0] = media.getProportionalWidth(imageSize[0],imageSize[1],height);
			result[1] = height;
			return result;
			
		}
		else if (height==0){
			if (imageSize[0]<width){
				return imageSize;
			}
			
			result[0] = width;
			result[1] = media.getProportionalHeight(imageSize[0],imageSize[1],width);
			return result;
		}
		else {
			if ((imageSize[0]<width) && (imageSize[1]<height)){
				return imageSize;
			}
			
			var imageAspectRatio = imageSize[0]/imageSize[1];
			var frameAspectRatio = width/height;
			if (imageAspectRatio>frameAspectRatio){
				result[0] = width;
				result[1] = media.getProportionalHeight(imageSize[0],imageSize[1],width);
			}
			else {
				result[0] = media.getProportionalWidth(imageSize[0],imageSize[1],height);
				result[1] = height;
			}
			return result;
		}
				
	}	
	
});


var System = Class.create({
	currentStyle: 'undefined',
	libraryPath: 'undefined',
	downloaderUrl: 'undefined',
	session: new Session(),
	popUp: new PopUp(),
	forms: new FormManager(),
	actionManager: new ActionManager(),
	messageManager: new MessageManager(),
	menuManager: new MenuManager(),
	pageManager: new PageManager(),
	dynamicPopUps: new Array(),
	currentModule: null,
	siteId: 0,

	initialize: function(libraryPath,style) {
		this.libraryPath = libraryPath;
		this.currentStyle = style;
		
		this.Browser.name = this.searchString(this.dataBrowser) || "An unknown browser";
		this.Browser.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) ||
		 						"an unknown version";
		this.Browser.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	
	getLibraryPath: function(){return this.libraryPath;},
	getStylesPath: function(){return this.libraryPath + "../styles/";},
	getPBPath: function(){return this.libraryPath + "plasticbriqFramework/";},
	getDownloaderUrl: function () { return this.downloaderUrl; },
	getCurrentStyle:function(){return this.currentStyle;},
	getCurrentStylePath: function(){ return this.getStylesPath() + this.getCurrentStyle(); },
	getSession:function(){return this.session;},
	getPopUp:function(){return this.popUp;},
	getFormManager:function(){return this.forms;},
	getActionManager:function(){return this.actionManager;},
	getMessageManager:function(){return this.messageManager;},
	getMenuManager:function(){return this.menuManager;},
	getPageManager:function(){return this.pageManager;},
	setCurrentModule: function(moduleName) { this.currentModule = new Module(moduleName); },
	getCurrentModule: function() { return this.currentModule; },
	getSiteId: function(){ return this.siteId; },
	
	browserIgnoresEmbeddedZIndex: function() {
		if ((system.Browser.IE) || (system.Browser.Opera) || (system.Browser.Camino) || (system.Platform.Win)) {
			return true;
		}
		
		return false;
	},
	
	getViewportSize: function() {
		var myWidth = 0, myHeight = 0;
		if( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}

		return [myWidth,myHeight];
	},
	
	getScrolls: function() {
		var scrOfX = 0, scrOfY = 0;
		if( typeof( window.pageYOffset ) == 'number' ) {
			//Netscape compliant
    		scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			//IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		
		return [ scrOfX, scrOfY ];
	},
	
	getLoadingIcon: function (){
		return system.getLibraryPath() + "plasticbriqFramework/interfaceFiles/images/loading.gif";
	},
	
	getLoadingIconBlack: function (){
		return system.getLibraryPath() + "plasticbriqFramework/interfaceFiles/images/loading_black.gif";
	},

	/*************************/
	
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
		return "";
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return null;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	
	dataBrowser: [
			{
				string: navigator.userAgent,
				subString: "Chrome",
				identity: "Chrome"
			},
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari",
				versionSearch: "Version"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				   string: navigator.userAgent,
				   subString: "iPhone",
				   identity: "iPhone/iPod"
		    },
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		],
	
	/**************************/

	Browser: {
		IE: Prototype.Browser.IE,
		Opera: Prototype.Browser.Opera,
		Camino: (navigator.vendor=='Camino'),
		WebKit: Prototype.Browser.WebKit,
		Gecko: Prototype.Browser.Gecko,
		MobileSafari: Prototype.Browser.MobileSafari,
		OmniWeb: (navigator.userAgent=='OmniWeb'),
		Safari: Prototype.Browser.WebKit,
		Firefox: (navigator.userAgent=='Firefox')
	},
	
	Platform: {
		Win: ((navigator.platform=='Win')||(navigator.platform=='Win32')),
		Windows: ((navigator.platform=='Win')||(navigator.platform=='Win32')),
		Mac: (navigator.platform=='Mac'),
		Linux: (navigator.platform=='Linux'),
		iPhone: (navigator.userAgent=='iPhone')		
	},
	
	checkCompatibilityForWebSite: function(messageId,textContainerId) {
		var show = false;
		switch( system.Browser.name ) {
			case 'Explorer':
				if( system.Browser.version<7 ) {
					$(textContainerId).innerHTML = 'Internet Explorer ' + system.Browser.version;
					show = true;
				}
				break;
			case 'Firefox':
				if( system.Browser.version<3 ) {
					$(textContainerId).innerHTML = 'Mozilla Firefox ' + system.Browser.version;
					show = true;
				}
				break;
			case 'Opera':
				if( system.Browser.version<9 ) {
					$(textContainerId).innerHTML = 'Opera ' + system.Browser.version;
					show = true;
				}
				break;
			default:
				show = false;
				break;
		}
		if( show==false ) {
			$(messageId).hide();
		}
	},
	
	checkCompatibilityForControlPanel: function(messageId,textContainerId) {
		var show = false;
		switch( system.Browser.name ) {
			case 'Explorer':
				if( system.Browser.version<8 ) {
					$(textContainerId).innerHTML = 'Internet Explorer ' + system.Browser.version;
					show = true;
				}
				break;
			case 'Firefox':
				if( system.Browser.version<3 ) {
					$(textContainerId).innerHTML = 'Mozilla Firefox ' + system.Browser.version;
					show = true;
				}
				break;
			case 'Opera':
				if( system.Browser.version<9 ) {
					$(textContainerId).innerHTML = 'Opera ' + system.Browser.version;
					show = true;
				}
				break;
		}
		if( show==false ) {
			$(messageId).hide();
		}
	},
	
	isCommandKey: function(event){
		if (system.Browser.Safari && (event.keyCode==91)) return true;
		else if (system.Browser.Opera && (event.keyCode==17)) return true; 
 		else if (event.META_MASK) return true;
		else return false;		
	},
	
	isCtrlKey: function(keyCode){
		if (system.Browser.Opera) return false;
		if (keyCode==17) return true;
		return false;
	},
	
	getDynamicPopUp:function (id) { 
			
			if (!this.dynamicPopUps[id]){
				this.dynamicPopUps[id] = new DynamicPopUp(id);
			}
			
			return this.dynamicPopUps[id];
		},
	
	importScript:function(scriptUrl,id,charset){

		if (!charset) {
			charset = "utf-8";
		}

		var script  = document.createElement('script');
		script.id = id;
		script.type = "text/javascript";
		script.src  = scriptUrl;
		script.setAttribute("charset", charset);
		
		if (!$(id)){
			document.getElementsByTagName('head')[0].appendChild(script);			
		}
		
	},
	
	evalAllScripts: function(elementId,contextMessage){
		//var scripts = $(elementId).getElementsByTagName('script');
		var scripts = $(elementId).select('script');
		var x;
		for (x in scripts){
			try {
				if (scripts[x].innerHTML){
					
					// if (system.Browser.IE){
					// 						var result = window.execScript(scripts[x].innerHTML);
					// 					}
					// 					else {
					var result = eval(scripts[x].innerHTML);
					//}
				}
			}
			catch(err){
				var errorMessage = err;
				if (contextMessage){
					errorMessage = 'system.evalAllScripts. ' + contextMessage + ': ' + err;
				}
				alert(errorMessage);
			}
		}	
	},
	
	checkFileExists: function(filePath,callback){
		
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_utils.php',{
			method:'post',
			parameters:{ command:'checkFileExists',style:system.getCurrentStyle(), filePath: filePath },
			onSuccess: function(transport) {
				if( transport.responseText=='TRUE' ) {
					callback(filePath,true);
				}
				else if (transport.responseText=='FALSE'){
					callback(filePath,false);
				}
			}
		});
		
	},
	
	showSupportedBrowsers: function() {
		this.getPopUp().setContent('Cargando...');
		this.getPopUp().setContentWithURL(this.getLibraryPath() + 'plasticbriqFramework/actions/_compatibility.php',{command:'showSupportedBrowsers',style:this.getCurrentStyle()});
		this.getPopUp().open();
	},

	showLegalNotice: function() {
		this.getPopUp().setContent('Cargando...');
		this.getPopUp().setContentWithURL(this.getLibraryPath() + 'plasticbriqFramework/actions/_legal.php',{command:'showLegalNotice',style:this.getCurrentStyle()});
		this.getPopUp().open();
	},
	
	showPrivacyPolicy: function() {
		this.getPopUp().setContent('Cargando...');
		this.getPopUp().setContentWithURL(this.getLibraryPath() + 'plasticbriqFramework/actions/_legal.php',{command:'showPrivacyPolicy',style:this.getCurrentStyle()});
		this.getPopUp().open();
	},
	
	showTermsOfUse: function() {
		this.getPopUp().setContent('Cargando...');
		this.getPopUp().setContentWithURL(this.getLibraryPath() + 'plasticbriqFramework/actions/_legal.php',{command:'showTermsOfUse',style:this.getCurrentStyle()});
		this.getPopUp().open();
	},


	hideFlashClips: function(exceptions){
		system.hideElementsWithTagName('object');
		system.hideElementsWithTagName('embed');
		
		for (j=0;j<exceptions.length;j++){
			var elements = $$('#' + exceptions[j] + ' object');
			system.showElements(elements);
			var elements = $$('#' + exceptions[j] + ' embed');
			system.showElements(elements);
		}
	},

	hideElements: function(elements){
		for (i=0;i<elements.length;i++)
		{
			if (elements[i]!=null && elements[i]!="0"){
				elements[i].style.visibility = 'hidden';
			}
		}
	},
	
	showElements: function(elements){
		for (i=0;i<elements.length;i++)
		{
			if (elements[i]!=null  && elements[i]!="0"){
				elements[i].style.visibility = 'visible';
			}
		}		
	},
	
	hideElementsWithTagName: function(tagName)
	{

		//var elements = document.getElementsByTagName(tagName);
		var elements = $$(tagName);
		system.hideElements(elements);
	},

	showElementsWithTagName: function(tagName)
	{
		//var elements = document.getElementsByTagName(tagName);
		var elements = $$(tagName);

		for (i=0;i<elements.length;i++)
		{
			if (elements[i]!=null  && elements[i]!="0"){
				elements[i].style.visibility = 'visible';
			}
		}
	},
	
	switchToLanguage: function(languageId) {
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_session.php',{
			method:'post',
			parameters:{command:'switchToLanguage',style:system.getCurrentStyle(), languageId:languageId},
			onSuccess: function(transport) {
			//	if( transport.responseText=='OK' ) {
					window.location.reload();
			//	}
			//	else {
			//		alert(transport.responseText);
			//	}
			}
		});
	}
	
});

var ControlPanel = Class.create({
	trash: null,

	initialize: function() {
		this.trash = new Trash();
	},
	
	getTrash: function() { return this.trash; }
});

var controlPanel = new ControlPanel();

/* Carga páginas 'a pelo'. Mirar el PageManager (system.getPageManager()) para
utilizarlo de forma más automática. Este método no tiene en cuenta el HASH de la página */
var Page = Class.create({
	initialize: function(url,params,containerName) {
		this.containerName = containerName;
		this.container = $(containerName);
		this.url = url;
		params.style = system.getCurrentStyle();
		this.parameters = params;
		
	//	contextManager.loadHash();
	//	for( var variable in contextManager.contextVariables ) {
	//		params[variable] = contextManager.contextVariables[variable];
	//	}

		document.fire("ws:reloading_container",{ name: containerName });
		new Ajax.Request(url, {
			method:'post',
			parameters:params,
			onSuccess: function(transport) {
				//$(containerName).update(transport.responseText);
				$(containerName).innerHTML = transport.responseText;
				system.evalAllScripts(containerName);
				
				try {
					document.fire("ws:init");
					document.fire("ws:window_load");
				}
				catch (err){}

			}
		});
	}
});

var Module = Class.create({
	
	moduleName: 'undefined',
	
	initialize: function(moduleName) {
		this.moduleName = moduleName;
		errorManager.addErrorMessage(this.moduleName,'pageContainer');
	},
	
	goToModule: function(moduleName) {
		var url = system.getLibraryPath() + moduleName + '/index.php';
		window.location = url;
	},
	
	setError: function(error) {
		//this.clearError();
		//this.addError(error);
		errorManager.getError(this.moduleName).setError(error);
	},
	
	addError: function(error) {
		
		errorManager.getError(this.moduleName).addError(error);
		
		/*var errorFieldId = this.moduleName + "_Error";
		var errorField = $(errorFieldId);
		if (errorField) {
			errorField.innerHTML = error;
			errorField.appear();
		}
		else {
			var pageContainer = $('pageContainer');
			var errorField = new Element('p', { 'class':'error', 'id' : errorFieldId });
			errorField.innerHTML = error;
			if (pageContainer){
				Element.insert(pageContainer, { 'top': errorField } );
			}
			else {
				alert(error);
			}
		}*/
	},
	
	clearError: function() {
		/*var errorFieldId = this.moduleName + "_Error";
		var errorField = $(errorFieldId);
		if (errorField && errorField.style.display!='none') {
			errorField.fade({ onComplete: function(){ errorField.innerHTML = ""; } });
		}*/
		errorManager.getError(this.moduleName).clearError(error);
		
	}
	
});


var ErrorMessage = Class.create({
	
	id: null,
	parentId: null,
	
	initialize: function(id,parentId){
		
		this.id = id;
		
		if (!parentId){
			parentId = 'pageContainer';
		}
		
		this.parentId = parentId;
		
	},
	
	setError: function(error) {
		
		if (!error) return;
		
		this.clearError();
		this.addError(error);
	},
	
	addError: function(error) {
		
		if (!error) return;
		
		var errorFieldId = this.id + "_Error";
		var errorField = $(errorFieldId);
		if (errorField) {
			errorField.innerHTML = errorField.innerHTML + error;
			errorField.appear();
		}
		else {
			var container = $(this.parentId);
			var errorField = new Element('p', { 'class':'error', 'id' : errorFieldId });
			errorField.innerHTML = error;
			if (container){
				Element.insert(container, { 'top': errorField } );
			}
			else {
				alert(error);
			}
		}
	},
	
	clearError: function() {
		var errorFieldId = this.id + "_Error";
		var errorField = $(errorFieldId);
		if (errorField && errorField.style.display!='none') {
			//errorField.fade({ onComplete: function(){ errorField.innerHTML = ""; } });
			errorField.hide();
			errorField.innerHTML = "";
		}
	}
	
	
});

var ErrorManager = Class.create({
	errors: new Object(),
	pageError: new ErrorMessage('pageError'),
	
	addErrorMessage: function(id,parentId){
		this.errors[id] = new ErrorMessage(id,parentId);
	},

	getError: function(id){
		return this.errors[id];
	},
	
	// Errores de la página
	
	setError: function(text){
		pageError.setError(text);
	},
	
	clearError: function(){
		pageError.clearError();
	}
		
});

var errorManager = new ErrorManager();
//var fileUploaders = new Object();
var media = new Media();
