/*
 *  Menu.js
 *  MerlinWeb
 *
 *  Created by Andreas Känner on 20.05.08.
 *  Copyright 2008 ProjectWizards. All rights reserved.
 *
 */

// Extend the CSS main menu with javascript functions

addBehaviorToMainMenu( $("menuBar").select(".navmenu-h")[0] );	

function gatherShortcuts(element) {
	shortcuts = {};

	function getStringFromShortcutElement(element) {
		var divs = element.select('.shortcutString');
		if(divs.length) 
			return divs[0].innerHTML;						
		return null;
	}

	function appendShortcuts(element) {
		if(element.tagName == "A") {
			var id = element.id;
			var sc = null;
			if(id) {
				var childs = element.childElements(); 
				for(var i=0; i<childs.length; i++) {
					var child = childs[i];
					if(child.className == "shortcut") {
						sc = getStringFromShortcutElement(child);
						break;
					}
				}
			}
			if(sc) {
				var command = id.substr(0, id.search('_'));
				shortcuts[sc.toLowerCase()] = function(){executeCommand(command);};
			}
		}
		var childs = element.childElements();
		for(var i=0; i<childs.length; i++){
			appendShortcuts(childs[i]);
		}
	}

	shortcut.is_editing_method = function() {
		return activeController && activeController.isEditing();
	}

	// Add shortcuts that are in the menu:

	appendShortcuts(element, shortcuts);
	Object.keys(shortcuts).each(function(key){
		shortcut.add(key, shortcuts[key], {'disable_in_input':true});
	});

	// Add shortcuts that are not in the menu:

	shortcut.add('left', function(){
		if(activeController)
			activeController.moveLeft()
	}, {'disable_in_input':true});			
	shortcut.add('right', function(){
		if(activeController)
			activeController.moveRight()				
	}, {'disable_in_input':true});			
	shortcut.add('up', function(){
		if(activeController)
			activeController.moveUp()								
	}, {'disable_in_input':true});			
	shortcut.add('down', function(){
		if(activeController)
			activeController.moveDown()												
	}, {'disable_in_input':true});			
	shortcut.add('shift_up', function(){
		if(activeController)
			activeController.moveUpAndModifySelection()								
	}, {'disable_in_input':true});			
	shortcut.add('shift_down', function(){
		if(activeController)
			activeController.moveDownAndModifySelection()												
	}, {'disable_in_input':true});			
	shortcut.add('delete', function(){
		executeCommand('delete');
	}, {'disable_in_input':true});			
	shortcut.add('enter', function(){
		if(activeController)
			activeController.insertNewline()												
	});			
	shortcut.add('tab', function(){
		if(activeController)
			activeController.insertTab()												
	});			
}

gatherShortcuts($$('.navmenu-h')[0]);

function updateColumnSetAndStyleSetMenus() {
	var container = $("unusedMenusContainer"); 
	var old = $("columnSets_MenuItem").nextSiblings();
	if(old.length)
		container.insert(Element.remove(old[0]))
	old = $("styleSets_MenuItem").nextSiblings();
	if(old.length)
		container.insert(Element.remove(old[0]))
	var columnSetsParent = $($("columnSets_MenuItem").parentNode);
	var styleSetsParent = $($("styleSets_MenuItem").parentNode);
	if(activeController == activitiesViewController) {
		if($("activityViewColumnSets_UL").childElements().length)
			columnSetsParent.insert(Element.remove($("activityViewColumnSets_UL")));
		if($("activityViewStyleSets_UL").childElements().length)
			styleSetsParent.insert(Element.remove($("activityViewStyleSets_UL")));
	}else if(activeController == resourcesViewController) {
		if($("resourcesViewColumnSets_UL").childElements().length)
			columnSetsParent.insert(Element.remove($("resourcesViewColumnSets_UL")));
		if($("resourcesViewStyleSets_UL").childElements().length)
			styleSetsParent.insert(Element.remove($("resourcesViewStyleSets_UL")));				
	}else if(activeController == utilizationViewController) {
		if($("utilizationViewColumnSets_UL").childElements().length)
			columnSetsParent.insert(Element.remove($("utilizationViewColumnSets_UL")));
		if($("utilizationViewStyleSets_UL").childElements().length)
			styleSetsParent.insert(Element.remove($("utilizationViewStyleSets_UL")));								
	}
	var separators = $$(".separator");
	separators.each(function(separator){
		if(!separator.previousSiblings().length)
			Element.remove(separator);
	});
}

