function setWindowLoadedFlagFunction() {
	pb.core.system.windowLoaded = true;
}

if (window.addEventListener) {
	window.addEventListener('load',setWindowLoadedFlagFunction,false);
}
else if (window.attachEvent) {
	window.attachEvent('onload',setWindowLoadedFlagFunction);
}

var pb_core_System = Class.create({
	currentStyle: 'undefined',
	libraryPath: '',
	downloaderUrl: '',
	operatingSystem: 'Unknown Operating System',
	windowLoaded:false,
	
	getLibraryPath: function() { return this.libraryPath; },
	getCurrentStyle: function() { return this.currentStyle; },
	getDownloaderUrl: function() { return this.downloaderUrl; },
	
	initialize: function() {
		this.browser.name = this.searchString(this.dataBrowser) || "Unknown browser";
		this.browser.version = this.searchVersion(navigator.userAgent) ||
				this.searchVersion(navigator.appVersion) ||
				"Unknown browser version";
		this.browser.OS = this.searchString(this.dataOS) || "Unknown OS";
	},
	
	isWindowLoaded: function() {
		return this.windowLoaded;
	},
	
	importJavaScript: function(fileURL) {
		var head = document.getElementsByTagName('head').item(0);
		script = document.createElement('script');
		script.src = fileURL;
		script.type = 'text/javascript';
		head.appendChild(script);
	},
	
	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.indexOf("Firefox")!=-1)
	},
	
	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')		
	},
	
	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;
		}
	},

	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	
	evalAllScripts: function(elementId,contextMessage){
		var scripts = $(elementId).select('script');
		var x;
		for (x in scripts){
			try {
				if (scripts[x].innerHTML){
					var result = eval(scripts[x].innerHTML);
				}
			}
			catch(err){
				var errorMessage = err;
				if (contextMessage){
					errorMessage = 'system.evalAllScripts. ' + contextMessage + ': ' + err;
				}
				alert(errorMessage);
			}
		}	
	},
	
	hideElementsWithTagName: 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 = 'hidden';
			}
		}
	},

	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';
			}
		}
	},
	
	getViewportSize: function() {
		var myWidth = 0, myHeight = 0;
		if( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			var size = document.viewport.getDimensions();
			myWidth = size.width;
			myHeight = size.height;
		} 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];
	},
	
	getScreenSize: function(){
		return [ screen.availWidth, screen.availHeight ];
	},
	
	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
			var size = document.viewport.getScrollOffsets();
			scrOfY = size[0];
			scrOfX = size[1];
		} 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 ];
	}
});  // pb_core_System

var pb_core_Actions = Class.create({
	execute: function(actionURL,command,parameters,onDone,taskId,onComplete) {
		parameters.command = command;
		parameters.style = pb.core.system.getCurrentStyle();
		// return new Ajax.Request(actionURL, {
		// 			method:'post',
		// 			parameters: parameters,
		// 			onSuccess: function(transport) {
		// 				if (onDone) {
		// 					onDone(transport.responseText);
		// 				}
		// 			},
		// 			onComplete: function(transport) {
		// 				if (onComplete) {
		// 					onComplete(transport.responseText);
		// 				}
		// 				if (taskId) pb.core.activityMonitor.endTask(taskId);
		// 			}
		// 		});
		
		if (!taskId) {
			new Ajax.Request(actionURL, {
					method:'post',
					parameters: parameters,
					onSuccess: function(transport) {
						if (onDone) {
							onDone(transport.responseText);
						}
					},
					onComplete: function(transport) {
						if (onComplete) {
							onComplete(transport.responseText);
						}
						if (taskId) pb.core.activityMonitor.endTask(taskId);
					}
				});
			return null;
		}
		
		
		var successCallback = null;
		if (onDone) successCallback = function(transport) {	onDone(transport.responseText); };

		var onCompleteCallback = null;
		if (onComplete) onCompleteCallback = function(transport) {	onComplete(transport.responseText); };
		
		var task = new pb_core_AjaxTask(taskId);
		task.run(actionURL,parameters,successCallback,onCompleteCallback);
		return task;
		
	},

	executeAndPutResultIntoContainer: function(actionURL,command,params,containerId,useInnerHTML,append,taskId,useParent,callback) {
		var container = $(containerId);
		if( container ) {
			document.fire("ws:reloading_container",{ name: containerId });
			return this.execute(actionURL,command,params,
				function(responseText) {
					if (useInnerHTML) {
						if (append) {
							container.innerHTML = container.innerHTML + responseText;
						}
						else {
							container.innerHTML = responseText;
						}
					}
					else {
						if (append) {
							container.value = container.value + responseText;
						}
						else {
							container.value = responseText;
						}
					}
					pb.core.system.evalAllScripts(containerId);
					document.fire('ws:init');
				},'',function(){ 	
					if (taskId) {
						if (useParent) parent.pb.core.activityMonitor.endTask(taskId);
						else pb.core.activityMonitor.endTask(taskId);
					}
					if (callback) callback();
				 });
		}
	},
	
	// Es una envoltura del periodicalUpdater de prototype, solo que incluye el comando y la plantilla
	periodicalUpdater: function(actionURL,command,parameters,containerId,frequency,decay) {
		parameters.command = command;
		parameters.style = pb.core.system.getCurrentStyle();
		if (!frequency) frequency = 60;
		if (!decay) decay = 1;
		new Ajax.PeriodicalUpdater(containerId, actionURL, {
			method:'post',
			parameters: parameters,
			frequency:frequency,
			decay:decay
		});
	}
}); // pb_core_Actions

var pb_core_Page = Class.create({
	
}); // pb_core_Page

var pb_core_Menu = Class.create({
	
}); // pb_core_Menu

var pb_core_Navigation = Class.create({
	
}); // pb_core_Navigation

var pb_core_Hash = Class.create({
	
}); // pb_core_Hash

var pb_core_Session = Class.create({
	logIn: function(loginParams) {
		pb.core.activityMonitor.addTask(new pb_core_Task('logIn','Login'));
		pb.core.actions.execute(this.actionFile(),'logIn',loginParams,
			function(responseText) {
				if (responseText=='OK') {
					$('logInErrorMessage').innerHTML = '';
					$('error_message').fade();
					$('pb_logo_icon').appear();
					window.location.href = window.location.href;
				}
				else {
					pb.core.activityMonitor.endTask('logIn');
					$('error_message').appear();
					$('pb_logo_icon').fade();
					$('logInErrorMessage').innerHTML = responseText;
				}
			});
	},
	
	logOut: function() {
		pb.core.activityMonitor.addTask(new pb_core_Task('logOut','Logging out..'));
		pb.core.actions.execute(this.actionFile(),'logOut',{},
			function(responseText) {
				window.location.reload();
			});
	},
	
	actionFile: function() {
		return pb.core.system.getLibraryPath() + 'plasticbriqFramework/core/_session.php';
	}
}); // pb_core_Session

var pb_core_LocalizedString = Class.create({
	
	localizations: new Object(),
	
	get: function(string){
		if (this.localizations[string]) {
			return this.localizations[string];
		}
		return string;
	}	
}); // pb_core_LocalizedString

var pb_core_ActivityMonitorView = Class.create({
	containerId: '',
	effect: null,

	initialize:function(containerId) {
		this.containerId = containerId;
	},
	
	showView: function() {
		if ($(this.containerId)) {
			if (this.effect) this.effect.cancel();
			$(this.containerId).show();
		}
	},
	
	hideView: function() {
		if ($(this.containerId)) {
			this.effect = Effect.Fade(this.containerId,{duration:0.4});
		}
	}
}); // pb_core_ActivityMonitorView

var pb_core_Task = Class.create({
	identifier: '',
	title: '',
	type: '',
	
	Task: function(identifier,title,type) {
		this.identifier = identifier;
		this.title = title;
		this.type = type;	
	},

	initialize: function(identifier,title,type) {
		this.Task(identifier,title,type);
	}
}); // pb_core_Task

var pb_core_ActivityMonitor = Class.create({
	views:new Array(),
	tasks:new Object(),

	registerView: function(view) {
		this.views[this.views.length] = view;
	},

	unregisterView: function(viewId) {
		var viewIndex = -1;
		for (var i=0; i<this.views.length; i++) {
			if (this.views[i].containerId==viewId) {
				viewIndex = i;
				break;
			}
		}
		this.views.splice(viewIndex,1);
	},

	addTask: function(task) {
		this.tasks[task.identifier] = task;
		this.checkTasks();
	},
	
	getUniqueTaskId: function(taskId) {
		var newTaskId = taskId;
		
		var i = 0;
		while (this.tasks[newTaskId]) {
			newTaskId = taskId + '_' + i;
			i++;
		}
		
		return newTaskId;
	},
	
	getActiveTasksCount: function() {
		return Object.keys(this.tasks).length;
	},

	endTask: function(taskId) {
		// var taskIndex = -1;
		// for (var i=0; i<this.views.length; i++) {
		// 	if (this.tasks[i] && (this.tasks[i].identifier==taskId)) {
		// 		taskIndex = i;
		// 		break;
		// 	}
		// }
		if (this.tasks[taskId]){
			//this.tasks.splice(taskId,1);
			delete this.tasks[taskId];
			this.checkTasks();
		}
		
		var activeTasks = this.getActiveTasksCount();
		if (activeTasks==0) document.fire('ws:pb_core_activity_monitor_all_finished');
	},
	
	checkTasks: function() {
		var key;
		var activeTasks = this.getActiveTasksCount();
		
		for ( key in this.views) {
			if (activeTasks>0) {
				if (this.views[key] && this.views[key].showView) this.views[key].showView();
			}
			else {
				if (this.views[key] && this.views[key].hideView) this.views[key].hideView();
			}
		}
	}
});	// pb_core_ActivityMonitor

