var pb_controls_Control = Class.create(pb_core_Node,{
	normalContainer:null,
	hoverContainer:null,
	activeContainer:null,
	disabledContainer:null,
	disabled:false,
	selected: false,
	isToggled:false,
	action:'',
	hoverEnabled: true,

	Control:function(identifier,action,disabled,selected,hoverEnabled,isToggled) {
		this.Node(identifier);
		this.action = action;
		this.disabled = disabled;
		this.selected = selected;
		this.normalContainer = $(identifier +'_normal');
		this.hoverContainer = $(identifier +'_hover');
		this.activeContainer = $(identifier +'_active');
		this.disabledContainer = $(identifier +'_disabled');
		this.hoverEnabled = hoverEnabled;
		this.isToggled = isToggled;
		if (this.selected) this.normalContainer = this.activeContainer;
	},

	initialize: function(identifier,action,disabled,selected,hoverEnabled,isToggled) {
		this.Control(identifier,action,disabled,selected,hoverEnabled,isToggled);
	},
	
	mouseOver:function() {
		if (!this.hoverEnabled) return;
		if (this.disabled) return;
		this.hideAll();
		this.showContainer(this.hoverContainer);
	},
	
	mouseOut: function() {
		if (this.disabled || !this.hoverEnabled) return;
		this.hideAll();
		if (this.isToggled) {
			this.showContainer(this.activeContainer);
		}
		else {
			this.showContainer(this.normalContainer);
		}
	},
	
	mouseDown: function() {
		if (this.disabled) return;
		this.hideAll();
		this.showContainer(this.activeContainer);
	},

	mouseUp: function() {
		if (this.disabled) return;
		this.hideAll();
		if (this.hoverEnabled) this.showContainer(this.hoverContainer);
		else if (this.isToggled) this.showContainer(this.activeContainer);
		else this.showContainer(this.normalContainer);
	},
	
	hideAll: function() {
		this.hideContainer(this.normalContainer);
		this.hideContainer(this.hoverContainer);
		this.hideContainer(this.activeContainer);
		this.hideContainer(this.disabledContainer);
	},
	
	hideContainer: function(container) {
		if (container && container.hide) {
			container.hide();
		}
	},

	showContainer: function(container) {
		if (container && container.show) {
			container.show();
		}
	}
});

var pb_controls_Button = Class.create(pb_controls_Control,{
	Button: function(identifier,action,disabled,selected,hoverEnabled,isToggled) {
		this.Control(identifier,action,disabled,selected,hoverEnabled,isToggled);
		this.type = 'button';
	},

	initialize: function(identifier,action,disabled,selected,hoverEnabled,isToggled) {
		this.Button(identifier,action,disabled,selected,hoverEnabled,isToggled);
	}
});

var pb_controls_AvatarField = Class.create(pb_core_Node,{
	menu:null,

	AvatarField: function(identifier) {
		this.Node(identifier);
		var app = 'lib';
		var className = 'AvatarSelector';
		var command = 'printAvatarSelector';
		this.menu = pb.controls.dropDownMenuManager.createMenu(app,className,command,{fieldId:identifier});
	},

	initialize: function(identifier) {
		this.AvatarField(identifier);
	},

	openAvatarSelector: function(event) {
		var posx = 100;
		var posy = 100;
		
		if (event.clientX) {
			posx = event.clientX;
			posy = event.clientY;
		}
//		else if ()
		this.menu.setPosition(posy + 'px',posx + 'px');
		this.menu.fixRightBounds();

		pb.controls.dropDownMenuManager.show(this.menu);
	},
	
	selectAvatar: function(file,url) {
		$(this.identifier).value = file;
		$('image_' + this.identifier).style.backgroundImage = 'url(' + url + ')';
		$('image_' + this.identifier).innerHTML = '';
		pb.controls.dropDownMenuManager.hide(this.menu);
	}
});

