// Copyright 2008 ProjectWizards GmbH. All rights reserved.

//console.log("ActivitiesView.js");

var ActivitiesView = Base.extend({
	constructor: function(outlineController, domNode, columns, styleList, ganttRuler, viewOptions, environment, controlsContainer, managedObjectContext, showPrintView, delegate, isBeingExportedForQuicklook){
		var me = this;

		this.delegate = delegate;
		this.moc = managedObjectContext;
		this.isBeingExportedForQuicklook = isBeingExportedForQuicklook;

		(function() {me.registerClickInBody()}).delay(1);

		var node;
		this.showPrintView = showPrintView;
		if(controlsContainer){
			this.hasControls = true;
			for(var i=0; i<controlsContainer.childNodes.length;i++){
				node = controlsContainer.childNodes[i];
				if(node.childNodes.length){
					node = node.childNodes[0];
					if(node.className == "addActivityButton"){
						this.addActivityButton = node; PWUtils.makeMultiStateButton(node);
					}else if(node.className == "chainActivitiesButton"){
						this.chainActivitiesButton = node; PWUtils.makeMultiStateButton(node);
					}else if(node.className == "deleteButton"){
						this.deleteButton = node; PWUtils.makeMultiStateButton(node);
					}else if(node.className == "indentButton"){
						this.indentButton = node; PWUtils.makeMultiStateButton(node);
					}else if(node.className == "outdentButton"){
						this.outdentButton = node; PWUtils.makeMultiStateButton(node);
					}else if(node.className == "saveButton"){
						this.saveButton = node; PWUtils.makeMultiStateButton(node);
					}else if(node.className == "undoButton"){
						this.undoButton = node; PWUtils.makeMultiStateButton(node);
					}else if(node.className == "redoButton"){
						this.redoButton = node; PWUtils.makeMultiStateButton(node);
					}else if(node.className == "zoomInButton"){
						this.zoomInButton = node; PWUtils.makeMultiStateButton(node, true);
					}else if(node.className == "zoomOutButton"){
						this.zoomOutButton = node; PWUtils.makeMultiStateButton(node, true);
					}else if(node.className == "columnsButton"){
						this.columnsButton = node; PWUtils.makeMultiStateButton(node);
					}
				}
			}
		}
		this.environment = environment;
		this.outlineController = outlineController;					
		// Vorgangsansicht anlegen:
		/*
		 <div name="activities">
		 <div name="splitview">
		 <div class="outline"></div>			
		 <div class="gantt"></div>		
		 </div>
		 </div>
		 */
		this.activitiesContainer = $(document.createElement("div"));
		this.activitiesContainer.className = "activities";
		this.splitViewContainer = $(document.createElement("div"));
		this.splitViewContainer.className = "splitview";
		this.outlineContainer = $(document.createElement("div"));
		this.outlineContainer.className = "outline";
		this.ganttContainer = $(document.createElement("div"));
		this.ganttContainer.className = "gantt";
		this.activitiesContainer.appendChild(this.splitViewContainer);
		this.splitViewContainer.appendChild(this.outlineContainer);
		this.splitViewContainer.appendChild(this.ganttContainer);
		domNode.appendChild(this.activitiesContainer);
		this.setGanttRuler(ganttRuler);		
		this.splitView = this.showPrintView ? new SplitView(this.splitViewContainer, 400, 0, 0) : new SplitView(this.splitViewContainer, 400, 9, 1);
		this.splitView.setEnableInteraction(!this.showPrintView);
		this.splitView.setDelegate(this);
		this.outlineView = new OutlineView(this.outlineContainer, this.outlineController, 20, null, !showPrintView, environment, showPrintView);
		if(this.isBeingExportedForQuicklook)
			this.outlineView.setEnableDrags(false);
		this.outlineView.setDelegate(this);		
		this.outlineView.setBlockRefresh(true);
		this.setColumns(columns);		
		this.setRootActivities(this.rootObjectsInManagedObjectContext(this.moc), true);
		this.ganttScrollView = new GanttScrollView(this.ganttContainer, this.outlineView, !this.showPrintView, this.ganttRuler, this.environment, delegate);			
		this.freshGanttScrollView = true;
		this.setStyleList(new StyleList(styleList, environment));
		this.setViewOptions(viewOptions);
		this.outlineView.setBlockRefresh(false);
		if(this.ganttScrollView)
			this.ganttScrollView.setBlockRefresh(false);
		this.outlineView.refresh();						
		this.outlineView.setXScrollBarType(this.showPrintView ? "hidden" : "scroll");
		this.ganttScrollView.setEnableScrollBars(!this.showPrintView);
		this.updateControlsEnabledStatus();
	},

	registerClickInBody: function() {
		PWUtils.observe($$('body')[0], "click", this.handleClick.bindAsEventListener(this), false, true);
	},

	setIsVisible: function(flag){
		this.outlineView.setEnableDrops(flag);	
	},

	displayGraphs: function(){
		return false;
	},			
						
	rootObjectsInManagedObjectContext: function(aMoc){
		var result = [];
		if(aMoc){
			for(var key in aMoc.registeredObjects){
				var object = aMoc.registeredObjects[key]; 
				if(object.className() == "MEProject" && !object.valueForKey("linkedParentActivity") && !object.valueForKey("projectLink")) {
					result.push(object);
				}
			}
		}
		return result;
	},	
		
	setDelegate: function(delegate){	
		this.delegate = delegate;
	},

	setColumns: function(columns){
		this.columns = columns;
		this.outlineView.setColumnsAndOutlineColumnKey(columns, "title");
	},
	
	setStyleList: function(styleList){
		this.styleList = styleList;
		if(this.ganttScrollView)
			this.ganttScrollView.setStyleList(styleList);
	},
	
	setGanttRuler: function(ruler){
		this.ganttRuler = ruler;
	},
	
	setViewOptions: function(viewOptions){
		this.viewOptions = viewOptions;		
		if(this.ganttScrollView)
			this.ganttScrollView.setViewOptions(viewOptions);
	},
	
	setRootActivities: function(activities, update){
		this.outlineController.setRootObjects(activities);
		this.ganttRuler.setLimitingActivities(activities);
		if(update)
			this.outlineView.updateTableBody();
	},
	
	splitterChangedAction: function(splitter){
		this.delegate.splitterPosition = splitter.position();
		if(splitter.secondDiv.offsetWidth == 0)	// ganttWidth
			this.outlineView.contentContainer.style.overflowY = "auto";
		else
			this.outlineView.contentContainer.style.overflowY = "hidden";
		this.containerSizeChanged();	
	},

	moveSplitterAction: function(splitter){
		this.containerSizeChanged();
	},
	
	containerSizeChanged: function(){
		this.outlineView.containerSizeChanged();
		if(this.ganttScrollView)
			this.ganttScrollView.containerSizeChanged();	
	},
	
	willMoveSplitterAction: function(splitter){
		this.outlineView.contentContainer.style.overflowY = "hidden";
		this.outlineView.headerContainer.style.right = "0px";
	},

	outlineChanged: function(outline, rows){		
		if(this.ganttScrollView){
			this.ganttScrollView.outlineViewChanged(rows);
			this.freshGanttScrollView = false;
		}
	},

	outlineHeightForRow: function(outline, row){
		var activity = row.object;
		var array = [];
		var h1 = this.styleList.flattenedStyleForTarget(StyleList.activityViewStyleTargets.MEStyleTargetRow, activity.valueForKey("styleConditionMask")).height;
		if(h1)
			array.push(h1);
		var h2 = this.styleList.flattenedStyleForTarget(StyleList.activityViewStyleTargets.MEStyleTargetOutline, activity.valueForKey("styleConditionMask")).fontSize;
		if(h2)
			array.push(h2);
		var h3 = this.styleList.flattenedStyleForTarget(StyleList.activityViewStyleTargets.MEStyleTargetBar, activity.valueForKey("styleConditionMask")).height;
		if(h3)
			array.push(h3+h3*0.2);
		var h4 = this.styleList.flattenedStyleForTarget(StyleList.activityViewStyleTargets.MEStyleTargetLabelLeft, activity.valueForKey("styleConditionMask")).fontSize;
		if(h4)
			array.push(h4+h4*0.5);
		var h5 = this.styleList.flattenedStyleForTarget(StyleList.activityViewStyleTargets.MEStyleTargetLabelMiddle, activity.valueForKey("styleConditionMask")).fontSize;
		if(h5)
			array.push(h5+h5*0.5);
		var h6 = this.styleList.flattenedStyleForTarget(StyleList.activityViewStyleTargets.MEStyleTargetLabelRight, activity.valueForKey("styleConditionMask")).fontSize;
		if(h6)
			array.push(h6+h6*0.5);
		var max = null;
		var value;
		for(var i=0; i<array.length; i++){
			value = array[i];
			if(!max || value>max)
				max = value;
		}
		var overlap = false;
		if(	this.viewOptions.displayMode != 3  
			&& activity.valueForKey("plannedStartDate") 
			&& activity.valueForKey("plannedEndDate") 
			&& (!activity.valueForKey("plannedStartDate").isEqual(activity.valueForKey("expectedStartDate")) || !activity.valueForKey("plannedEndDate").isEqual(activity.valueForKey("expectedEndDate")))){
			var x = this.ganttRuler.dateToPos(activity.valueForKey("expectedStartDate"));
			var width = this.ganttRuler.dateToPos(activity.valueForKey("expectedEndDate"))-x;	
			plannedX = this.ganttRuler.dateToPos(activity.valueForKey("plannedStartDate"));
			plannedWidth = this.ganttRuler.dateToPos(activity.valueForKey("plannedEndDate"))-plannedX;
			var end1 = x+width+2;
			var end2 = plannedX+plannedWidth+2;
			overlap = (end1>=plannedX && end1<=end2) || (x>=plannedX && x<=end2);
		}
		max = Math.floor(max);
		if(overlap && max < 16)
			max+=2;
		return max+3;
	},

	outlineDoubleClickInEmptyArea: function(outline, event) {
		if(this.delegate && this.delegate.outlineDoubleClickInEmptyArea)
			this.delegate.outlineDoubleClickInEmptyArea(outline, event);
	},
	
	outlineDidCreateRows: function(outline, rows){
		this.ganttScrollView.outlineDidCreateRows(outline, rows);
	},
	
	outlineRowsBecameVisible: function(outline, rows){
		this.ganttScrollView.outlineRowsBecameVisible(outline, rows);
	},

	outlineDidCreateCellInRow: function(outline, cell, row, editMode, isSelected){
		var activity = row.object;
		if(activity.className() == "MEAssignment" && cell.column == outline.outlineColumn){
			var image = $(document.createElement("img"));
			if(Prototype.Browser.IE && editMode){
				var height = parseInt(cell.style.lineHeight);
				image.style.top = (height-11)/2+"px";
			}
			image.style.position = "relative";
			image.width = 8;
			image.height = 10;
			image.style.left="-8px";
			image.style.marginRight="-8px";
			image.src = this.environment.images.AssignmentArrow;
			cell.appendChild(image);
		}
		var mask = activity.valueForKey("styleConditionMask");
		if(activity.valueForKey('hasConflicts'))
		{
			var maxLevel = [activity.maximumLevelInConflictsForKey(cell.column.key)];
			if(maxLevel>=100)
				mask |= 1<<StyleList.styleConditions.MEActivityStyleConditionConflict;
			else if(maxLevel>=50)
				mask |= 1<<StyleList.styleConditions.MEActivityStyleConditionWarning;
			cell.keepOriginalColorInSelection = maxLevel > 0;
		}
		var style = this.styleList.flattenedStyleForTarget(StyleList.activityViewStyleTargets.MEStyleTargetOutline, mask);			
		if(style.fontSize) 
			cell.style.fontSize = style.fontSize+"px";
		if(style.fontWeight)
			cell.style.fontWeight = style.fontWeight;
		if(style.fontStyle)
			cell.style.fontStyle = style.fontStyle;
		if(style.fontStretch)
			cell.style.fontStretch = style.fontStretch;
		if(style.fontFamily)
			cell.style.fontFamily = style.fontFamily;
		if(style.color){		
			cell.style.color = style.color;
			cell.originalColor = style.color;
		}else
			cell.originalColor = "#000000";

		if(activity.className() == "MEProjectLink" && !activity.valueForKey("targetProject")) {
			var gray = "#707070";
			cell.style.color = gray;
			cell.originalColor = gray;
		}

		if(isSelected && !cell.keepOriginalColorInSelection)
			cell.style.color = "#ffffff";
	},
	
	outlineDidChangeSelection: function()
	{
		var objects = this.outlineView.controller.selectedObjects;
		this.parentIDs = [];
		for(var i=0; i<objects.length; i++){
			var parent = this.outlineController.indentationParentObjectForObject(objects[i]);
			this.parentIDs.push(parent ? parent.objectID.uri : "0");
		}
		if(this.ganttScrollView)
			this.ganttScrollView.refreshSelection(objects);
	},
	
	outlineViewDidCreateDisclosureButtonForRow: function(outline, button, row){
		if(row.object.hasAssignments()){
			button.src = row.object.valueForKey("isCollapsed") ? this.environment.images.AssignmentDisclosureRight : this.environment.images.AssignmentDisclosureDown;
		}
	},
	
	outlineShouldShowDisclosureButtonForObject: function(object) {
		return object.className() == "MEProjectLink";
	},

	outlineShouldExpandObject: function(object) {
		var expand = true;
		if(object.className() == "MEProjectLink") {
			if(!object.valueForKey("targetProject"))
					expand = this.delegate && this.delegate.loadProjectLink ? this.delegate.loadProjectLink(object) : false;
		}
		return expand;
	},

	handleClick: function(event){
		var event = event || window.event;	// Damit Comboboxen ihr Popup-Fenster schliessen, wenn in die Umgebung geklickt wird
		PWUtils.notificationCenter.sendMessage("click", event);
	},

	zoomIn: function(){
		this.ganttScrollView.zoomIn();
//		this.ganttScrollView.refreshSelection(this.outlineController.selectedObjects);
	},

	zoomOut: function(){
		this.ganttScrollView.zoomOut();	
//		this.ganttScrollView.refreshSelection(this.outlineController.selectedObjects);
	},
	
	endEditing: function(){
		this.outlineView.endEditing();
	},

	canIndentActivity: function(){
		var selectedObjects = this.outlineController.selectedObjects;
		var object;
		if(selectedObjects && selectedObjects.length){
			for(var i=0; i<selectedObjects.length; i++){
				object = selectedObjects[i];
				if(object.className() != "MEAssignment" && this.outlineController.isObjectIndentable(object))
					return true;
			}
		}
		return false;
	},

	canOutdentActivity: function(){
		var selectedObjects = this.outlineController.selectedObjects;
		var object;
		if(selectedObjects && selectedObjects.length){
			for(var i=0; i<selectedObjects.length; i++){
				object = selectedObjects[i];
				if(object.className() != "MEAssignment" && this.outlineController.isObjectOutdentable(object))
					return true;
			}
		}
		return false;
	},

	setActivitiesCollapsed: function(activities, collapsed, noRefresh) {
		var update = false;
		for(var i=0; i<activities.length; i++) {
			var activity = activities[i];

            //ak Quick test if project links can be loaded automatically.
            //			if(activity.className() == "MEProjectLink")
            //				this.delegate.loadProjectLink(activity);

			var children = activity.valueForKey(this.outlineController.childrenKey);			
			if(children && children.length)	{
				var state = activity.valueForKey(this.outlineController.isCollapsedKey);
				if(state != collapsed) {
					activity.setValueForKey(collapsed, this.outlineController.isCollapsedKey);
					update = true;
				}
			}
		}
		if(update && !noRefresh)
			this.refresh();	
	},

	collapseAll: function() {
		var activities = this.outlineController.getAllObjects().reject(function(object){
			return object.className() == "MEProject";
		}, this);
		this.setActivitiesCollapsed(activities, true);
	},

	expandAll: function() {
		var activities = this.outlineController.getAllObjects().reject(function(object){
			return object.hasAssignments && object.hasAssignments();
		}, this);
		this.setActivitiesCollapsed(activities, false);
	},
	
	hideAllAssignments: function() {
		var activities = this.outlineController.getAllObjects().findAll(function(object){
			return object.hasAssignments && object.hasAssignments();
		}, this);
		this.setActivitiesCollapsed(activities, true);		
	},

	showAllAssignments: function() {
		var activities = this.outlineController.getAllObjects().findAll(function(object){
			return object.hasAssignments && object.hasAssignments();
		}, this);
		this.setActivitiesCollapsed(activities, false);			
	},
	
	showOutlineLevel: function(level) {
		var update = false;
		var activities = this.outlineController.getAllObjects().reject(function(activity){
			return activity.hasAssignments && activity.hasAssignments();
		}, this);
		var result = activities.partition(function(activity){
			return activity.level <= level-1;
		}, this)
		if(result[0].length) {
			update = true;
			this.setActivitiesCollapsed(result[0], false, true);
		}
		if(result[1].length) {
			update = true;
			this.setActivitiesCollapsed(result[1], true, true);
		}
		if(update) {
			this.moc.synchronize();
			this.refresh();
		}
	},
	
	minOutdentLevel: function(){
		return 1;
	},

	canAddActivity: function(){
		return true; //this.outlineController.selectedObjects.length > 0;
	},
	
	canAddAssignment: function(){
		if(this.outlineController.selectedObjects.length != 1)
			return false;
		if(this.outlineController.selectedObjects.length == 1 && this.outlineController.selectedObjects[0].className() == "MEProject")
			return false;
		var subActivities = this.outlineController.selectedObjects[0].valueForKey("linkedSubActivities");	
		if(subActivities && subActivities.length && subActivities[0].className() != "MEAssignment")
			return false;
		return true;
	},
	
	canDeleteActivity: function(){
		if(this.outlineController.selectedObjects.length == 1 && this.outlineController.selectedObjects[0].className() == "MEProject")
			return false;
		else
			return this.outlineController.selectedObjects.length > 0 && this.outlineController.flatObjects.length > 1;
	},	
	
	canChainActivities: function() {
		return this.outlineController.selectedObjects.length > 1;
	},
	
	updateControlsEnabledStatus: function(){
		if(this.hasControls && this.chainActivitiesButton){
			this.chainActivitiesButton.setEnabled( this.canChainActivities() );
			this.addActivityButton.setEnabled( this.canAddActivity() );
			this.indentButton.setEnabled( this.canIndentActivity() );
			this.outdentButton.setEnabled( this.canOutdentActivity() );
		}
	},
	
	selectionChanged: function(outline, selectedObjects){
		this.updateControlsEnabledStatus();
	},

	synchronizeWithServer: function(){
		var me = this;
		onSuccess = function(result){
			me.outlineView.refresh();
		}
		this.moc.synchronize(onSuccess);
	},
	
	refresh: function(refreshSelection){
		this.outlineView.refresh();
		if(refreshSelection)
			this.outlineDidChangeSelection(this);
		this.updateControlsEnabledStatus();
	},
	
	refreshRuler: function() {
		this.ganttScrollView.ganttRulerView.refreshRuler();
		this.ganttScrollView.containerSizeChanged();		
	},
	
	outlineShouldEditObjectProperty: function(outline, object, key){
		return this.delegate.shouldEditObjectProperty(object, key);
	},
	
//	outlineValidateValueForKeyOfObject: function(outline, objectValue, stringValue, key, object, validationDidEndHandler) {
//		
//	},
//
//	outlineValidatePropertyOfObject: function(outline, property, object, validationDidEndHandler){
//		this.validationDidEndHandler = validationDidEndHandler;
//		this.delegate.validatePropertyOfObject(this, property, object, this.delegateDidValidateProperty);
//	},
	
	delegateDidValidateProperty: function(result){
		result = eval("("+result+")");
		if(result.validated){
			var object = this.moc.registeredObjectWithURIString(result.objectID);
			if(object){ 
				var value = object.createValueForPropertyFromJSON(result.propertyName, result.value);
				object.setValueForKey(value, result.propertyName);				
				this.moc.synchronize();
				this.validationDidEndHandler.call(this.outlineView, result);
			}
		}
	},
	
	outlineViewShouldHandleClickInRow: function(outlineView, row){
		if(window["datePickerIsVisible"]  && datePickerIsVisible()){
			closeCalendar();
			return false;
		}
		return true;
	},
	
	setVisibleOutlineWidth: function(width){
		this.splitView.setSplitterPosition(width);
	},

	// ************************************************************************************************************
	// *****
	// *****										Drag and Drop
	// *****
	
	outlineShouldDragRows: function(outline, rows){
		if(this.delegate.outlineShouldDragRows)
			return this.delegate.outlineShouldDragRows(outline, rows);
		return false;
	},
	
	outlineValidateDrop: function(outline, location, pasteboard){		
		if(this.delegate.outlineValidateDrop)
			return this.delegate.outlineValidateDrop(outline, location, pasteboard);
		return false;
	},

	outlineAcceptDrop: function(outline, location, pasteboard){
		if(this.delegate.outlineAcceptDrop)
			this.delegate.outlineAcceptDrop(outline, location, pasteboard);
	}

});