var pb_core_Counter = Class.create({
	
	counter: 0,
	
	getId: function(prefix){
		this.counter++;
		return this.getLastId(prefix);
	},
	
	getLastId: function(prefix){
		return prefix + this.counter;
	}
	
}); // pb_core_Counter

var pb_core_Node = Class.create({
	identifier:'',
	type:'node',
	htmlContainer:null,
	
	Node: function(identifier) {
		this.identifier = identifier;
		if ($(identifier)) {
			this.htmlContainer = $(identifier);
		}
	},
	
	setZIndex: function(zIndex){
		if (this.htmlContainer) this.htmlContainer.style.zIndex = zIndex;
	},
	
	getZIndex: function(){
		if (this.htmlContainer) return this.htmlContainer.style.zIndex;
	},

	initialize:function(identifier) {
		this.Node(identifier);
	},
	
	finish: function() {
		
	}
}); // pb_core_Node

var pb_core_Container = Class.create(pb_core_Node,{
	
	visible: true,
	
	Container: function(identifier){
		this.Node(identifier);
	},
	
	initialize: function(identifier){
		this.Container(identifier);
	},
	
	show: function(){
		if (this.htmlContainer) this.htmlContainer.show();
		this.visible = true;
	},
	
	hide: function(){
		if (this.htmlContainer) this.htmlContainer.hide();
		this.visible = false;
	},
	
	toggle: function(){
		if (this.htmlContainer){
			if (this.visible){
				this.htmlContainer.hide();
			}
			else {
				this.htmlContainer.show();
			}
		}
		this.visible = !this.visible;
	},
	
	setContent: function(content){
		if (this.htmlContainer){
			this.htmlContainer.innerHTML = content;
			return true;
		}
		return false;
	},
	
	setContentWithURL: function(url,command,parameters,task) {
		if (!task){
			var task = new pb_core_Task(pb.core.counter.getId(this.identifier),pb.core.localizedString.get('Loading container content'));
		}
		
		pb.core.activityMonitor.addTask(task);
		pb.core.actions.executeAndPutResultIntoContainer(url,command,parameters,this.identifier,true,false,task.identifier);
	}

}); // pb_core_Container

var pb_core_ItemManager = Class.create({
	items:null,
	
	ItemManager: function(){
		this.items = new Object();
	},	
	
	initialize: function(){
		this.ItemManager();
	},

	addItem: function(item) {
		if (item && item.identifier) {
			if (this.getItem(item.identifier)) this.removeItem(item.identifier);
			this.items[item.identifier] = item;
		}
	},

	addItemOfType: function(item,type) {
		if (item && item.type==type) this.addItem(item);
	},

	getItem: function(identifier) {
		return this.items[identifier];
	},

	removeItem: function(identifier) {
		this.items[identifier].finish();
		this.items[identifier] = undefined;
	}
}); // pb_core_ItemManager


var pb_core_AjaxTask = Class.create(pb_core_Task,{
	
	request: null,
	
	AjaxTask: function(identifier,title) {
		this.Task(identifier,title,'ajax');
	},
	
	initialize: function(identifier,title){
		this.AjaxTask(identifier,title);
	},
	
	run: function(url,parameters,callback,onCompleteCallback,delay) {
		pb.core.ajaxTaskManager.removeTask(this.identifier);
		pb.core.ajaxTaskManager.addTask(this);
		if (!delay) delay = 30; // 30 milisegundos de retardo por defecto
		
		var task = this;
		
		
		var fun = function () {
			task.request = new Ajax.Request(url, {
				method:'post',
				parameters:parameters,
				onSuccess: callback,
				onComplete: function(transport) {
					if (parent) parent.pb.core.activityMonitor.endTask(task.identifier);
					pb.core.activityMonitor.endTask(task.identifier);
					if (onCompleteCallback) onCompleteCallback(transport);
				}
			});			
		}
		
		pb.core.submissionManager.run('ajaxTask_' + this.identifier,fun,delay);
	},
	
	abort: function() {
		var result = pb.core.submissionManager.abort('ajaxTask_' + this.identifier);
		if (this.request && this.request.transport) {
			//var onComplete = this.request.options.onComplete;
			this.request.transport.onreadystatechange = Prototype.emptyFunction;
			this.request.transport.abort();
			//if (onComplete) onComplete();
			Ajax.activeRequestCount--;
			if (Ajax.activeRequestCount < 0) {
			    Ajax.activeRequestCount = 0;
			}
		}
	}
	
}); // pb_core_AjaxTask

var pb_core_AjaxTaskManager = Class.create(pb_core_ItemManager,{
	
	initialize: function() {
		this.ItemManager();
	},

	addTask: function(task) {
		return this.addItem(task);
	},
		
	getTask: function(identifier) {
		return this.getItem(identifier);
	},
	
	stopTask: function(identifier) {
		var task = this.getItem(identifier);
		if (task) task.abort();
	},

	removeTask: function(identifier) {
		this.removeItem(identifier);
	},
	
	removeItem: function(identifier) {
		var task = this.getItem(identifier);
		if (task) task.abort();
		this.items[identifier] = undefined;
	}
	
}); // pb_core_AjaxTaskManager


var pb_core_DepthManager = Class.create(pb_core_ItemManager,{
	
	minDepth:0,
	maxDepth:100,
	currentDepth:0,
	currentMinDepth:0,
	currentMaxDepth: 100,
	reverse: false,
	fields:null,
	inc: 1,
	
	ignoreItemsZIndex: true,
	
	DepthManager: function(minDepth,maxDepth,reverse){
		
		this.ItemManager();
		
		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();
	},
	
	setIgnoreItemsZIndex: function(ignoreItemsZIndex){
		this.ignoreItemsZIndex = ignoreItemsZIndex;
	},

	getIgnoreItemsZIndex: function(){
		return this.ignoreItemsZIndex;
	},
	
	initialize: function(minDepth,maxDepth,reverse){
		this.DepthManager(minDepth,maxDepth,reverse);
	},
	
	getFrontZIndex: function(){
		return this.currentMaxDepth;
	},
	
	addItem: function($super,item) {
		$super(item);
		this.addItemZIndex(item);
	},

	addItemOfType: function($super,item,type) {
		$super(item,type);
		this.addItemZIndex(item);
	},
	
	addItemZIndex: function(item){
		if (item && item.identifier && item.htmlContainer){
			if (this.ignoreItemsZIndex){
				this.fields[this.currentDepth] = new Array(item.identifier);
				item.setZIndex(this.currentDepth);
				document.fire('ws:zIndex_changed',{ identifier: item.identifier });
				this.incDepth();				
			}
			else {
				var depth = item.getZIndex();
				if (!depth){
					if (this.fields[depth]){
						this.fields[depth].push(item.identifier);
					}
					else {
						this.fields[this.currentDepth] = new Array(item.identifier);
					}
					this.currentDepth = depth;					
				}
				else {
					this.fields[this.currentDepth] = new Array(item.identifier);
					item.setZIndex(this.currentDepth);
					document.fire('ws:zIndex_changed',{ identifier: item.identifier });
					this.incDepth();					
				}
			}
		}
	},

	removeItem: function($super,identifier) {
		$super(identifier);
		if (this.items[identifier]){
			
			var item = this.items[identifier];
			var depth = item.getZIndex();
			var objects = this.fields[depth];
			
			for (var i=0;i<objects.length;i++){
				if (objects[i]==item){
					objects.splice(i,1);
					break;
				}
			}
		}
	},
		
	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){
		
		if (originDepth==destinationDepth) return;
		
		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;
		}		
	}
	
}); // pb_core_DepthManager

var pb_core_ResourceManager = Class.create({

	// TODO Poner iconos de ventanas normales
	getWindowIconTitleLeft: function(){
		return pb.core.system.getLibraryPath() + '/plasticbriqFramework/interfaceFiles/applications/window_title_left.png';
	},
	
	getWindowIconTitleRight: function(){
		return pb.core.system.getLibraryPath() + '/plasticbriqFramework/interfaceFiles/applications/window_title_right.png';
	},
	
	getWindowIconTitleClose: function(){
		return pb.core.system.getLibraryPath() + '/plasticbriqFramework/interfaceFiles/applications/window_close.png';
	},
	
	getHUDWindowIconTitleLeft: function(){
		return pb.core.system.getLibraryPath() + '/plasticbriqFramework/interfaceFiles/applications/hud_title_left.png';
	},
	
	getHUDWindowIconTitleRight: function(){
		return pb.core.system.getLibraryPath() + '/plasticbriqFramework/interfaceFiles/applications/hud_title_right.png';
	},
	
	getHUDWindowIconTitleClose: function(){
		return pb.core.system.getLibraryPath() + '/plasticbriqFramework/interfaceFiles/applications/hud_close.png';
	}
}); // pb_core_ResourceManager