var pb_controls_MenuButton = Class.create(pb_controls_Button,{
	menu:null,
	side:'left',

	MenuButton: function(identifier,sourceApp,sourceClass,command,disabled,side,selected) {
		this.menu = pb.controls.dropDownMenuManager.createMenu(sourceApp,sourceClass,command,null,this);
		this.Button(identifier,'',disabled,selected);
		this.type = 'menuButton';
		this.isToggled = true;
		if (side) {
			this.side = side;
		}
	},
	
	menuHidden: function(){
		this.hideAll();
		this.showContainer(this.normalContainer);
	},
	
	// mouseUp: function() {
	// 		this.hideAll();
	// 		this.showContainer(this.normalContainer);
	// 	},

	initialize: function(identifier,sourceApp,sourceClass,command,disabled,side,selected) {
		this.MenuButton(identifier,sourceApp,sourceClass,command,disabled,side,selected);
	},
	
	showMenu: function() {
		var container = this.htmlContainer;
		if (container) {
			var left = container.offsetLeft;
			var top = container.offsetTop + container.offsetHeight;

			this.menu.setPosition(top + 'px',left + 'px');
			this.menu.fixRightBounds();

			pb.controls.dropDownMenuManager.show(this.menu);
		}
		
	}
});

var pb_controls_ActionBarMenuButton = Class.create(pb_controls_Button,{
	menu:null,
	side:'left',

	ActionBarMenuButton: function(identifier,sourceApp,sourceClass,command,disabled,side,selected,params) {
		this.menu = pb.controls.dropDownMenuManager.createMenu(sourceApp,sourceClass,command,params);
		this.Button(identifier,'',disabled,selected);
		this.type = 'menuButton';
		if (side) {
			this.side = side;
		}
	},

	initialize: function(identifier,sourceApp,sourceClass,command,disabled,side,selected,params) {
		this.ActionBarMenuButton(identifier,sourceApp,sourceClass,command,disabled,side,selected,params);
	},
	
	showMenu: function() {
		var container = $(this.identifier);
		if (container) {
			
			if (container.parentNode && container.parentNode.parentNode &&  container.parentNode.parentNode.position=='absolute'){
				var left = 0;
				var top = 0;
				var obj = container;

				if (obj.offsetParent) {
					do {
						left += obj.offsetLeft;
						top += obj.offsetTop;
						obj = obj.offsetParent;
					} while (obj);
				}
				var pageHeight = pb.core.browserWindow.getHeight();
				var bottom = pageHeight - top;
			
				this.menu.setPositionBottom(bottom + 'px',left + 'px');
				this.menu.fixRightBounds();				
			}
			else {
				var bottom = parseInt(container.parentNode.parentNode.style.bottom)||0;
				bottom += pb.core.cssUtils.getHeight(container);
				this.menu.setPositionBottom(bottom + 'px',container.parentNode.parentNode.style.left);
			}
		
			pb.controls.dropDownMenuManager.show(this.menu);
		}
		
	}
});

var pb_controls_ControlManager = Class.create(pb_core_ItemManager,{
	mouseOver: function(identifier) {
		var control = this.getItem(identifier);
		if (control && control.mouseOver) {
			control.mouseOver();
		}
	},

	mouseOut: function(identifier) {
		var control = this.getItem(identifier);
		if (control && control.mouseOut) {
			control.mouseOut();
		}
	},

	mouseUp: function(identifier) {
		var control = this.getItem(identifier);
		if (control && control.mouseUp) {
			control.mouseUp();
		}
	},

	mouseDown: function(identifier) {
		var control = this.getItem(identifier);
		if (control && control.mouseDown) {
			control.mouseDown();
		}
	}
}); // pb_controls_ControlManager