var menus = $$('.navmenu-h li');
for(var i=0; i<menus.length; i++) {
	var menu = menus[i];
	PWUtils.setSelectionEnabled(menu, false);
}

function canExecuteCommand(command) {
	var r = false;
	if(command.startsWith('setWorkspace'))
		return true;
	switch(command) {
		case "about":
			r = true;
			break;
		case "logout":
			r = true;
			break;
		case "save":
			r = true;
			break;
		case "print":
			r = true;
			break;
		case "undo":
			r = true;
			break;
		case "redo":
			r = true;
			break;	
		case "delete":
			r = activeController.canDeleteSelection();
			break;
		case "selectAll":
			r = true;
			break;
		case "indent":
			r = activeController == activitiesViewController && activitiesViewController.canIndentActivity();
			break;
		case "outdent":
			r = activeController == activitiesViewController && activitiesViewController.canOutdentActivity();
			break;
		case "collapseAll":
		case "expandAll":
			r = activeController == activitiesViewController || activeController == utilizationViewController;
			break;
		case "hideAllAssignments":
		case "showAllAssignments":
		case "level1":
		case "level2":
		case "level3":
		case "level4":
		case "level5":
		case "level6":
		case "level7":
		case "level8":
		case "level9":
			r = activeController == activitiesViewController;
			break;
		case "freezeSortOrder": {
				var sortDescriptors = activitiesViewController.outlineController.sortDescriptors;
				r = activeController == activitiesViewController && sortDescriptors && sortDescriptors.length && sortDescriptors[0].key != "flatOrder";
			} break;
		case "makeMilestone":
			r = activeController == activitiesViewController && activitiesViewController.canTransformSelectedActivitiesIntoMilestones();
			break;
		case "clearActualValues":
			r = activeController == activitiesViewController && activitiesViewController.canClearActualValues();
			break;
		case "insertActivity":
		case "insertMilestone":
			r = activeController == activitiesViewController && activitiesViewController.canAddActivity();
			break;
		case "insertSubActivity":
			r = activeController == activitiesViewController && activitiesViewController.canAddSubActivity();
			break;
		case "insertSuccessorActivity":
			r = activeController == activitiesViewController && activitiesViewController.canAddSuccessorActivity();
			break;
		case "insertPredecessorActivity":
			r = activeController == activitiesViewController && activitiesViewController.canAddPredecessorActivity();
			break;
		case "insertAuntActivity":
			r = activeController == activitiesViewController && activitiesViewController.canAddAuntActivity();
			break;
		case "insertAssignment":
			r = activeController == activitiesViewController && activitiesViewController.canAddAssignment();
			break;
		case "showActivitiesView":
		case "showResourcesView":
		case "showUtilizationView":
			r = true;
			break;
		case "zoomIn":
		case "zoomOut":
			r = activeController == activitiesViewController || activeController == utilizationViewController;
			break;
		case "showMerlinHelp":
		case "showMerlinWebsite":
			r = true;
			break;
		case "chainFinishStart":
		case "chainFinishFinish":
		case "chainStartFinish":
		case "chainStartStart":
			r = (activeController == activitiesViewController || activeController == utilizationViewController) && activeController.canChainActivities();
			break;
		case "disconnect":
			r = (activeController == activitiesViewController || activeController == utilizationViewController ) && activeController.canDisconnectActivities();
			break;											
	}
	return r;
}