var pb_core_LoaderAnimation = Class.create({
	getLoaderIconURL: function(black) {
		if (black) return pb.core.system.getLibraryPath() + 'plasticbriqFramework/interfaceFiles/images/loading_black.gif';
		else return pb.core.system.getLibraryPath() + 'plasticbriqFramework/interfaceFiles/core/page_loader.gif';
	},
	
	getLoaderContainer: function(id) {
		var loader = document.createElement('div');
		Element.extend(loader);
		loader.id = id;
		loader.className = 'loaderContainer';
		loader.style.backgroundImage = 'url(' + this.getLoaderIconURL() + ')';
		loader.style.marginLeft = 'auto';
		loader.style.marginRight = 'auto';
		loader.style.marginTop = '90px';
		loader.style.width = '32px';
		loader.style.height = '32px';
		return loader;
	},
	
	getLoaderContainerText: function(id,black) {
		var loaderText = '<div id="' + id + '" class="loaderContainer" style="margin-left:auto;margin-right:auto;margin-top:90px;width:32px;height:32px;background:url('
					+ this.getLoaderIconURL(black) + ') no-repeat;"></div>';
		return loaderText;
	}
});

var pb_core_ModalBackground = Class.create({
	
	url: null,
	color: null,
	
	setURL: function(url){
		this.url = url;
	},
	
	setColor: function(color){
		this.color = color;
	},
	
	getColor: function(){
		return this.color;
	},

	getURL: function(){
		return this.url;
	},
	
	getContainer: function(id){
		var container = document.createElement('div');
		Element.extend(container);
		container.id = 'modalBackground';
		if (id) container.id = id;
		container.className = 'modalBackground';
		container.style.backgroundImage = 'url(' + this.getURL() + ')';
		container.style.backgroundColor = this.getColor();
		container.style.width = '100%';
		container.style.height = '100%';
		container.style.position = 'fixed';
		container.style.zIndex = '4900';
		container.style.left = '0';
		container.style.top = '0';
		return container;
	},
	
	getContainerText: function(id) {
		var containerText = '<div ';
		if (id) containerText += 'id="' + id + ' ';
		containerText += 'class="modalBackground" style="background:url('
					+ this.getURL() + ');backgroundColor: '+this.getColor()+';width:100%;height:100%;position: fixed;z-index: 4900;left:0;top:0;"></div>';
		return containerText;
	}
		
}); // pb_core_ModalBackground

var pb_core_ResizeHandle = Class.create({
	url: null,
	
	setURL: function(url){
		this.url = url;
	},
	
	getURL: function(){
		return this.url;
	},
	
	getContainer: function(id){
		var container = document.createElement('div');
		Element.extend(container);
		if (id) container.id = id;
		container.className = 'resizeHandle';
		container.style.backgroundImage = 'url(' + this.getURL() + ')';
		container.style.cursor = 'se-resize';
		container.style.position = 'absolute';
		var image = new Image();
		image.src = this.getURL();
		if (image.width){
			container.style.width = image.width + 'px';
			container.style.height = image.height + 'px';
		}

		return container;
	},
	
	getContainerText: function(id){
		var containerText = '<div ';
		if (id) containerText += 'id="' + id + ' ';
		
		var image = new Image();
		image.src = this.getURL();
		
		containerText += 'class="resizeHandle" style="background:url('
					+ this.getURL() + ');position: absolute;cursor: se-resize;';

		if (image.width){
			containerText += 'width:' + image.width + 'px;height:' + image.height + 'px';
		}
		
		containerText += "></div>";
		
		return containerText;
	}
	
}); // pb_core_ResizeHandle


var pb_core_BrowserWindow = Class.create({
	
	getWidth: function() {
		var width = 0;
		if( document.documentElement && document.documentElement.clientWidth ) {
			width = document.documentElement.clientWidth;
		}
		else if( typeof( window.innerWidth ) == 'number' ) {
			width = window.innerWidth;
		}
		else if( document.body && document.body.clientWidth ) {
			width = document.body.clientWidth;
		}
		return width;
	},
	
	getHeight: function() {
		var height = 0;
		if( document.documentElement && document.documentElement.clientHeight ) {
			height = document.documentElement.clientHeight;
		}
		else if( typeof( window.innerHeight ) == 'number' ) {
			height = window.innerHeight;
		}
		else if( document.body && document.body.clientHeight ) {
			height = document.body.clientHeight;
		}
		return height;
	},
	
		getScreenSize: function(){
		return [ screen.availWidth, screen.availHeight ];
	},
	
	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
			var size = document.viewport.getScrollOffsets();
			scrOfY = size[0];
			scrOfX = size[1];
		} 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 ];
	}
}); // pb_core_BrowserWindow

var pb_core_UserAccount = Class.create({
	loadFullUserName: function(nickname,destContainer,useInnerHTML) {
		pb.core.actions.executeAndPutResultIntoContainer(pb.core.system.getLibraryPath() + 'plasticbriqFramework/core/_session.php',
					'loadUserName',{nickname:nickname},destContainer,useInnerHTML);
	}
}); // pb_core_UserAccount

var pb_core_Notification = Class.create({
	category:'',
	sourceType:'',
	sourceId:'',
	title:'',
	description:'',
	params:'',

	Notification: function(category,sourceType,sourceId,title,description,params) {
		this.category = category;
		this.sourceType = sourceType;
		this.sourceId = sourceId;
		this.title = title;
		this.description = description;
		this.params = params;
	},

	initialize: function(category,sourceType,sourceId,title,text,params) {
		this.Notification(category,sourceType,sourceId,title,text,params);
	}
});

var pb_core_NotificationManager = Class.create({
	send: function(notification) {
		var params = Object();
		params.category = notification.category;
		params.sourceType = notification.sourceType;
		params.sourceId = notification.sourceId;
		params.title = notification.title;
		params.description = notification.description;
		params.params = notification.params;

		pb.core.actions.execute(pb.core.system.getLibraryPath() + 'plasticbriqFramework/core/_notification_api.php',
				'send',params,
				function(responseText) {
					// En principio no hay que hacer nada
				});
	}
}); // pb_core_NotificationManager