var pb_controls_DropDownMenu = Class.create(pb_core_Node,{
	application:'',
	className:'',
	command:'',
	otherParams:{},
	menuButton: null,

	DropDownMenu: function(identifier,application,className,command,otherParams,menuButton) {
		if (otherParams) this.otherParams = otherParams;
		var menuContainer = pb.controls.dropDownMenuManager.getMenuContainer();
		// Creamos el nodo HTML antes, para que el constructor de Node inicialize el atributo htmlContainer
		var htmlContainer = document.createElement('div');
		Element.extend(htmlContainer);
		htmlContainer.id = identifier;
		htmlContainer.className = 'dropDownMenu';
		htmlContainer.hide();
		htmlContainer.style.position = 'fixed';
		htmlContainer.style.zIndex = htmlContainer.style.zIndex + 1;
		htmlContainer.style.top = '40px';
	//	htmlContainer.style.left = '40px';
		menuContainer.appendChild(htmlContainer);
		htmlContainer.observe('click',function(evt) { evt.cancelBubble = true;});

		this.menuButton = menuButton;

		this.Node(identifier);
		this.application = application;
		this.className = className;
		this.command = command;
		
		this.setLoaderContent();
		this.loadContent();
	},
	
	initialize: function(identifier,application,className,command,otherParams,menuButton) {
		this.DropDownMenu(identifier,application,className,command,otherParams,menuButton);
	},
	
	hide: function() {
		pb.controls.dropDownMenuManager.hide(this.identifier);
	},
	
	show: function() {
		pb.controls.dropDownMenuManager.show(this.identifier);
	},
	
	setPosition: function(top,left) {
		this.htmlContainer.style.bottom = '';
		this.htmlContainer.style.top = top;
		this.htmlContainer.style.left = left;
	},
	
	setPositionBottom: function(bottom,left) {
		this.htmlContainer.style.top = '';
		this.htmlContainer.style.bottom = bottom;
		this.htmlContainer.style.left = left;
	},
	
	loadContent: function() {
		var actionFile = pb.core.system.getLibraryPath() + 'plasticbriqFramework/actions/_application_action.php';
		var parameters = this.otherParams;
		parameters.appname = this.application;
		parameters.actionClass = this.className;
		parameters.command = this.command;
		var menuId = this.identifier;

		pb.core.actions.execute(actionFile,this.command,parameters,
			function(responseText) {
				var menu = pb.controls.dropDownMenuManager.itemManager.getItem(menuId);
				menu.htmlContainer.innerHTML = responseText;	
			});
	},
	
	setLoaderContent: function() {
		var loader = pb.core.loaderAnimation.getLoaderContainer(this.identifier + '_animationContainer');
		loader.style.marginTop = '20px';
		var loaderContainer = document.createElement('div');
		Element.extend(loaderContainer);
		loaderContainer.style.width = '200px';
		loaderContainer.style.height = '80px';
		loaderContainer.style.backgroundColor = 'white';
		loaderContainer.style.border = 'gray 1px solid';
		loaderContainer.style.opacity = '0.8';
		loaderContainer.appendChild(loader);
		this.htmlContainer.innerHTML = '';
		this.htmlContainer.appendChild(loaderContainer);
	},
	
	fixRightBounds: function() {
		pb.controls.dropDownMenuManager.show(this);
		var leftPos = this.htmlContainer.offsetLeft;
		var topPos = this.htmlContainer.offsetTop;
		this.setPosition('0px','0px');
		var menuWidth = this.htmlContainer.offsetWidth;
		pb.controls.dropDownMenuManager.hide();

		var windowWidth = pb.core.browserWindow.getWidth();

		if ((leftPos + menuWidth)>windowWidth) {
			leftPos = windowWidth - menuWidth;
		}
		this.setPosition(topPos + 'px',leftPos + 'px');
	}
});	// pb_controls_Menu