function executeCommand(command) {
	closeMenu();
	if(canExecuteCommand(command)) {
		if(command.startsWith('setWorkspace')) {
			applyWorkspace({workspaceURI:command.substr('setWorkspace:'.length)});
		}
		switch(command) {
			case "about": 
				showAboutDialog(); 
				break;
			case "logout": 
				if(isLoggedInAsUser || openedFromProjectList)
					window.location.href = logoutAction;
				else
					window.close();
				break;
			case "save": 
				context.synchronizeAndSave(true); 
				break;
			case "print": 
				activeController.print(); 
				break;
			case "undo": 
				context.undo(); 
				activeController.refresh();
				break;
			case "redo":
				context.redo(); 
				activeController.refresh();
				break;
			case "delete": 
				activeController.deleteSelectedObjects(); 
				break;
			case "selectAll": 
				activeController.selectAll(); 
				break;
			case "indent":	
				activitiesViewController.indentSelection();
				break;
			case "outdent":
				activitiesViewController.outdentSelection();
				break;
			case "collapseAll":
				activeController.collapseAll();
				break;
			case "expandAll":
				activeController.expandAll();
				break;
			case "hideAllAssignments":
				activitiesViewController.hideAllAssignments();
				break;
			case "showAllAssignments":
				activitiesViewController.showAllAssignments();
				break;
			case "level1":
			case "level2":
			case "level3":
			case "level4":
			case "level5":
			case "level6":
			case "level7":
			case "level8":
			case "level9":
				activitiesViewController.showOutlineLevel(command.toArray().reverse()[0]);
				break;
			case "freezeSortOrder":
				activitiesViewController.freezeSortOrder();
				break;
			case "makeMilestone":
				activitiesViewController.transformSelectedActivitiesIntoMilestones();
				break;
			case "clearActualValues":
				activitiesViewController.clearActualValues();						
				break;
			case "insertActivity":
				activitiesViewController.addActivity();						
				break;
			case "insertMilestone":
				activitiesViewController.addMilestone();						
				break;
			case "insertSubActivity":
				activitiesViewController.addActivity('subActivity');
				break;
			case "insertSuccessorActivity":
				activitiesViewController.addActivity('successorActivity');
				break;
			case "insertPredecessorActivity":
				activitiesViewController.addActivity('predecessorActivity');
				break;
			case "insertAuntActivity":
				activitiesViewController.addActivity('auntActivity');
				break;
			case "insertAssignment":
				activitiesViewController.addAssignment();
				break;
			case "showActivitiesView":
				mainViewSwitcher.activateSegmentAtIndex(0);
				break;
			case "showResourcesView":
				mainViewSwitcher.activateSegmentAtIndex(2);
				break;
			case "showUtilizationView":
				mainViewSwitcher.activateSegmentAtIndex(4);						
				break;
			case "zoomIn":
				activeController.zoomIn();
				break;
			case "zoomOut":
				activeController.zoomOut();
				break;
			case "showMerlinHelp":
				window.open('http://www.projectwizards.net/merlin/webhelp');
				break;
			case "showMerlinWebsite":
				window.open('http://www.merlin2.net', '');
				break;
			case "chainFinishStart":
				activitiesViewController.chainFinishStart();
				break;						
			case "chainFinishFinish":
				activitiesViewController.chainFinishFinish();
				break;						
			case "chainStartFinish":
				activitiesViewController.chainStartFinish();
				break;
			case "chainStartStart":
				activitiesViewController.chainStartStart();
				break;
			case "disconnect":
				activitiesViewController.disconnectActivities();
				break;							
		}
	}
}


var menuItems = $$('.navmenu-h li a');
for(var i=0; i<menuItems.length; i++) {
	var menuItem = menuItems[i];
	menuItem.originalClassName = menuItem.className;
}

function closeMenu() {
	var menus = $$('.navmenu-h li ul');
	for(var i=0; i<menus.length; i++) {
		var menu = menus[i];
		menu.style.visibility = "hidden";
		if(menu.getStyle('left'))
			menu.style.left = ""+(parseInt(menu.getStyle('left'))+10)+"px";
	}
	(function(){
		for(var i=0; i<menus.length; i++) {
			var menu = menus[i];
			menu.style.left = null;
			menu.style.visibility = "visible";
		}
	}).delay(0.5);
}

