// Copyright 2008 ProjectWizards GmbH. All rights reserved.

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

/*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *	
 *	MEManagedObjectContext
 *
 */

var MEManagedObjectContext = WRLAjaxContext.extend({
	constructor: function(serverContextID, requestURL) {
		this.base(serverContextID, requestURL);		
	},
	
	rootProject: function(){
		var rootProject = null;
		var objects = Object.values(this.registeredObjects);
		for(var i=0; i<objects.length; i++) {
			var object = objects[i];
			if(object.className() == "MEProject" && !object.valueForKey("linkedParentActivity")) {
				rootProject = object;
				break;
			}
		}		
		return rootProject;
	}
	
});




/*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *	
 *	MEActivity
 *
 */

var eDurationUnit;
if(!eDurationUnit) eDurationUnit = {    
	MESeconds: 0,  
	MEMinutes: 1,  
	MEHours: 2,
	MEDays: 3,
	MEWeeks: 4,
	MECalendarWeeks: 5,
	MEMonths: 6,
	MEQuarterYears: 7,
	MEYears: 8,
	MENoUnit: 19,
	MEFraction: 20,
	MEMaterialUnit: 21,
	MESpecialCompareUnit: 22
}

var MEStart = false;
var MEEnd = true;

var MEItem = WRLManagedObject.extend({
	constructor: function(context, objectID, properties){
		this.base(context, objectID, properties);
	},
	
	sortValueForKey: function(key){	
		var value = this.valueForKey(key);
		if(value && value.sortValue){
			if(this.descriptionForProperty(key).className == "MEDuration")
				value = value.sortValue(this.valueForKeyPath("project.manDayHours"), this.valueForKeyPath("project.manWeekHours"));
			else
				value = value.sortValue();
		}else if(typeof value == 'string'){
			if(key == 'wbsCode') {
				value = this.valueForKeyPath("flatOrder");
			}else
				value = value.toLowerCase();
		}
		return value;
	}
});

var MEActivity = MEItem.extend({
	constructor: function(context, objectID, properties){
		this.base(context, objectID, properties);
	},
	
	hasAssignments: function(){
		var subActivities = this.valueForKey("linkedSubActivities");
		if(subActivities) {
			for(var i=0; i<subActivities.length; i++){
				if(subActivities[i].className() == "MEAssignment")
					return true;
			}
		}
		return false;
	},
	
	isLeaf: function(){
		var subActivities = this.valueForKey("linkedSubActivities");
		return !(subActivities && subActivities.length);
	},
	
	isGroup: function(){
		return !this.isLeaf();
	},
	
	linkedSubActivities: function(){
		return this.valueForKey("subActivities");
	},

	linkedParentActivity: function(){
		var parent = this.valueForKey("parentActivity");
		var link = parent ? parent.valueForKey("projectLink") : null;
		return link ? link : parent;
	},
	
//	isMilestone: function(){
//		var start = this.valueForKey("expectedStartDate");
//		var end = this.valueForKey("expectedEndDate");
//		return (start && end && start.getTime() == end.getTime());
//	},
		
	project: function(){
		if(!this._project){
			var activity = this;
			while(activity.valueForKey("linkedParentActivity"))
				activity = activity.valueForKey("linkedParentActivity");
			this._project = activity;
		}
		return this._project;
	},
	
	utilizationTitle: function(){
		return this.valueForKey("title");
	},

	isAncestorOf: function(activity){
		if(!activity)
			return false;
		var parent = activity.valueForKey("linkedParentActivity");
		return (parent == this) ? true : this.isAncestorOf(parent);
	},
	
	styleConditionMask: function() {
		var result = this.properties.styleConditionMask;
		if(!this.isLeaf()) {
			if(this.valueForKey('isCollapsed')) {
				result |= (1<<StyleList.styleConditions.MEActivityStyleConditionCollapsed);
				result &= ~(1<<StyleList.styleConditions.MEActivityStyleConditionExpanded);
			}else{
				result &= ~(1<<StyleList.styleConditions.MEActivityStyleConditionCollapsed);
				result |= (1<<StyleList.styleConditions.MEActivityStyleConditionExpanded);
				result &= ~(1<<StyleList.styleConditions.MEActivityStyleConditionCritical);
			}
		}
		return result;	
	},
	
	maximumLevelInConflictsForKey: function(key) {
		return 0;	// TODO: MEConflicts mit übertragen 
	},

	subActivityWithTitle: function(title) {
		var subActivities = this.linkedSubActivities();		
		for(var i=0; i<subActivities.length; i++) {
			var activity = subActivities[i];
			if(activity.valueForKey("title") == title)
				return activity;
		}
		return null;
	},

	subActivityWithTitlePath: function(titlePath) {
		var index = titlePath.indexOf(".");
		if(index == -1)
			return this.subActivityWithTitle(titlePath);
		else{
			var firstTitle = titlePath.substring(0, index);
			var activity = this.subActivityWithTitle(firstTitle);
			return activity ? activity.subActivityWithTitlePath(titlePath.substring(index+1)) : null;
		}
	}
	
});