var pb_controls_DropDownMenuManager = Class.create({
	menuContainer:null,
	itemManager: new pb_core_ItemManager(),
	currentDropDownMenu:null,

	generateIdentifier: function() {
		return pb.core.counter.getId('dropDownMenu_');
	},

	createMenu: function(application,className,command,otherParams,menuButton) {
		var menu = new pb_controls_DropDownMenu(this.generateIdentifier(),application,className,command,otherParams,menuButton);
		this.itemManager.addItem(menu);
		return menu;
	},

	getMenuContainerId: function() {
		return 'dropDownMenuContainer';
	},

	getMenuContainer: function() {
		if (!this.menuContainer) {
			this.menuContainer = document.createElement('div');
			Element.extend(this.menuContainer);
			this.menuContainer.id = this.getMenuContainerId();
			this.menuContainer.className = this.getMenuContainerId();
			this.menuContainer.style.position = 'fixed';
			this.menuContainer.style.top = '0px';
			this.menuContainer.style.bottom = '0px';
			this.menuContainer.style.left = '0px';
			this.menuContainer.style.right = '0px';
			this.menuContainer.style.zIndex = 20000;
			this.menuContainer.hide();
			document.body.appendChild(this.menuContainer);
			
			//var obj = this;
			// this.menuContainer.observe('mouseup',function(event) {
			// 					if (obj.getMenuContainer().style.display=='none') return;
			// 					obj.hide();
			// 					var clicked = document.elementFromPoint(event.pointerX(), event.pointerY());
			// 					if (clicked){
			// 						console.log('clicked element');
			// 						console.debug(clicked);
			// 						//clicked.simulate('click',{ pointerX: event.pointerX(),pointerY: event.pointerY() });
			// 						clicked.simulate('mouseup');
			// 						console.log('event simulated');
			// 					}
			// 					obj.show();
			// 				});
				
			// this.menuContainer.observe('mousedown',function(event) {
			// 		if (obj.getMenuContainer().style.display=='none') return;
			// 		obj.hide();
			// 		var clicked = document.elementFromPoint(event.pointerX(), event.pointerY());
			// 		if (clicked){
			// 			console.log('clicked element');
			// 			console.debug(clicked);
			// 			//clicked.simulate('click',{ pointerX: event.pointerX(),pointerY: event.pointerY() });
			// 			clicked.simulate('mousedown');
			// 			console.log('event simulated');
			// 		}
			// 		obj.show();
			// 	});
			// 
			this.menuContainer.observe('click',this.onClickFunc.bind(this));
			// this.menuContainer.observe('mouseup',this.onMouseUpFunc.bind(this));
			// 			this.menuContainer.observe('mouseover',this.onMouseOverFunc.bind(this));
			// 			this.menuContainer.observe('mouseout',this.onMouseOutFunc.bind(this));
		}
		return this.menuContainer;
	},
	
	showMenuContainer: function() {
		this.getMenuContainer().show();
	},
	
	hideMenuContainer: function() {
		this.getMenuContainer().hide();
	},
	
	show: function(dropMenu) {
		this.hide();
		this.currentDropDownMenu = dropMenu;
		if (this.currentDropDownMenu) {
			this.getMenuContainer().show();
			this.currentDropDownMenu.htmlContainer.show();
		}
	},
	
	hide: function() {
		if (this.currentDropDownMenu) {
			this.currentDropDownMenu.htmlContainer.hide();
			if (this.currentDropDownMenu.menuButton){
				this.currentDropDownMenu.menuButton.mouseUp();
			}
		}
		this.getMenuContainer().hide();
	},
	
	onClickFunc: function(event) {
		//console.log('mouse down');
		this.hide();
		
		if (this.currentDropDownMenu) {
			if (this.currentDropDownMenu.menuButton){
				//this.currentDropDownMenu.menuButton.mouseUp();
				this.currentDropDownMenu.menuButton.menuHidden();
			}
		}
		
		this.currentDropDownMenu = null;
		
		// var clicked = document.elementFromPoint(event.pointerX(), event.pointerY());
		// if (clicked){
		// 	clicked.simulate('mousedown');
		// }
	}
	
	// onMouseUpFunc: function(event){
	// 		console.log('mouse up');
	// 		this.getMenuContainer().hide();
	// 		
	// 		var clicked = document.elementFromPoint(event.pointerX(), event.pointerY());
	// 		if (clicked){
	// 			clicked.simulate('mouseup');
	// 		}
	// 		this.getMenuContainer().show();
	// 	},
	// 	
	// 	onMouseOverFunc: function(event){
	// 		console.log('mouseOver');
	// 		this.getMenuContainer().hide();
	// 		
	// 		var clicked = document.elementFromPoint(event.pointerX(), event.pointerY());
	// 		if (clicked){
	// 			clicked.simulate('mouseover');
	// 		}
	// 		this.getMenuContainer().show();
	// 	},
	// 	
	// 	onMouseOutFunc: function(event,name){
	// 		console.log('mouse out');
	// 		this.getMenuContainer().hide();
	// 		
	// 		var clicked = document.elementFromPoint(event.pointerX(), event.pointerY());
	// 		if (clicked){
	// 			clicked.simulate('mouseout');
	// 		}
	// 		this.getMenuContainer().show();
	// 	}
});	// pb_controls_MenuManager

var pb_controls_TreeManager = Class.create({
	draggable: false,
	
	toggle: function(groupId){
		
	}
	
}); // pb_TreeManager