function validateMenuItems() {
	function validateMenuItemForCommand(command) {
		var item = $(command+'_MenuItem');
		var enable = canExecuteCommand(command);
		if(enable)
			item.className = item.originalClassName;
		else
			item.className = "disabledMenuItem "+item.originalClassName;
		var shortcuts = item.select('.shortcut');
		if(shortcuts.length) {
			var sc = shortcuts[0];
			if(!sc.originalClassName)
				sc.originalClassName = sc.className ? sc.className : '';
			if(enable)
				sc.className = sc.originalClassName;
			else
				sc.className = "disabledMenuItem "+sc.originalClassName;
		}
	}
	validateMenuItemForCommand('logout');
	if(PWUtils.effectiveStyle( $('file_MenuItem')).backgroundImage && PWUtils.effectiveStyle( $('file_MenuItem')).backgroundImage != "none"){
		validateMenuItemForCommand('save');
		validateMenuItemForCommand('print');					
	}else if(PWUtils.effectiveStyle( $('edit_MenuItem')).backgroundImage && PWUtils.effectiveStyle( $('edit_MenuItem')).backgroundImage != "none"){
		validateMenuItemForCommand('undo');
		validateMenuItemForCommand('redo');
		validateMenuItemForCommand('delete');						
		validateMenuItemForCommand('selectAll');		
		validateMenuItemForCommand('indent');		
		validateMenuItemForCommand('outdent');		
		validateMenuItemForCommand('collapseAll');		
		validateMenuItemForCommand('expandAll');		
		validateMenuItemForCommand('hideAllAssignments');		
		validateMenuItemForCommand('showAllAssignments');		
		validateMenuItemForCommand('freezeSortOrder');		
		validateMenuItemForCommand('makeMilestone');		
		validateMenuItemForCommand('clearActualValues');		
		validateMenuItemForCommand('level1');		
		validateMenuItemForCommand('level2');		
		validateMenuItemForCommand('level3');		
		validateMenuItemForCommand('level4');		
		validateMenuItemForCommand('level5');		
		validateMenuItemForCommand('level6');		
		validateMenuItemForCommand('level7');		
		validateMenuItemForCommand('level8');		
		validateMenuItemForCommand('level9');		

		validateMenuItemForCommand('chainFinishStart');		
		validateMenuItemForCommand('chainFinishFinish');		
		validateMenuItemForCommand('chainStartFinish');		
		validateMenuItemForCommand('chainStartStart');		
		validateMenuItemForCommand('disconnect');		

	}else if(PWUtils.effectiveStyle( $('insert_MenuItem')).backgroundImage && PWUtils.effectiveStyle( $('insert_MenuItem')).backgroundImage != "none"){
		validateMenuItemForCommand('insertActivity');		
		validateMenuItemForCommand('insertMilestone');		
		validateMenuItemForCommand('insertSubActivity');	
		validateMenuItemForCommand('insertSuccessorActivity');	
		validateMenuItemForCommand('insertPredecessorActivity');	
		validateMenuItemForCommand('insertAuntActivity');	
		validateMenuItemForCommand('insertAssignment');	
	}else if(PWUtils.effectiveStyle( $('view_MenuItem')).backgroundImage && PWUtils.effectiveStyle( $('view_MenuItem')).backgroundImage != "none"){
		validateMenuItemForCommand('showActivitiesView');	
		validateMenuItemForCommand('showResourcesView');	
		validateMenuItemForCommand('showUtilizationView');	
		validateMenuItemForCommand('zoomIn');	
		validateMenuItemForCommand('zoomOut');	
	}else if(PWUtils.effectiveStyle( $('help_MenuItem')).backgroundImage && PWUtils.effectiveStyle( $('help_MenuItem')).backgroundImage != "none"){
		validateMenuItemForCommand('showMerlinHelp');	
		validateMenuItemForCommand('showMerlinWebsite');	
	}
}

updateColumnSetAndStyleSetMenus();

var ViewMenuUpdater = Base.extend({
	constructor: function(){
		this.base();
        NotificationCenter.defaultNotificationCenter().addObserverForMessage(this, WRLAjaxContextChangedByServerNotification, "contextChanged");	
	},
	
    workspaceMenuItemsAreTemporary: function() {
        return $$('.workspaceMenuItem').any(function(element){
            return element.id.indexOf("/Workspace/t") != -1;
        });
    },
    
	contextChanged: function(msg, userInfo) {
        if(this.workspaceMenuItemsAreTemporary()) {
            mainViewMenuUpdate();
            addBehaviorToMainMenu.delay(1.0, $("menuBar").select(".navmenu-h")[0] );
        }
	}
});

viewMenuUpdater = new ViewMenuUpdater();