var InfoIconsIndices = WRLObject.extend({
	constructor: function(json){
		this.base();
		this.indices = json;
	}
});

/*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *	
 *	MEActivityRelationship
 *
 */

var relID = 0;

var MEActivityRelationship = WRLManagedObject.extend({
	constructor: function(context, objectID, properties){
		this.base(context, objectID, properties);
		this.ID = relID;
		relID++;
	}
	
},{	// Class interface
	MEFinishToStartRelationship: 0,			
	MEStartToStartRelationship: 1,
	MEFinishToFinishRelationship: 2,
	MEStartToFinishRelationship: 3,
	MENoRelationship: -1

/*
	isRelationshipOfKindPossibleBetweenActivityAndActivity: function(kind, previous, next){
		if(previous == next || !previous || !next)
			return false;
		if(previous.valueForKey("project") != next.valueForKey("project"))
			return false;
		if(!previous.valueForKey("mayBeManagedByCurrentUser")] || !next.valueForKey("mayBeManagedByCurrentUser"))
			return false;
		if((kind == MEActivityRelationship.MEFinishToFinishRelationship || kind == MEActivityRelationship.MEStartToFinishRelationship) && next.isGroup())
			return false;
			
		var project = previous.valueForKey("project");
		
		if(kind == MEActivityRelationship.MEFinishToStartRelationship)
			return !project.hasPathFromSideOfActivityToSideOfActivity(MEStart, next, MEEnd, previous);
		else if(kind == MEActivityRelationship.MEStartToStartRelationship)
			return !project.hasPathFromSideOfActivityToSideOfActivity(MEStart, next, MEStart, previous) && !project.hasPathFromSideOfActivityToSideOfActivity(MEStart, next, MEEnd, previous);
		else if(kind==MEActivityRelationship.MEFinishToFinishRelationship)
			return !project.hasPathFromSideOfActivityToSideOfActivity(MEEnd, next, MEEnd, previous) && !project.hasPathFromSideOfActivityToSideOfActivity(MEStart, next, MEEnd, previous);
		else if(kind==MEActivityRelationship.MEStartToFinishRelationship)
			return !project.hasPathFromSideOfActivityToSideOfActivity(MEEnd, next, MEStart, previous) && !project.hasPathFromSideOfActivityToSideOfActivity(MEStart, next, MEStart, previous) && !project.hasPathFromSideOfActivityToSideOfActivity(MEEnd, next, MEEnd, previous);
		return false;
	},
		
	isRelationshipOfKindPossibleAndNotDispensibleBetweenActivityAndActivity: function(kind, previous, next){
		return MEActivityRelationship.isRelationshipOfKindPossibleBetweenActivityAndActivity(kind, previous, next)
			&& !MEActivityRelationship.isRelationshipOfKindDispensableBetweenActivityAndActivity(kind, previous, next);
	},
				
	canChainActivitiesUsingRelationshipKind: function(activities, kind) {
		var count = activities.length;
		for(var index=0; index<count-1; index++)
		{
			var prev = activities[index];
			var next = activities[index+1];
			if( MEActivityRelationship.isRelationshipOfKindPossibleAndNotDispensibleBetweenActivityAndActivity(kind, prev, next))
				return true;
		}
		return false;
	}
*/
														
});

/*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *	
 *	MEAssignment
 *
 */

var print = true;

var MEAssignment = MEActivity.extend({
	constructor: function(context, objectID, properties){
		this.base(context, objectID, properties);
	},
	
	utilizationTitle: function(){
		return this.valueForKeyPath("linkedParentActivity.title");
	}	
	
});

/*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *	
 *	MEProject
 *
 */

var MEProject = MEActivity.extend({
	constructor: function(context, objectID, properties){
		this.base(context, objectID, properties);
	},
	
	sortedRoles: function(){
		var result = [];
		var roles = this.valueForKey("roles");
		if(roles){
			roles = roles.clone();
			for(var i=0; i<roles.length; i++){
				var role = roles[i];
				result[parseInt(role.valueForKey("displayOrder"))] = role;
			}
		}
		return result;
	},
	
	hasPathFromSideOfActivityToSideOfActivity: function(startSide, startActivity, endSide, endActivity) {
		
	},
	
	resourceWithTitle: function(title)
	{
		var resources = this.valueForKey('resources');
		for(var i=0; i<resources.length; i++) {
			var resource = resources[i];
			if(resource.valueForKey('title') == title)
				return resource;
		}
		return null;
	}	
	
},{
	rootProjectInManagedObjectContext: function(moc){
		if(moc){
			for(var key in moc.registeredObjects){
				var object = moc.registeredObjects[key]; 
				if(object.className() == "MEProject" && !object.valueForKey("linkedParentActivity")) {
					return object;
				}
			}
		}
		return nil;
	}
});