var pb_controls_View = Class.create(pb_core_Node,{
	title: "",
	
	View: function(identifier,title){
		this.Node(identifier);
		this.htmlContainer = new Element('div',{ id: identifier });
		this.title = title;
		this.type = 'view';
	},
	
	initialize: function(identifier,title){
		this.View(identifier,title);
	},
	
	show: function(){
		if (this.htmlContainer) this.htmlContainer.show();
	},
	
	hide: function(){
		if (this.htmlContainer) this.htmlContainer.hide();
	},
	
	setContent: function(content){
		if (this.htmlContainer){
			this.htmlContainer.innerHTML = content;
			return true;
		}
		return false;
	},
	
	setContentWithURL: function(url,command,parameters,task) {
		if (!task){
			task = new pb_core_Task(pb.core.counter.getId(this.identifier),pb.core.localizedString.get('Loading view content'));
		}
		
		pb.core.activityMonitor.addTask(task);
		
		this.setContent(pb.core.loaderAnimation.getLoaderContainerText('loading'));
		
		pb.core.actions.executeAndPutResultIntoContainer(url,command,parameters,this.identifier,true,false,task.identifier);
	}
		
}); // pb_controls_NavigationView

var pb_controls_NavigationViewController = Class.create(pb_core_Node,{
	
	rootView: null,
	parentNode: null,
	currentView: null,
	views: null,
	breadcrumbSeparator: ' > ',
	breadcrumbItemStyle: null,
	hideBreadcrumbInRootView: false,
	
	NavigationViewController: function(identifier,rootView,parentNode){
		//console.log('NavigationViewController');
		this.Node(identifier);
		this.rootView = rootView;
		this.parentNode = parentNode;
		this.currentView = rootView;
		this.views = new Array();
		this.breadcrumbItemStyle = 'float: left;cursor: pointer; cursor: hand;color: white; text-decoration: underline;';
		this.breadcrumbSeparator = '<div style="float:left;"> > </div>';
		
		//console.log('Initializing');
		this.breadcrumbNode = new Element('div', { id: identifier + '_breadcrumb' });
		// this.breadcrumbNode.style.height = '20px';
		this.breadcrumbNode.style.color = 'white';
		this.breadcrumbNode.style.backgroundColor = 'black';
		this.breadcrumbNode.style.borderBottomStyle = 'solid';
		this.breadcrumbNode.style.borderBottomColor = 'grey';
		this.breadcrumbNode.style.borderBottomWidth = '1px';
		this.breadcrumbNode.style.paddingLeft = '10px';
		this.breadcrumbNode.style.paddingTop = '2px';
		this.breadcrumbNode.style.paddingBottom = '2px';
		this.breadcrumbNode.style.overflow = 'hidden';
						
		this.parentNode.appendChild(this.breadcrumbNode);
		this.pushView(rootView);
	},
	
	initialize: function(identifier,rootView,parentNode){
		this.NavigationViewController(identifier,rootView,parentNode);
	},
	
	pushView: function(view){
		//console.log('push view');
		this.views.push(view);
		if (this.currentView) this.currentView.hide();
		this.currentView = view;
		//console.log('append view to container');
		this.parentNode.appendChild(this.currentView.htmlContainer);
		//console.log('show view');
		this.currentView.show();
		this.updateBreadcrumb();
	},
	
	popView: function(){
		//console.log('pop view');
		if (this.currentView) this.currentView.hide();
		this.currentView.htmlContainer.remove();
		this.views.pop();
		this.currentView = this.views.last();
		if (!this.currentView) this.currentView = this.rootView;
		this.currentView.show();
		this.updateBreadcrumb();
	},
	
	loadView: function(index){
		while ((this.views.length>(index+1))){
			this.popView();
		}
	},
	
	updateBreadcrumb: function(){

		this.breadcrumbNode.show();
		if (this.hideBreadcrumbInRootView && (this.currentView==this.rootView)){
			this.breadcrumbNode.hide();
			return;
		}
		
		var title = "";
		var loadViewEvent = this.loadView.bind(this);
		var lastIndex = this.views.length-1;
		this.views.each(function(item,index){
			var action = 'pb.controls.navigationViewControllerManager.getItem(\'' + this.identifier + '\').loadView(' + index + ');';
			title += '<div class="BreadcrumbItem" id="' + item.identifier + '_breadcrumb" style="' + this.breadcrumbItemStyle + '" onclick="' + action + '">' + item.title + '</div>';
			if (index<lastIndex){
				title += this.breadcrumbSeparator;
			}
		},this);

		title += '<div style="clear: both"></div>';	

		this.breadcrumbNode.innerHTML = title;
	}
		
}); // pb_controls_NavigationView

var pb_controls = Class.create({
	controlManager: new pb_controls_ControlManager(),
	dropDownMenuManager: new pb_controls_DropDownMenuManager(),
	navigationViewControllerManager: new pb_core_ItemManager()
});