var pb_core_CSSUtils = Class.create({
	
	effects: null,
	
	initialize: function () {
		this.effects = new Object();
	},
	
	addPx: function(value){
		return this.fixCSSUnit(value,true);		
	},
	
	getLeft: function(node){
		if (node.offsetLeft) return node.offsetLeft;
		else return (parseInt(node.style.left)||0);
	},
	
	getTop: function(node){
		if (node.offsetTop) return node.offsetTop;
		else return (parseInt(node.style.top)||0);
	},
	
	getWidth: function(node){
		if (!node) return null;
		
		if (node.style.width=="") return node.offsetWidth;
		
		// var w = node.offsetWidth;
		// if (!w){
			w = node.style.width;
			if (w){
				w = (parseInt(w)||0);
				var lw = this.getLeftExtraWidth(node);
				var rw = this.getRightExtraWidth(node);
				return (w+lw+rw);
			}
			return 0;
		// }
		// return w;
	},
	
	setWidth: function(node,value){
		var w = node.offsetWidth;
		var innerW = node.style.width;
		if (w && innerW){
			var offset = w-(parseInt(innerW)||0);
			//pb.core.console.log('offset ' + offset)
			node.style.width = (value-offset) + 'px';
		}
		else {
			var lw = this.getLeftExtraWidth(node);
			var rw = this.getRightExtraWidth(node);
			node.style.width = (value-lw-rw) + 'px';
		}
	},
	
	getHeight: function(node){
		if (!node) return null;
		
		if (node.style.height=='') {
			if (node.offsetHeight<parseInt(node.style.minHeight)) {
				h = (parseInt(node.style.minHeight)||0);
				var th = this.getTopExtraHeight(node);
				var bh = this.getBottomExtraHeight(node);
				return (h+th+bh);
			}
			else if (node.offsetHeight>parseInt(node.style.maxHeight)) {
				h = (parseInt(node.style.maxHeight)||0);
				var th = this.getTopExtraHeight(node);
				var bh = this.getBottomExtraHeight(node);
				return (h+th+bh);
			}
			return node.offsetHeight;
		}
		
		h = node.style.height;
		if (h){
			h = (parseInt(h)||0);
			var th = this.getTopExtraHeight(node);
			var bh = this.getBottomExtraHeight(node);
			return (h+th+bh);
		}
		return 0;
	},
	
	setHeight: function(node,value){
		var h = node.offsetHeight;
		var innerH = node.style.height;
		if (h && innerH){
			var offset = h-(parseInt(innerH)||0);
			node.style.height = (value-offset) + 'px';
		}
		else {
			var th = this.getTopExtraHeight(node);
			var bh = this.getBottomExtraHeight(node);
			node.style.height = (value-th-bh) + 'px';
		}
	},
	
	getLeftExtraWidth: function(node){
		var w = 0;

		if (node.style.paddingLeft) {
			w += (parseInt(node.style.paddingLeft)||0);
		}
		
		if (node.style.borderLeftWidth && (node.style.borderLeftStyle!='none')) {
			w += (parseInt(node.style.borderLeftWidth)||0);
		}
		
		return w;
	},
	
	getRightExtraWidth: function(node){
		var w = 0;

		if (node.style.paddingRight) {
			w += (parseInt(node.style.paddingRight)||0);
		}
		
		if (node.style.borderRightWidth && (node.style.borderRightStyle!='none')) {
			w += (parseInt(node.style.borderRightWidth)||0);
		}
		
		return w;
	},
	
	getTopExtraHeight: function(node){
		var h = 0;

		if (node.style.paddingTop) {
			h += (parseInt(node.style.paddingTop)||0);
		}
		
		if (node.style.borderTopWidth && (node.style.borderTopStyle!='none')) {
			h += (parseInt(node.style.borderTopWidth)||0);
		}
		
		return h;
	},
	
	getBottomExtraHeight: function(node){
		var h = 0;

		if (node.style.paddingBottom) {
			h += (parseInt(node.style.paddingBottom)||0);
		}
		
		if (node.style.borderBottomWidth && (node.style.borderBottomStyle!='none')) {
			h += (parseInt(node.style.borderBottomWidth)||0);
		}
		
		return h;
	},
	
	getMarginLeft: function(node){
		return (parseInt(node.style.marginLeft)||0);
	},

	getMarginRight: function(node){
		return (parseInt(node.style.marginRight)||0);
	},


	getMarginTop: function(node){
		return (parseInt(node.style.marginTop)||0);
	},

	getMarginBottom: function(node){
		return (parseInt(node.style.marginBottom)||0);
	},
	
	getCSSUnit: function(value){
		var unit = value.substr(value.length-2);
		if (unit=='px' || unit=='pt' || unit=='pc' || unit=='ex' || unit=='in' || unit=='cm' || unit=='mm' || unit=='em'){
			return unit;
		}
		else if (value.substr(value.length-1)=='%') return '%';
		return '';
	},
	
	getCSSValue: function(value){
		if (parseInt(value)==NaN){
			return value;
		}
		else return parseInt(value);
	},
	
	addCSSUnit: function(value) {
		return this.fixCSSUnit(value,true,true,true,true,true,true,true,true,true);
	},
		
	fixCSSUnit: function(value,allowPx,allowPercent,allowPt,allowPc,allowEx,allowIn,allowCm,allowMm,allowEm) {
		value = new String(value);
		value = value.toLowerCase();
		var unit = 'px';

		if (value=='') {
			return;
		}

		if (allowPx && value.indexOf('px')!=-1) {
			value = value.substr(0,value.length-2);
		}
		else if (allowPercent && value.indexOf('%')!=-1) {
			value = value.substr(0,value.length-1);
			unit = '%';
		}
		else if (allowPt && value.indexOf('pt')!=-1) {
			value = value.substr(0,value.length-2);
			unit = 'pt';
		}
		else if (allowPc && value.indexOf('pc')!=-1) {
			value = value.substr(0,value.length-2);
			unit = 'pc';
		}
		else if (allowEx && value.indexOf('ex')!=-1) {
			value = value.substr(0,value.length-2);
			unit = 'ex';
		}
		else if (allowIn && value.indexOf('in')!=-1) {
			value = value.substr(0,value.length-2);
			unit = 'in';
		}
		else if (allowCm && value.indexOf('cm')!=-1) {
			value = value.substr(0,value.length-2);
			unit = 'cm';
		}
		else if (allowMm && value.indexOf('mm')!=-1) {
			value = value.substr(0,value.length-2);
			unit = 'mm';
		}
		else if (allowEm && value.indexOf('em')!=-1) {
			value = value.substr(0,value.length-2);
			unit = 'em';
		}
		else if (parseInt(value)!=NaN) {
			value = parseInt(value);
			unit = 'px';
		}
		else if (parseInt(value.substr(0,length-1))!=NaN) {	// Por si se ha puesto % pero no se permite usar esa medida
			value=parseInt(value.substr(0,length-1));
			unit = 'px';
		}
		else {	// En el resto de los casos, intentamos substituir cualquier otra medida, que tienen todas dos caracteres de longitud
			value = value.substr(0,value.length-2);
			unit = 'px';
		}

		if (parseInt(value)==NaN) {
			value = '0';
		}
	
		return value + unit;
	},
	
	switchToLeftCoords: function(rightPos){
		return (pb.core.browserWindow.getWidth() - rightPos) + 'px';
	},
	
	switchToRightCoords: function(leftPos){
		return (pb.core.browserWindow.getWidth() - leftPos) + 'px';
	},
	
	switchToTopCoords: function(bottomPos){
		return (pb.core.browserWindow.getHeight() - bottomPos) + 'px';
	},

	switchToBottomCoords: function(topPos){
		return (pb.core.browserWindow.getHeight() - topPos) + 'px';
	},
	
	calculateLeftPosFromRight: function(node){
		var rightPos = node.offsetRight;
		if (!rightPos) rightPos = (parseInt(node.style.right)||0);
		return this.calculateLeftPosFromRightPos(rightPos,node.offsetWidth);
	},
	
	calculateLeftPosFromRightPos: function(rightPos,width){
		//pb.core.console.log('calculateLeftPosFromRightPos ' + pb.core.browserWindow.getWidth() + ' ' + rightPos + ' ' + width);
		return (pb.core.browserWindow.getWidth() - rightPos - width) + 'px';
	},
	
	calculateRightPosFromLeft: function(node){ // Calcular posición derecha a partir de la izquierda
		//pb.core.console.log('calculateRightPosFromLeft');
		var leftPos = node.offsetLeft;
		if (!leftPos) leftPos = (parseInt(node.style.left)||0);
		//pb.core.console.log(pb.core.browserWindow.getWidth() + ' ' + leftPos + ' ' + node.offsetWidth);
		return this.calculateRightPosFromLeftPos(leftPos,node.offsetWidth);
	},
	
	calculateRightPosFromLeftPos: function(leftPos,width){
		return (pb.core.browserWindow.getWidth() - leftPos - width) + 'px';
	},
	
	calculateTopPosFromBottom: function(node){
		var bottomPos = node.offsetBottom;
		if (!bottomPos) bottomPos = (parseInt(node.style.bottom)||0);
		return this.calculateTopPosFromBottomPos(bottomPos,node.offsetHeight);
	},
	
	calculateTopPosFromBottomPos: function(bottomPos,height){
		return (pb.core.browserWindow.getHeight() - bottomPos - height) + 'px';
	},
	
	calculateBottomPosFromTop: function(node){
		var topPos = node.offsetTop;
		if (!topPos) topPos = (parseInt(node.style.top)||0);
		return this.calculateBottomPosFromTopPos(topPos,node.offsetHeight);
	},
	
	calculateBottomPosFromTopPos: function(topPos,height) {
		return (pb.core.browserWindow.getHeight() - topPos - height) + 'px';
	},
	
	getOffsetRight: function(node){
		if ((node.getAttribute('anchorLeft')=='both') || (node.getAttribute('anchorLeft')=='right')){
			return (parseInt(node.style.right)||'');
		}
		else {
			return (node.offsetLeft + node.offsetWidth);			
		}
	},
	
	getOffsetBottom: function(node){
		var top = node.offsetTop;
		return (top + node.offsetHeight);
	},
	
	morphToStyle: function(node,style,duration,dontFireEvent){
		
		if (this.effects[node.id]) {
			this.effects[node.id].cancel();
		}
		
		if (!duration || duration==0) return this.setStyle(node,style,dontFireEvent);
		
		var aux = style.parseStyle();		
		
		if (!duration) duration = 0.1;
		
		var aux = this.setStyle.bind(this);
		var setStyle = function () { aux(node,style,dontFireEvent); };
		this.effects[node.id] = new Effect.Morph(node,{style: style,afterFinish: setStyle, duration: duration});
	},
	
	setStyle: function(node,style,dontfireEvent) {
		node.setAttribute('style',style);
		if (!dontfireEvent) node.fire('ws:style_changed',{ style: style });
	},
	
	addStyles: function(style,baseStyle) {
		if (!style) return baseStyle;
		if (!baseStyle) return style;
		var baseStyleObject = pb.core.cssUtils.styleToObject(baseStyle);
		var styleObject = pb.core.cssUtils.styleToObject(style);
		
		styleObject = pb.core.cssUtils.addStyle(styleObject,baseStyleObject);
		
		return pb.core.cssUtils.objectToStyle(styleObject);		
	},
	
	setIncrementalStyle: function(node,style,baseStyle,dontfireEvent) {
		var finalStyle = pb.core.cssUtils.addStyles(style,baseStyle);
		
		node.setAttribute('style',finalStyle);
		if (!dontfireEvent) node.fire('ws:style_changed',{ style: finalStyle });
	},
	
	parseBackgroundImage: function(style){
		var results = (/.*background-image:\s*url\((.*?)\);.*/g).exec(style);
		
		if (results) return results[1];
		return null;
	},
	
	parseDisplay: function(style){
		var results = (/.*display:\s*['"](.*?)['"];.*/g).exec(style);
		
		if (results) return results[1];
		return null;
	},
	
	getAlignment: function(node) {
		var oldAlignment = '';
		if (node.descendantOf('externalRelativeContainer')) { // Hace falta para diseñar el menú. Se mete en un contenedor y ese es al que le cambiamos la alineación
			return 'center';
		}
		else {
			return 'free';
		}
	},
	
	setAlignment: function(node,value) {
		var oldAlignment = this.getAlignment(node);
		if (oldAlignment===value) return;
		
		if (value=='center') {
			$('externalRelativeContainer').appendChild(node.remove());
			
			var w = this.getWidth($('externalRelativeContainer'));
			var nodeW = this.getWidth(node);
			
			node.style.left = ((w/2)-(nodeW/2)) + 'px';
		}
		else {
			$('mainWebsiteContainer').appendChild(node.remove());
		}
	},
	
 	fixColorValue: function(value) {
		if (value!='' && value!='transparent' && value.substr(0,3)!='rgb' && value.substr(0,1)!='#') value = '#' + value;
		return value;
	},
	
	getPosition: function(node){
		if (node.parentNode.id=='PageContainerAnchor') {
			return 'pageContainer';
		}
		else if (node.parentNode.id=='externalRelativeContainer') {
			return 'center';
		}
		else if (node.style.position=='fixed') {
			return node.style.position;
		}
		else if (node.style.position=='absolute') {
			return node.style.position;
		}
		else return 'absolute';
	},
	
	setPosition: function(node,value) {
		if (value=='absolute') {
			$('mainWebsiteContainer').appendChild(node.remove());			
		}	
		else if (value=='fixed') {
			$('mainWebsiteContainer').appendChild(node.remove());
		}
		else if (value=='center') {
			$('externalRelativeContainer').appendChild(node.remove());
		}
		else if (value=='pageContainer') {
			$('PageContainerAnchor').appendChild(node.remove());
		}
	},
	
	addStyle: function(style1,style2) {
		var oldValue = null;
		if (style1.left && style2.left) {
			oldValue = style2.left;
			style2.left = (parseInt(style1.left) + parseInt(style2.left)) + this.getCSSUnit(style2.left);
			if (isNaN(parseInt(style2.left))) style2.left = oldValue;
		}

		if (style1.top && style2.top) {
			oldValue = style2.top;
			style2.top = (parseInt(style1.top) + parseInt(style2.top)) + this.getCSSUnit(style2.top);
			if (isNaN(parseInt(style2.top))) style2.top = oldValue;
		}

		if (style1.right && style2.right) {
			oldValue = style2.right;
			style2.right = (parseInt(style1.right) + parseInt(style2.right)) + this.getCSSUnit(style2.right);
			if (isNaN(parseInt(style2.right))) style2.right = oldValue;
		}
		
		if (style1.bottom && style2.bottom) {
			oldValue = style2.bottom;
			style2.bottom = (parseInt(style1.bottom) + parseInt(style2.bottom)) + this.getCSSUnit(style2.bottom);
			if (isNaN(parseInt(style2.bottom))) style2.bottom = oldValue;
		}
		
		if (style1.width && style2.width) {
			oldValue = style2.width;
			style2.width = (parseInt(style1.width) + parseInt(style2.width)) + this.getCSSUnit(style2.width);
			if (isNaN(parseInt(style2.width))) style2.width = oldValue;
		}
		
		if (style1.height && style2.height) {
			oldValue = style2.height;
			style2.height = (parseInt(style1.height) + parseInt(style2.height)) + this.getCSSUnit(style2.height);
			if (isNaN(parseInt(style2.height))) style2.height = oldValue;
		}
		
		if (style1['min-width'] && style2['min-width']) {
			oldValue = style2['min-width'];
			style2['min-width'] = (parseInt(style1['min-width']) + parseInt(style2['min-width'])) + this.getCSSUnit(style2['min-width']);
			if (isNaN(parseInt(style2['min-width']))) style2['min-width'] = oldValue;
		}
		
		if (style1['min-height'] && style2['min-height']) {
			oldValue = style2['min-height'];
			style2['min-height'] = (parseInt(style1['min-height']) + parseInt(style2['min-height'])) + this.getCSSUnit(style2['min-height']);
			if (isNaN(parseInt(style2['min-height']))) style2['min-height'] = oldValue;
		}
		
		if (style1['max-width'] && style2['max-width']) {
			oldValue = style2['max-width'];
			style2['max-width'] = (parseInt(style1['max-width']) + parseInt(style2['max-width'])) + this.getCSSUnit(style2['max-width']);
			if (isNaN(parseInt(style2['max-width']))) style2['max-width'] = oldValue;
		}

		if (style1['max-height'] && style2['max-height']) {
			oldValue = style2['max-height'];
			style2['max-height'] = (parseInt(style1['max-height']) + parseInt(style2['max-height'])) + this.getCSSUnit(style2['max-height']);
			if (isNaN(parseInt(style2['max-height']))) style2['max-height'] = oldValue;
		}
		
		if (style1['margin-left'] && style2['margin-left']) {
			oldValue = style2['margin-left'];
			style2['margin-left'] = (parseInt(style1['margin-left']) + parseInt(style2['margin-left'])) + this.getCSSUnit(style2['margin-left']);
			if (isNaN(parseInt(style2['margin-left']))) style2['margin-left'] = oldValue;
		}

		if (style1['margin-top'] && style2['margin-top']) {
			oldValue = style2['margin-top'];
			style2['margin-top'] = (parseInt(style1['margin-top']) + parseInt(style2['margin-top'])) + this.getCSSUnit(style2['margin-top']);
			if (isNaN(parseInt(style2['margin-top']))) style2['margin-top'] = oldValue;
		}		

		if (style1['margin-right'] && style2['margin-right']) {
			oldValue = style2['margin-right'];
			style2['margin-right'] = (parseInt(style1['margin-right']) + parseInt(style2['margin-right'])) + this.getCSSUnit(style2['margin-right']);
			if (isNaN(parseInt(style2['margin-right']))) style2['margin-right'] = oldValue;
		}

		if (style1['margin-bottom'] && style2['margin-bottom']) {
			oldValue = style2['margin-bottom'];
			style2['margin-bottom'] = (parseInt(style1['margin-bottom']) + parseInt(style2['margin-bottom'])) + this.getCSSUnit(style2['margin-bottom']);
			if (isNaN(parseInt(style2['margin-bottom']))) style2['margin-bottom'] = oldValue;
		}
		
		if (style1['padding-left'] && style2['padding-left']) {
			oldValue = style2['padding-left'];
			style2['padding-left'] = (parseInt(style1['padding-left']) + parseInt(style2['padding-left'])) + this.getCSSUnit(style2['padding-left']);
			if (isNaN(parseInt(style2['padding-left']))) style2['padding-left'] = oldValue;
		}

		if (style1['padding-top'] && style2['padding-top']) {
			oldValue = style2['padding-top'];
			style2['padding-top'] = (parseInt(style1['padding-top']) + parseInt(style2['padding-top'])) + this.getCSSUnit(style2['padding-top']);
			if (isNaN(parseInt(style2['padding-top']))) style2['padding-top'] = oldValue;
		}		

		if (style1['padding-right'] && style2['padding-right']) {
			oldValue = style2['padding-right'];
			style2['padding-right'] = (parseInt(style1['padding-right']) + parseInt(style2['padding-right'])) + this.getCSSUnit(style2['padding-right']);
			if (isNaN(parseInt(style2['padding-right']))) style2['padding-right'] = oldValue;
		}

		if (style1['padding-bottom'] && style2['padding-bottom']) {
			oldValue = style2['padding-bottom'];
			style2['padding-bottom'] = (parseInt(style1['padding-bottom']) + parseInt(style2['padding-bottom'])) + this.getCSSUnit(style2['padding-bottom']);
			if (isNaN(parseInt(style2['padding-bottom']))) style2['padding-bottom'] = oldValue;
		}
		
		if (style1.opacity && style2.opacity) {
			oldValue = style2.opacity;
			style2.opacity = (parseFloat(style1.opacity) + parseFloat(style2.opacity));
			if (isNaN(parseInt(style2.opacity))) style2.opacity = oldValue;
		}
		
		if (style1['background-image']) {
			style2['background-image'] = style1['background-image'];
		}
		
		if (style1['background-position']) {
			style2['background-position'] = style1['background-position'];
		}
		
		if (style1['background-repeat']) {
			style2['background-repeat'] = style1['background-repeat'];
		}
		
		if (style1['cursor']) {
			style1['cursor'] = style1['cursor'];
		}
		
		return style2;
	},
	
	styleToObject: function(style) {
		var parsedStyle = style.replace(/,/g,'$');
		parsedStyle = parsedStyle.replace(/;/g,',');
		parsedStyle = '{' + parsedStyle + '}';
		parsedStyle = parsedStyle.replace(/\s/g,'');
		parsedStyle = parsedStyle.replace(/,\s*\}/g,'" }');
		parsedStyle = parsedStyle.replace(/:(?!\/)/g,'":"');
		parsedStyle = parsedStyle.replace(/\{/g,'{ "');
		parsedStyle = parsedStyle.replace(/,/g,'", "');
		return parsedStyle.evalJSON();		
	},
	
	objectToStyle: function(styleObject) {
		var style = Object.toJSON(styleObject);
		style = style.replace(/\s/g,'');
		style = style.replace(/\{/g,'');
		style = style.replace(/\}/g,'');
		style = style.replace(/,/g,';');
		style = style.replace(/\$/g,',');
		style = style.replace(/"/g,'');
		return style;
	}
	
}); // pb_core_CSSUtils


// Propiedades de un elemento, ya sea bloque, contenedor genérico, o lo que sea
var pb_core_ItemProperties = Class.create({ 
	
	identifier: null,
	style: '',
	hoverStyle: '',
	selectedStyle: '',
	node: null,
	
	ItemProperties: function(identifier,style,hoverStyle,selectedStyle){
		this.identifier = identifier;
		this.style = style;
		this.hoverStyle = hoverStyle;
		this.selectedStyle = selectedStyle;
		
		this.node = $(this.identifier);
	},
	
	initialize: function(identifier,style,hoverStyle,selectedStyle){
		this.ItemProperties(identifier,style,hoverStyle,selectedStyle);
	}
	
}); // pb_core_ItemProperties

var pb_core_ItemEventController = Class.create(pb_core_Node,{
	
	identifier: null,
	normalStyle: null,
	hoverStyle: null,
	pushedStyle: null,

	hoverStyleDif: null,
	pushedStyleDif: null,
	
	disabled: false,
	locked: false,
	
	ItemEventController: function(identifier,normalStyle) {
		
		this.Node(identifier);
		
		this.normalStyle = normalStyle;
		
		if (this.htmlContainer) {
			var field = this.htmlContainer;
						
			field.observe('mouseover',this.mouseOver.bind(this));
			field.observe('mouseout',this.mouseOut.bind(this));
			field.observe('mousedown',this.mouseDown.bind(this));
			field.observe('mouseup',this.mouseUp.bind(this));

			var obj = this;
			var disableControllerFun = function () { obj.disabled = true; }; 
			var lockControllerFun = function () { obj.locked = true; }; 

			field.observe('ws:visibility_changing',lockControllerFun);
			field.observe('ws:visibility_changed',this.updateVisibility.bind(this));

			field.observe('ws:changing_style',disableControllerFun);
			field.observe('ws:style_changed',function(event){ obj.setStyle(event.memo.style); });
			
			
			field.observe('ws:width_changed',this.updateWidth.bind(this));
			field.observe('ws:height_changed',this.updateHeight.bind(this));
			
			field.observe('ws:animation_started',this.disableEvents.bind(this));
			field.observe('ws:animation_stopped',this.enableEvents.bind(this));
		}
	},
	
	enableEvents: function() {
		this.disabled = false;
		this.updateStyles();
	},
	
	disableEvents: function() {
		this.disabled = true;
	},
	
	updateStyles: function() {
		this.performSetHoverStyle(this.hoverStyleDif);
		this.performSetPushedStyle(this.pushedStyleDif);
	},
	
	setHoverStyle: function(style) {
		if (this.normalStyle!=style) this.performSetHoverStyle(style);
		else this.hoverStyle = null; // Si es el mismo estilo mejor no hacemos nada con los eventos
	},
	
	setPushedStyle: function(style) {
		if (this.normalStyle!=style) this.performSetPushedStyle(style);
		else this.pushedStyle = null; // Si es el mismo estilo mejor no hacemos nada con los eventos
	},
	
	performSetHoverStyle: function(style) {
		if (!this.normalStyle) return;
		
		this.hoverStyle = pb.core.cssUtils.addStyles(style,this.normalStyle);
		this.hoverStyleDif = style;
		
		// var baseStyleObject = pb.core.cssUtils.styleToObject(this.normalStyle);
		// 
		// var baseStyle = this.normalStyle.replace(/;/g,',');
		// baseStyle = '{' + baseStyle + '}';
		// baseStyle = baseStyle.replace(/,\s*\}/g,'" }');
		// baseStyle = baseStyle.replace(/:/g,'":"');
		// baseStyle = baseStyle.replace(/\{/g,'{ "');
		// baseStyle = baseStyle.replace(/,/g,'", "');
		// var baseStyleObject = baseStyle.evalJSON();
		// 
		// var hoverStyle = style.replace(/;/g,',');
		// hoverStyle = '{' + hoverStyle + '}';
		// hoverStyle = hoverStyle.replace(/,\s*\}/g,'" }');
		// hoverStyle = hoverStyle.replace(/:/g,'":"');
		// hoverStyle = hoverStyle.replace(/\{/g,'{ "');
		// hoverStyle = hoverStyle.replace(/,/g,'", "');
		// var hoverStyleObject = hoverStyle.evalJSON();
		// 
		// hoverStyleObject = pb.core.cssUtils.addStyle(hoverStyleObject,baseStyleObject);
		// 
		// this.hoverStyle = Object.toJSON(hoverStyleObject);
		// this.hoverStyle = this.hoverStyle.replace(/\{/g,'');
		// this.hoverStyle = this.hoverStyle.replace(/\}/g,'');
		// this.hoverStyle = this.hoverStyle.replace(/,/g,';');
		// this.hoverStyle = this.hoverStyle.replace(/"/g,'');
	},
	
	performSetPushedStyle: function(style) {
		if (!this.normalStyle) return;

		this.pushedStyle = pb.core.cssUtils.addStyles(style,this.normalStyle);
		this.pushedStyleDif = style;
	},
	
	mouseOver: function() {
		if (this.disabled || this.locked) return;
		if (this.hoverStyle) pb.core.cssUtils.morphToStyle(this.htmlContainer,this.hoverStyle,0,true);
	},
	
	mouseOut: function() {
		if (this.disabled || this.locked) return;
		if (this.hoverStyle) pb.core.cssUtils.morphToStyle(this.htmlContainer,this.normalStyle,0,true);		
	},
	
	mouseDown: function() {
		if (this.disabled || this.locked) return;
		if (this.pushedStyle) pb.core.cssUtils.morphToStyle(this.htmlContainer,this.pushedStyle,0,true);
	},
	
	mouseUp: function() {
		if (this.disabled || this.locked) return;
		if (this.hoverStyle) pb.core.cssUtils.morphToStyle(this.htmlContainer,this.hoverStyle,0,true);
		else pb.core.cssUtils.morphToStyle(this.htmlContainer,this.normalStyle,0,true);
	},
	
	updateVisibility: function(event) {
		this.locked = false;

		if (this.disabled) return;
		var visible = (this.htmlContainer.style.display!='none');
		var regExp = /display:(.)*?;/ig;
		
		this.normalStyle = this.normalStyle.replace(regExp,'');
		if (visible) this.normalStyle += 'display: block;';
		else this.normalStyle += 'display: none;';
		
		if (this.hoverStyle) {
			this.hoverStyle = this.hoverStyle.replace(regExp,'');
			if (visible) this.hoverStyle += 'display: block;';
			else this.hoverStyle += 'display: none;';
		}
		if (this.pushedStyle){
			this.pushedStyle = this.pushedStyle.replace(regExp,'');	
			if (visible) this.pushedStyle += 'display: block;';
			else this.pushedStyle += 'display: none;';
		}
	},
	
	updateWidth: function(event) {
		this.locked = false;

		if (this.disabled) return;
		var width = 'width:' + this.htmlContainer.style.width + 'px';
		var regExp = /width:(.)*?;/ig;
		
		this.normalStyle = this.normalStyle.replace(regExp,'');
		this.normalStyle += width;
		
		if (this.hoverStyle) {
			this.hoverStyle = this.hoverStyle.replace(regExp,'');
			this.hoverStyle += width;
		}
		if (this.pushedStyle){
			this.pushedStyle = this.pushedStyle.replace(regExp,'');	
			this.pushedStyle += width;
		}
	},
	
	updateHeight: function(event) {
		this.locked = false;

		if (this.disabled) return;
		var height = 'height:' + this.htmlContainer.style.height + 'px';
		var regExp = /height:(.)*?;/ig;
		
		this.normalStyle = this.normalStyle.replace(regExp,'');
		this.normalStyle += height;
		
		if (this.hoverStyle) {
			this.hoverStyle = this.hoverStyle.replace(regExp,'');
			this.hoverStyle += height;
		}
		if (this.pushedStyle){
			this.pushedStyle = this.pushedStyle.replace(regExp,'');	
			this.pushedStyle += height;
		}
	},
		
	initialize: function(identifier,normalStyle) {
		this.ItemEventController(identifier,normalStyle);
	},
	
	setStyle: function(style) {
		this.normalStyle = style;
		this.hoverStyle = null;
		this.pushedStyle = null;
	}
	
}); // pb_core_ItemEventController

var pb_core_ContainerEventController = Class.create(pb_core_Node,{
	
	identifier: null,
	normalStyle: null,
	hoverStyle: null,
	pushedStyle: null,
	
	hoverStyleDif: null,
	pushedStyleDif: null,
	
	pageNormalStyle: null,
	pageHoverStyle: null,
	pagePushedStyle: null,
	
	pageHoverStyleDif: null,
	pagePushedStyleDif: null,
	
	disabled: false,
	locked: false,
	
	updateStyle: false,
	
	initialize: function(identifier,normalStyle) {
		this.ContainerEventController(identifier,normalStyle);
	},
	
	ContainerEventController: function(identifier,normalStyle) {
		
		this.Node(identifier);
		
		this.normalStyle = normalStyle;
		
		var updateStyle = this.updateStyle.bind(this);
		document.observe('ws:style_changed',updateStyle);
		
		if (this.htmlContainer) {
			var field = this.htmlContainer;
						
			field.observe('mouseover',this.mouseOver.bind(this));
			field.observe('mouseout',this.mouseOut.bind(this));
			field.observe('mousedown',this.mouseDown.bind(this));
			field.observe('mouseup',this.mouseUp.bind(this));

			var obj = this;
			var disableControllerFun = function () { obj.disabled = true; }; 
			var lockControllerFun = function () { obj.locked = true; }; 

			field.observe('ws:visibility_changing',lockControllerFun);
			field.observe('ws:visibility_changed',this.updateVisibility.bind(this));

			field.observe('ws:changing_style',disableControllerFun);
			field.observe('ws:style_changed',function(event){ obj.setStyle(event.memo.style); });
			
			
			field.observe('ws:width_changed',this.updateWidth.bind(this));
			field.observe('ws:height_changed',this.updateHeight.bind(this));

			field.observe('ws:animation_started',this.disableEvents.bind(this));
			field.observe('ws:animation_stopped',this.enableEvents.bind(this));
		}
	},
	
	enableEvents: function() {
		this.disabled = false;
		this.updateStyles();
	},
	
	disableEvents: function() {
		this.disabled = true;
	},
	
	updateStyle: function(event) {
		if (this.identifier!=event.memo.id) return;
		if (this.pageNormalStyle) this.pageNormalStyle = event.memo.style;
		else this.normalStyle = event.memo.style;
	},
	
	setPageNormalStyle: function(style) {
		if (style==null) {
			this.pageNormalStyle = null;
			//this.pageHoverStyle = null;
			//this.pagePushedStyle = null;
			if (this.updateStyle) pb.core.cssUtils.morphToStyle(this.htmlContainer,this.normalStyle,0,true);
			this.updateStyle = false;
		}
		else if (this.normalStyle!=style) {
			this.updateStyle = true;
			this.pageNormalStyle = style;
			pb.core.cssUtils.morphToStyle(this.htmlContainer,this.pageNormalStyle,0,true);
		}
		else {
			this.pageNormalStyle = null;
			this.updateStyle = true;
			pb.core.cssUtils.morphToStyle(this.htmlContainer,this.normalStyle,0,true);
		}
		this.updateStyles();
	},
	
	updateStyles: function() {
		this.performSetHoverStyle(this.hoverStyleDif);
		this.performSetPushedStyle(this.pushedStyleDif);
		this.performSetPageHoverStyle(this.pageHoverStyleDif);
		this.performSetPagePushedStyle(this.pagePushedStyleDif);
	},
	
	setHoverStyle: function(style) {
		this.hoverStyleDif = style;
 		this.performSetHoverStyle(style);
	},
	
	setPageHoverStyle: function(style) {
		this.pageHoverStyleDif = style;
		this.performSetPageHoverStyle(style);
	},
	
	
	setPushedStyle: function(style) {
		if (style!=null) this.hoverPushedDif = style;
 		this.performSetPushedStyle(style);
	},

	setPagePushedStyle: function(style) {
		this.pagePushedStyleDif = style;
		this.performSetPagePushedStyle(style);
	},	
	
	performSetHoverStyle: function(style) {
		if (this.pageNormalStyle) this.hoverStyle = pb.core.cssUtils.addStyles(style,this.pageNormalStyle);
		else if (this.normalStyle) this.hoverStyle = pb.core.cssUtils.addStyles(style,this.normalStyle);
	},
	
	performSetPushedStyle: function(style) {
		if (this.pageNormalStyle) this.pushedStyle = pb.core.cssUtils.addStyles(style,this.pageNormalStyle);
		else if (this.normalStyle) this.pushedStyle = pb.core.cssUtils.addStyles(style,this.normalStyle);
	},
	
	performSetPageHoverStyle: function(style) {
		if (this.pageNormalStyle) this.pageHoverStyle = pb.core.cssUtils.addStyles(style,this.pageNormalStyle);
		else if (this.normalStyle) this.pageHoverStyle = pb.core.cssUtils.addStyles(style,this.normalStyle);
	},

	performSetPagePushedStyle: function(style) {
		if (this.pageNormalStyle) this.pagePushedStyle = pb.core.cssUtils.addStyles(style,this.pageNormalStyle);
		else if (this.normalStyle) this.pagePushedStyle = pb.core.cssUtils.addStyles(style,this.normalStyle);
	},
	
	mouseOver: function() {
		if (this.disabled || this.locked) return;
		if (this.pageHoverStyle) pb.core.cssUtils.morphToStyle(this.htmlContainer,this.pageHoverStyle,0,true);
		else if (this.hoverStyle && !this.pageNormalStyle) pb.core.cssUtils.morphToStyle(this.htmlContainer,this.hoverStyle,0,true);
	},
	
	mouseOut: function() {
		if (this.disabled || this.locked) return;
		if (this.pageHoverStyle || this.hoverStyle) {
			if (this.pageNormalStyle) pb.core.cssUtils.morphToStyle(this.htmlContainer,this.pageNormalStyle,0,true);
			else pb.core.cssUtils.morphToStyle(this.htmlContainer,this.normalStyle,0,true);
		}
	},
	
	mouseDown: function() {
		if (this.disabled || this.locked) return;
		if (this.pagePushedStyle) pb.core.cssUtils.morphToStyle(this.htmlContainer,this.pagePushedStyle,0,true);
		else if (this.pushedStyle && !this.pageNormalStyle) pb.core.cssUtils.morphToStyle(this.htmlContainer,this.pushedStyle,0,true);
	},
	
	mouseUp: function() {
		if (this.disabled || this.locked) return;
		if (this.pageHoverStyle) pb.core.cssUtils.morphToStyle(this.htmlContainer,this.pageHoverStyle,0,true);
		else if (this.hoverStyle) pb.core.cssUtils.morphToStyle(this.htmlContainer,this.hoverStyle,0,true);
		else pb.core.cssUtils.morphToStyle(this.htmlContainer,this.normalStyle,0,true);
	},
	
	updateVisibility: function(event) {
		this.locked = false;

		if (this.disabled) return;
		var visible = (this.htmlContainer.style.display!='none');
		var regExp = /display:(.)*?;/ig;
		
		this.normalStyle = this.normalStyle.replace(regExp,'');
		if (visible) this.normalStyle += 'display: block;';
		else this.normalStyle += 'display: none;';
		
		if (this.hoverStyle) {
			this.hoverStyle = this.hoverStyle.replace(regExp,'');
			if (visible) this.hoverStyle += 'display: block;';
			else this.hoverStyle += 'display: none;';
		}
		if (this.pushedStyle){
			this.pushedStyle = this.pushedStyle.replace(regExp,'');	
			if (visible) this.pushedStyle += 'display: block;';
			else this.pushedStyle += 'display: none;';
		}
	
		if (this.pageNormalStyle) {
			this.pageNormalStyle = this.pageNormalStyle.replace(regExp,'');
			if (visible) this.pageNormalStyle += 'display: block;';
			else this.pageNormalStyle += 'display: none;';
		}
			
		if (this.pageHoverStyle) {
			this.pageHoverStyle = this.pageHoverStyle.replace(regExp,'');
			if (visible) this.pageHoverStyle += 'display: block;';
			else this.pageHoverStyle += 'display: none;';
		}
		
		if (this.pagePushedStyle){
			this.pagePushedStyle = this.pagePushedStyle.replace(regExp,'');	
			if (visible) this.pagePushedStyle += 'display: block;';
			else this.pagePushedStyle += 'display: none;';
		}
	},
	
	updateWidth: function(event) {
		this.locked = false;

		if (this.disabled) return;
		var width = 'width:' + this.htmlContainer.style.width + 'px';
		var regExp = /width:(.)*?;/ig;
		
		this.normalStyle = this.normalStyle.replace(regExp,'');
		this.normalStyle += width;
		
		if (this.hoverStyle) {
			this.hoverStyle = this.hoverStyle.replace(regExp,'');
			this.hoverStyle += width;
		}
		if (this.pushedStyle){
			this.pushedStyle = this.pushedStyle.replace(regExp,'');	
			this.pushedStyle += width;
		}

		if (this.pageNormalStyle) {
			this.pageNormalStyle = this.pageNormalStyle.replace(regExp,'');
			this.pageNormalStyle += width;
		}
		
		if (this.pageHoverStyle) {
			this.pageHoverStyle = this.pageHoverStyle.replace(regExp,'');
			this.pageHoverStyle += width;
		}
		if (this.pagePushedStyle){
			this.pagePushedStyle = this.pagePushedStyle.replace(regExp,'');	
			this.pagePushedStyle += width;
		}
	},
	
	updateHeight: function(event) {
		this.locked = false;

		if (this.disabled) return;
		var height = 'height:' + this.htmlContainer.style.height + 'px';
		var regExp = /height:(.)*?;/ig;
		
		this.normalStyle = this.normalStyle.replace(regExp,'');
		this.normalStyle += height;
		
		if (this.hoverStyle) {
			this.hoverStyle = this.hoverStyle.replace(regExp,'');
			this.hoverStyle += height;
		}
		if (this.pushedStyle){
			this.pushedStyle = this.pushedStyle.replace(regExp,'');	
			this.pushedStyle += height;
		}
		
		if (this.pageNormalStyle) {
			this.pageNormalStyle = this.pageNormalStyle.replace(regExp,'');
			this.pageNormalStyle += height;
		}

		if (this.pageHoverStyle) {
			this.pageHoverStyle = this.pageHoverStyle.replace(regExp,'');
			this.pageHoverStyle += height;
		}
		if (this.pagePushedStyle){
			this.pagePushedStyle = this.pagePushedStyle.replace(regExp,'');	
			this.pagePushedStyle += height;
		}
	},	
	
	setStyle: function(style) {
		this.normalStyle = style;
		pb.core.cssUtils.morphToStyle(this.htmlContainer,this.normalStyle,0,true);
		this.updateStyles();
	},
	
	setAttachedToPage: function(attached) {
		var oldAttached = (this.htmlContainer.parentNode.id=='PageContainerAnchor');
		
		if (attached==oldAttached) return;
		
		if (attached) $('PageContainerAnchor').appendChild(Element.remove(this.identifier));
		else $('mainWebsiteContainer').appendChild(Element.remove(this.identifier));
	},
	
	setAlignment: function(alignment) {
		pb.core.cssUtils.setAlignment(this.htmlContainer,alignment);
	},
	
	setPosition: function(value) {
		if (value=='absolute') {
			$('mainWebsiteContainer').appendChild(this.htmlContainer.remove());			
		}	
		else if (value=='fixed') {
			$('mainWebsiteContainer').appendChild(this.htmlContainer.remove());
		}
		else if (value=='center') {
			$('externalRelativeContainer').appendChild(this.htmlContainer.remove());
		}
		else if (value=='pageContainer') {
			$('PageContainerAnchor').appendChild(this.htmlContainer.remove());
		}
	}
	
}); // pb_core_ContainerEventController


var pb_core_Console = Class.create({
	
	disabled: false,
	
	initialize: function(){
		if (typeof(console)=='undefined'){
			this.disabled = true;
		}
	},
	
	log: function(message){
		if (!this.disabled) console.log(message);
	},
	
	debug: function(object){
		if (!this.disabled) console.debug(object);
	}
	
}); // pb_core_Console

var pb_core_SubmissionThrottle = Class.create({
	submissions: null,

	initialize: function(){
		this.submissions = new Object();
	},
	
	run: function(id,code,milliseconds){
		pb.core.console.log('submission throttle running ' + id);
		this.abort(id);
		this.submissions[id] = setTimeout(code,milliseconds);
	},
	
	abort: function(id) {
		if (this.submissions[id]){
			clearTimeout(this.submissions[id]);
		}
	}
	
}); // pb_core_SubmissionThrottle

var pb_core_ItemInfoManager = Class.create({
	objects: null,
	
	ItemInfoManager: function(){
		this.objects = new Object();		
	},

	initialize: function(){
		this.ItemInfoManager();
	},
	
	add: function(type,object,identifier){
		if (!this.objects[type]) this.objects[type] = new Object();
		var objs = this.objects[type];
		objs[identifier] = object;
	},
	
	get: function(type,identifier){
		
		if (!identifier) identifier = 0;
		
		if (this.objects[type] && this.objects[type][identifier]){
			return this.objects[type][identifier];
		}
		
		return null;
	}
	
}); // pb_core_ItemInfoManager

var pb_core_ItemPropertiesEditor = Class.create({

	actionFile: 'actions/_item_properties_actions.php',

	loadStyleTab: function(id,tabViewId,fieldId,propertiesId,state,params) {
		
		params.id = id;
		params.fieldId = fieldId;
		params.propertiesId = propertiesId;
		params.state = state;
		params.siteId = system.getSiteId();
		params.pageId = system.getPageId();
		
		pb.core.console.log(tabViewManager.tabView(tabViewId).getCurrentTabContentField().id);
		
		pb.core.activityMonitor.addTask(new pb_core_Task('loading_style',pb.core.localizedString.get('Loading style')));

		pb.core.actions.executeAndPutResultIntoContainer(system.getLibraryPath() + 'plasticbriqFramework/' + this.actionFile,'printStyleTab',params,tabViewManager.tabView(tabViewId).getCurrentTabContentField().id,true,false,'loading_style');
	}	
	
}); // pb_core_ItemProperties


/*
* Orginal: http://adomas.org/javascript-mouse-wheel/
* prototype extension by "Frank Monnerjahn" themonnie @gmail.com
*/
Object.extend(Event, {
        wheel:function (event){
                var delta = 0;
                if (!event) event = window.event;
                if (event.wheelDelta) {
                        delta = event.wheelDelta/120;
                        if (window.opera) delta = -delta;
                } else if (event.detail) { delta = -event.detail/3;     }
                return 15*Math.round(delta); //Safari Round
        }
});
/*
* end of extension
*/

var pb_core_EventUtils = Class.create({
	
	disableWheelEvent: function(node) {
		if (!node) return;
		node.observe('DOMMouseScroll',function(event) {
				event.stop();
				//pb.core.console.log('wheel. scrolltop ' + node.scrollTop + ' height ' + node.scrollHeight);
				var newTop = node.scrollTop - (Event.wheel(event));
				//if (newTop<0) newTop = 0;
				//if (newTop>node.scrollHeight) newTop = node.scrollHeight;
				node.scrollTop = newTop;
				//pb.core.console.log('after wheel. scrolltop ' + node.scrollTop + ' height ' + node.scrollHeight);
			});
			
		node.observe('mousewheel',function(event){
				event.stop();
				// pb.core.console.log('wheel. scrolltop ' + node.scrollTop + ' height ' + node.scrollHeight);
				var newTop = node.scrollTop - (Event.wheel(event));
				//if (newTop<0) newTop = 0;
				//if (newTop>node.scrollHeight) newTop = node.scrollHeight;
				node.scrollTop = newTop;

				// pb.core.console.log('after wheel. scrolltop ' + node.scrollTop + ' height ' + node.scrollHeight);
		    });
	}
	
}); // pb_core_EventUtils

var pb_core = Class.create({
	system: new pb_core_System(),
	page: new pb_core_Page(),
	menu: new pb_core_Menu(),
	navigation: new pb_core_Navigation(),
	hash: new pb_core_Hash(),
	actions: new pb_core_Actions(),
	session: new pb_core_Session(),
	activityMonitor: new pb_core_ActivityMonitor(),
	counter: new pb_core_Counter(),
	localizedString: new pb_core_LocalizedString(),
	resourceManager: new pb_core_ResourceManager(),
	loaderAnimation: new pb_core_LoaderAnimation(),
	modalBackground: new pb_core_ModalBackground(),
	resizeHandle: new pb_core_ResizeHandle(),
	browserWindow: new pb_core_BrowserWindow(),
	userAccount: new pb_core_UserAccount(),
	notificationManager: new pb_core_NotificationManager(),
	cssUtils: new pb_core_CSSUtils(),
	console: new pb_core_Console(),
	submissionManager: new pb_core_SubmissionThrottle(),
	itemInfoManager: new pb_core_ItemInfoManager(),
	itemPropertiesEditor: new pb_core_ItemPropertiesEditor(),
	itemEventControllerManager: new pb_core_ItemManager(),
	containerEventControllerManager: new pb_core_ItemManager(),
	eventUtils: new pb_core_EventUtils(),
	ajaxTaskManager: new pb_core_AjaxTaskManager()
});