/*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *	
 *	MEProjectLink
 *
 */

var MEProjectLink = MEActivity.extend({
	constructor: function(context, objectID, properties){
		this.base(context, objectID, properties);
	},
	
	linkedSubActivities: function(){
		var target = this.valueForKey("targetProject");
		return target ? target.valueForKey("subActivities") : [];
	}
},{
	CouldNotAccessProject: 15002,
	ProjectLinkCouldNotFindTargetProject: 15000
});


/*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *	
 *	MEResource
 *
 */

var MEResource = MEItem.extend({
	constructor: function(context, objectID, properties){
		this.base(context, objectID, properties);
	},
	
	projectTitle: function(){
		return this.valueForKeyPath("project.title");
	},
	
	validateValueForKey: function(value, key) {
		if(key == "role" && typeof value == "string")
			return true;
		return this.base(value, key);
	}
	
},{
	MEResourceType: {	MEPersonResource:0,			
						MEMaterialResource:1,		
						MECompanyResource:2,
						MEEquipmentResource:3	}
});


/*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *	
 *	MEResourceGroup
 *
 */

var MEResourceGroup = MEItem.extend({
	constructor: function(context, objectID, properties){
		this.base(context, objectID, properties);
	}

/*	,
	resources: function(){
		return this.valueForKey("resources");
	}
*/	
	
});


/*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *	
 *	MEMasterResource
 *
 */

var MEMasterResource = MEItem.extend({
	constructor: function(context, objectID, properties){
		this.base(context, objectID, properties);
		this.properties.isCollapsed = true;
	},

	isLeaf: function(){
		var assignments = this.valueForKey("assignments");
		return !(assignments && assignments.length);
	},

	utilizationTitle: function(){
		return this.valueForKey("title");
	},
	
	sortValueForKey: function(key){	
		var result;
		if(!this.valueForKey('resources').length && key == "utilizationTitle") {
			result = "----";
		} else {
			result = this.base(key);
		}
		return result;
	},

	// Methods to make this object compatible with the gantt view.
	linkedSubActivities: function(){
		return this.valueForKey("resources");
	},
	
	isMilestone: function(){
		return false;
	},
	
	flagStatus: function(){
		return this.valueForKey("automaticFlagStatus");
	},

	givenFlagStatus: function(){
		return this.valueForKey("automaticFlagStatus");
	}	
	
});

/*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *	
 *	MERole
 *
 */

var MERole = MEItem.extend({
	constructor: function(context, objectID, properties){
		this.base(context, objectID, properties);
	}
	
});


/*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *	
 *	AllProjectsItem
 *
 */

var AllProjectsItem = WRLObject.extend({
	constructor: function(moc, environment){
		this.base();
		this.environment = environment;
		this.objectID = {uri:'AllProjectsItem'};
		this.title = this.environment.localizedString("All Projects");
		this.moc = moc;
	},
	
	resourceGroups: function(){
		return [];
	},
	
	title: function(){
		return title;
	},
	
	sortValueForKey: function(key){	
		return '----';
	},
	
	className: function(){
		return "AllProjectsItem";
	},	
	
	resources: function(){
		var resources = [];
		for(var key in this.moc.registeredObjects){
			var object = this.moc.registeredObjects[key]; 
			if(object.className() == "MEProject"){
				var r = object.valueForKey("resources");
				r.each(function(item){
					if(resources.indexOf(item) == -1)
						resources.push(item);
				});
			}
		}
		return resources;				
	}		
});


/*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *	
 *	MEWorkspace
 *
 */

var MEWorkspace = MEItem.extend({
	constructor: function(context, objectID, properties){
		this.base(context, objectID, properties);
	}
	
},{

	filteredWorkspacesForSingleViewSinglePart: function(workspaces, singleView, singlePart) {
		var result = [];
		if(workspaces.length) {		
			workspaces.each(function(workspace){
				var view = workspace.valueForKey("singleSettingView");
				var part = workspace.valueForKey("singleSettingPart");
				if(((!singleView && !singlePart) && (!view || !part)) || (singleView == view && singlePart == part))
					result.push(workspace);
			
			});			
		}
		return result;
	}

});

