/*
 * (c) Copyright Trilog Group 2004-2012. All Rights Reserved.
 */

function run() {
}
/*
 * initializeIdTable
 * Initializes rows in the FB__SEQID so that when rows are imported during the deployment
 * the last id won't be 0 (but actually the last id of that view).
 * This function is usually code from the deployment file.
 */

function checkIfParentChanged(document){
	try{
		var inherit = true; //document.getBooleanValue("//metadata/security/inherit");
		var rootNode = document.getRootElement();
		inherit = rootNode.getBooleanValue("metadata/security/inherit");
		
		if(!document.isNewDocument() && inherit){
			var siteID = rootNode.getChildText("siteid");
			var projectID = rootNode.getChildText("projectid");
			var schema = document.getSchema();
			//get current parent ID
			var newParentID = "";
			var documentID = "";
			if(schema=="pe_task"){
				newParentID = rootNode.getChildText("wbsid");
				documentID = rootNode.getChildText("id");
			}else if (schema == "pe_wbs"){
				newParentID = rootNode.getChildText("category");
				documentID = rootNode.getChildText("uid");
			}
			
			//get old parent id
			var oldParentID = session.getLookupValue("tg_pe_schedule","alltasksandwbsbysiteidprojectidandid",siteID+"|"+projectID+"|"+documentID,"wbscategory");

			//if parent ID changed, remove existing security and inherit security from parent
			if(oldParentID!=newParentID){
				//get parent document
				var db = document.getDatabase();
				var parentDocument = db.getDocumentByKey("allwbsbysiteidprojectidandwbsid",new Array(siteID,projectID,newParentID));

				if(parentDocument!=null){
					//start by removing the existing security node
					var metadataNode = rootNode.getChild("metadata");
					if (metadataNode != null) {
						var securityNode = metadataNode.getChild("security");
						if(securityNode!=null){
							securityNode.detach();
						}
					}
					//attach parent security node
					var parentSecurityNode = parentDocument.getRootElement().nodes("metadata/security")[0];
					if(parentSecurityNode!=null){
						if(metadataNode == null){
							metadataNode = new DOMElement("metadata");	
							var root = document.getRootElement();
							root.addContent(metadataNode);
						}
						var securityClone = parentSecurityNode.clone();
						securityClone.setBooleanValue("inherit",inherit);
						metadataNode.addContent(securityClone);
					}
				}
			}
		}
	}catch(e){
		print("Error executing checkIfParentChanged method for " + document.getSchema() + " " + document.getId());
		print(e.toString());
	}
}

function getDefaultSecurityDocument(securityDB,schema,siteID,projectID){
	if(schema=="pe_issue_type"){
		return securityDB.getDocumentByKey("alldefaultsecuritiesbysiteidandschema",new Array(siteID,schema));
	}else{
		return securityDB.getDocumentByKey("alldefaultsecuritiesbysiteidprojectidandschema",new Array(siteID,projectID,schema));
	}
}

function propagateSecurity(document){
	com.triloggroup.pe.util.InitializationUtil.propagateSecurity(document);
}


function populateScheduleSecurity(document){
	com.triloggroup.pe.util.InitializationUtil.populateScheduleSecurity(session, document);
}

function populateFolderSecurity(document){
	//check if security is already added
	var rootNode = document.getRootElement();
	var securityNode = rootNode.nodes("metadata/security");
	if(securityNode.length==0){
		//this means security isn't added
		var siteID = rootNode.getChildText("siteid");
		var projectID = rootNode.getChildText("projectid");
		if(siteID != ""){
			//get default security document
			var securityDB = null;
			var schema = document.getSchema();
			try{
				securityDB = session.openDatabase("tg_pe_security");
				var securityDoc = getDefaultSecurityDocument(securityDB,schema,siteID,projectID);
				if(securityDoc!=null){
					var parentId = document.getStringValue("/folder/parentid");	
					if(parentId != "" && parentId != null){
						//get the parent security
						inheritParentSecurity(document);
					}else{
						attachSecurity(securityDoc,document);
					}
				}
			}catch(e){
				print(e.toString());
			}finally{
				if(securityDB!=null){
					securityDB.close();
				}
			}
		}
	}
}

function populateDefaultSecurity(document){
	try{
		//check if security is already added
		var rootElt = document.getRootElement();
		var securityNode = rootElt.nodes("metadata/security");
		if(securityNode.length!=0) return;
		
		//this means security isn't added
		var siteID = rootElt.getStringValue("siteid");
		var projectID = rootElt.getStringValue("projectid");
		if(siteID != ""){
			//get default security document
			var securityDB = null;
			var schema = document.getSchema();
			if(schema=="pe_issue_type" || schema=="pe_changerequest"){
				//copy default security from security database
				try{
					securityDB = session.openDatabase("tg_pe_security");
					var securityDoc = getDefaultSecurityDocument(securityDB,schema,siteID,projectID);
					if(securityDoc!=null){
						attachSecurity(securityDoc,document);
					}
				}catch(e){
					e.printStackTrace();
				}finally{
					if(securityDB!=null) securityDB.close();
				}
			}else if(schema=="pe_support_request"){
				//copy default security from issue type
				var issueType = document.getStringValue("/supportrequest/type");
				if(issueType!=""){
					var supportDB = null;
					try{
						supportDB = session.openDatabase("tg_pe_support");
						var doc = supportDB.getDocumentByKey("allissuetypesbysiteidprojectidandid",new Array(siteID,projectID,issueType));
						if(doc!=null){
							attachSecurity(doc,document);
						}
					}catch(e){
						e.printStackTrace();
					}finally{
						if(supportDB!=null){
							supportDB.close();
						}
					}
				}
			}else if(schema=="pe_discussion"){
				// not used anymore

			}else if (schema=="tg_reportDef"){
				try{
					securityDB = session.openDatabase("tg_pe_security");
					var doc = securityDB.getDocumentByKey("alldefaultsecuritiesbysiteidandschema",new Array(siteID,schema));
					if(doc!=null){
						attachSecurity(doc,document);
					}
				}catch(e){
					print(e.toString());
				}finally{
					if(securityDB!=null) securityDB.close();
				}
			}else if (schema=="pe_portfolio"){
				try{
					securityDB = session.openDatabase("tg_pe_security");
					var doc = securityDB.getDocumentByKey("alldefaultsecuritiesbysiteidandschema",new Array(siteID,schema));
					if(doc!=null){
						attachSecurity(doc,document);
					}
				}catch(e){
					print(e.toString());
				}finally{
					if(securityDB!=null) securityDB.close();
				}
			}
		}
	}catch(e){
		print("Error while populating default security for " + document.getSchema() + " " + document.getId());
		e.printStackTrace();
	}
}

function inheritParentSecurity(document){
	var rootNode = document.getRootElement();
	var siteID = rootNode.getChildText("siteid");
	var projectID = rootNode.getChildText("projectid");
	var schema = document.getSchema();
	var securityNode = null;
	

	var parentWBSID = "";
	if(schema=="pe_task"){
		parentWBSID = document.getStringValue("/task/wbsid");
	}else{
		parentWBSID = document.getStringValue("/wbs/category");
	}
	var scheduleDB = document.getDatabase();
	var parentWBSDocument = scheduleDB.getDocumentByKey("allwbsbysiteidprojectidandwbsid",new Array(siteID,projectID,parentWBSID));
	if(parentWBSDocument!=null){
		securityNode = parentWBSDocument.getRootElement().nodes("metadata/security")[0];
	}
	
	if(securityNode!=null){
		//set the inherited flag to true in all the entries
		var entries = securityNode.nodes("//entry");
		for(var i=0;i<entries.length;i++){
			entries[i].setStringValue("inherited","true");
		}	
		//attach security to the document
		var metadataNode = rootNode.getChild("metadata");
		if(metadataNode == null){
			metadataNode = new DOMElement("metadata");	
			var root = document.getRootElement();
			root.addContent(metadataNode);
		} else {		
			var oldSecurityNode = metadataNode.getChild("security");
			if (oldSecurityNode != null) {
				oldSecurityNode.detach();
			}
		}
		securityNode.detach();
		securityNode.setBooleanValue("inherit",true);
		metadataNode.addContent(securityNode);
	}else{
		print("Parent not set for " + schema + " document with id " + document.getId() + ", therefore no security could be attached"); 
	}
}

function attachSecurity(securityDoc,document){
	var securityNode = securityDoc.nodes("//security")[0];;
	if (securityNode != null) {
		//attach security to the document
		var root = document.getRootElement();
		var metadataNode = root.getChild("metadata");
		if(metadataNode == null){
			metadataNode = new DOMElement("metadata");
			root.addContent(metadataNode);
		}
		securityNode.detach();
		metadataNode.addContent(securityNode);
	}	
}

function updateDefaultSecurity(siteID){
	import pe_util;
	import pe_internationalization;

	//check for existing default security documents
	//these schema will have default security per site
	var allGlobalSchemas = new Array("pe_issue_type","tg_reportDef","pe_portfolio");
	var globalFilePaths = new Array("/projexec/data/pe_defaultsecurity_support.xml","/projexec/data/pe_defaultsecurity_report.xml","/projexec/data/pe_defaultsecurity_portfolio.xml");
	
	var securityDB = null;
	try{
		securityDB = session.openDatabase("tg_pe_security");
		
		//check for global default security documents
		var definedGlobalSchemas = session.getLookupValues("tg_pe_security","alldefaultsecuritiesbysiteidandschema",siteID,"schema");
		for(var i=0;i<allGlobalSchemas.length;i++){	
			if(!inArray(allGlobalSchemas[i],definedGlobalSchemas)){
				try{
					//create default security document for this schema
					var doc = securityDB.createNewDocument("pe_defaultsecurity");
					var dom = doc.getDOM();
					dom.loadResource(globalFilePaths[i]);
					doc.setStringValue("/defaultsecurity/siteid",siteID);
					doc.save();
					doc.close();
				}catch(e){
					print(e.toString());
				}
			}
		}
		updateDefaultSecurityForProjects(siteID,securityDB);
	}catch(e){
		print(e.toString());
	}finally{
		if(securityDB!=null){
			securityDB.close();
		}
	}
}

function updateDefaultSecurityForProjects(siteID,securityDB){
	//get all projects on site
	var projectIDs = session.getLookupValues("tg_pe_project","allprojects",siteID,"id");
	for(var j=0;j<projectIDs.length;j++){
		var projectID = projectIDs[j];
		updateDefaultSecurityForProject(siteID,projectID,securityDB);
	}
}

function updateDefaultSecurityForProject(siteID,projectID,securityDB){
	import pe_util;
	import pe_administration_util;
	
	var closeSecurityDB = false;
	if(securityDB==null){
		try{
			securityDB = session.openDatabase("tg_pe_security");
			closeSecurityDB = true;
		}catch(e){
			print(e.toString());
			return;
		}
	}
	var isTemplate = isTemplate(siteID, projectID);
	
	var allLocalSchemas = new Array("pe_task","pe_wbs","pe_changerequest");
	var localFilePaths = new Array("/projexec/data/pe_defaultsecurity_task.xml","/projexec/data/pe_defaultsecurity_wbs.xml","/projexec/data/pe_defaultsecurity_change.xml");
	var definedLocalSchemas = session.getLookupValues("tg_pe_security","alldefaultsecuritiesbysiteidprojectidandschema",siteID+"|"+projectID,"schema");
	
	for(var i=0;i<allLocalSchemas.length;i++){
		if(!inArray(allLocalSchemas[i],definedLocalSchemas)){
			try{
				//create default security document for this schema
				var doc = securityDB.createNewDocument("pe_defaultsecurity");
				var dom = doc.getDOM();
				dom.loadResource(localFilePaths[i]);
				doc.setStringValue("/defaultsecurity/siteid",siteID);
				doc.setStringValue("/defaultsecurity/projectid",projectID);
				if (isTemplate) {
					doc.setBooleanValue("/defaultsecurity/istemplate", true);
				}	
				doc.save();
				doc.close();
			}catch(e){
				print(e.toString());
			}
		}
	}
	if(closeSecurityDB==true && securityDB!=null){
		securityDB.close();
	}
}	
	
// This method creates all the predefined roles that are not already present in the site
// from the file pe_predefinedroles.
function updatePredefinedRoles(siteId) {
	var securityDB = null;
	var predefinedRoles = null;
	try {
		securityDB = session.openDatabase("tg_pe_security");
		var siteLanguage=com.triloggroup.pe.util.PEUtil.getSiteLanguage(session,siteId);	
		var dom = new DOMDocument();
		var predefinedRoles="/projexec/data/pe_predefinedroles.xml";		
		dom.loadResource(predefinedRoles);			
		var predefinedRoleNodes = dom.nodes("/roles/role");
		
		var predefinedRoleIds=securityDB.getLookupValues("allpredefinedrolesbysiteidandid", siteId, "id");
		for(var i=0;i<predefinedRoleIds.length;i++){
			var doc=securityDB.getDocumentByKey("allpredefinedrolesbysiteidandid",new Array(siteId,predefinedRoleIds[i]));
			doc.remove();		
		}
		
		var peRoleIds = securityDB.getLookupValues("allrolesbysiteidandid", siteId, "id");

		for (var i = 0 ; i < predefinedRoleNodes.length; i++) {
			if (@IsMember(predefinedRoleNodes[i].getStringValue("id"), peRoleIds) == 0) {
				// new predefined role -> add it to the site
				var roleDoc = securityDB.createNewDocument("pe_role");
				roleDoc.setRootElement(predefinedRoleNodes[i].clone());
				var roleLabel = roleDoc.getStringValue("/role/label[@language='"+siteLanguage+"']");
				
				if (roleLabel == null || roleLabel == "") {
					roleLabel = roleDoc.getStringValue("/role/label");
				}	
				
				var labelsNode = roleDoc.nodes("/role/label");
				for (var j = 0 ; j < labelsNode.length ;j++) {
					labelsNode[j].detach();
				}	
				roleDoc.setStringValue("/role/label", roleLabel);		
				
				roleDoc.setBooleanValue("/role/predefined", true);
				roleDoc.setStringValue("/role/siteid", siteId);
				roleDoc.save();
			}	
		}			
	}
	catch (e) {
		e.printStackTrace();
	}	
	finally {
		if (securityDB != null) {
			securityDB.close();
		}	
	}	
}	


// This method creates all the predefined security profiles that are not already present 
// in the site from the file pe_predefinedsecurityprofiles.
function updatePredefinedSecurityProfiles(siteId) {
	var securityDB = null;
	try {
		securityDB = session.openDatabase("tg_pe_security");
		var siteLanguage=com.triloggroup.pe.util.PEUtil.getSiteLanguage(session,siteId);
		var dom = new DOMDocument();
		var predefSecProfiles="/projexec/data/pe_predefinedsecurityprofiles.xml"; 
		dom.loadResource(predefSecProfiles);		
		var predefinedSecurityProfiles = dom.nodes("/securityprofiles/securityprofile");
		
		var predefinedSecProfileIds=securityDB.getLookupValues("allpredefinedsecurityprofilesbysiteidandid", siteId, "id");
		for(var i=0;i<predefinedSecProfileIds.length;i++){
			var doc=securityDB.getDocumentByKey("allsecurityprofilesbysiteidandid",new Array(siteId,predefinedSecProfileIds[i]));
			doc.remove();		
		}
		
		var peSecurityProfileIds = securityDB.getLookupValues("allsecurityprofilesbysiteidandid", siteId, "id");

		for (var i = 0 ; i < predefinedSecurityProfiles.length; i++) {
			if (@IsMember(predefinedSecurityProfiles[i].getStringValue("id"), peSecurityProfileIds) == 0) {
				// new predefined role -> add it to the site
				var securityProfileDoc = securityDB.createNewDocument("pe_securityprofile");
				securityProfileDoc.setRootElement(predefinedSecurityProfiles[i].clone());
				
				var securityProfileLabel = securityProfileDoc.getStringValue("/securityprofile/label[@language='"+siteLanguage+"']");
				
				if (securityProfileLabel == null || securityProfileLabel == "") {
					securityProfileLabel = securityProfileDoc.getStringValue("/securityprofile/label");
				}	
				
				var labelsNode = securityProfileDoc.nodes("/securityprofile/label");
				for (var j = 0 ; j < labelsNode.length ;j++) {
					labelsNode[j].detach();
				}	
				securityProfileDoc.setStringValue("/securityprofile/label", securityProfileLabel);				
				securityProfileDoc.setStringValue("/securityprofile/siteid", siteId);
				securityProfileDoc.setBooleanValue("/securityprofile/predefined", true);
				securityProfileDoc.save();
			}	
		}			
	}
	catch (e) {
		print(e.toString());
	}	
	finally {
		if (securityDB != null) {
			securityDB.close();
		}	
	}		
}


function getStartValue(db,view,siteid,projectid,idIndex){
	
	var databaseview = null;
	var allentries=null;
	try{
		if (projectid != ""){
			databaseview = db.openView(view,"projectid = '" + projectid + "' and siteid='"+ siteid +"'");
		}else{
			databaseview = db.openView(view,"siteid='"+ siteid +"'");
		}
		allentries = databaseview.getAllEntries();
		entry = allentries.getFirstEntry();
		if (entry != null){
			lastId = @Explode(entry.getValue(idIndex),"_",1);
			startvalue = lastId[1];	
		} 
		else {
			startvalue=0;
		}
		return startvalue;
	}catch (e) {print(e.toString());
	}finally{
		if (allentries != null){
			allentries.close();
		}
		if(databaseview != null){
			databaseview.close();
		}
	}
}

function generateNextId(application,category,prefix,startvalue){
	var idgen = session.getIDGenerator(application, category, "0", 8, prefix , "", 1, startvalue); 
	idgen.resetGenerator(false);
	idgen.generateNextID();
}

function initializeIdTable(){
	import pe_util;
	var sitemanagerDB = null;
	var projectDB = null;
	var supportDB = null;
	var view =  null;
	try {
		sitemanagerDB = session.openDatabase("tg_site_manager");
		projectDB = session.openDatabase("tg_pe_project");
		supportDB = session.openDatabase("tg_pe_support");
		
		view = sitemanagerDB.openView("allsites");
		var siteids = getDistinctValues(view.getColumnsValues("id"));

		for (var j=0;j<siteids.length;j++) {
		
			// get all project ids
			view = projectDB.openView("allprojectsdescbyid","siteid='"+ siteids[j] +"'");
			var projectids = view.getColumnsValues("id");
				
			for (var i=0;i<projectids.length;i++) {
				//support requests		
				startvalue = getStartValue(supportDB,"allrequestsdescbyid",siteids[j],projectids[i],0);
				generateNextId("pe_support","SupportRequest_" + siteids[j] + "_" + projectids[i],"SupportRequest_",parseInt(startvalue));
			}
		}	
	}catch(e){
		print(e);
	}finally{
		if (view != null)
			view.close();
		if (projectDB!=null)
			projectDB.close();
		if (supportDB!=null)
			supportDB.close();
		if (sitemanagerDB != null){
			sitemanagerDB.close();
		}
	}
}

function initializeSiteIdTable(siteId){
	import pe_util;
	var projectDB = null;
	var supportDB = null;
	var view =  null;
	try {
		projectDB = session.openDatabase("tg_pe_project");
		supportDB = session.openDatabase("tg_pe_support");

		// get all project ids
		view = projectDB.openView("allprojectsdescbyid","siteid='"+ siteId +"'");
		var projectids = view.getColumnsValues("id");
				
		for (var i=0;i<projectids.length;i++) {
			//support requests		
			startvalue = getStartValue(supportDB,"allrequestsdescbyid",siteId,projectids[i],0);
			generateNextId("pe_support","SupportRequest_" + siteId + "_" + projectids[i],"SupportRequest_",parseInt(startvalue));
		}
	}catch(e){
		print(e);
	}finally{
		if (view != null)
			view.close();
		if (projectDB!=null)
			projectDB.close();
		if (supportDB!=null)
			supportDB.close();
	}
}

function reset(allCategories,appName,genName) {
	var conn= session.getSQLConnection();
    try {
         var stmt=conn.createStatement();
         try {
              var query;
              if(allCategories) {
      	    	  query= "DELETE FROM FB__SEQID WHERE appname='" + appName +"'";
              } else {
        	      query="DELETE FROM FB__SEQID WHERE appname='" + appName + "' AND genname='" + genName + "'";
              }
              stmt.execute(query);
           }catch(e){
			   print(e.toString());
			}finally {
				try{
              		stmt.close();
				}catch(e){print(e.toString());}
           }
    } catch(e) {
    		  print(e.toString());
    } finally {
              try {
                  conn.close();
              } catch( e ) {print(e);}
    }
}	

function getDefaultHoursPerDay(language) {
	return com.triloggroup.pe.util.InitializationUtil.getDefaultHoursPerDay(language);
}

function getDefaultHoursPerWeek(language) {
	return com.triloggroup.pe.util.InitializationUtil.getDefaultHoursPerWeek(language);
}
	
function getDefaultDaysPerMonth() {
	return com.triloggroup.pe.util.InitializationUtil.getDefaultDaysPerMonth();
}	

function getDefaultTrackingWarningThreshold() {
	return com.triloggroup.pe.util.InitializationUtil.getDefaultTrackingWarningThreshold();
}	

function getDefaultTrackingCriticalThreshold() {
	return com.triloggroup.pe.util.InitializationUtil.getDefaultTrackingCriticalThreshold();
}
	
// To initialize the project document
function initializeProjectDocument(document) {
	import tg_site_manager_settings;
	var defaultLanguage = getDefaultLanguage();
	
	//document.setDateValue("/project/startdate", new Date());
	document.setStringValue("/project/status" , "Pending");
	setDefaultHoursForLocale(document, defaultLanguage);
	document.setIntValue("/project/dayspermonth" , getDefaultDaysPerMonth());
	
	document.setIntValue("/project/maxAttSize", 2);
  	var root = document.getRootElement();
	
	var trackingNode = new DOMElement("tracking");
	
	var thresholdsNode = new DOMElement("thresholds");
	thresholdsNode.setIntValue("warning", getDefaultTrackingWarningThreshold());
	thresholdsNode.setIntValue("critical", getDefaultTrackingCriticalThreshold());
	trackingNode.addContent(thresholdsNode);
	
	root.addContent(trackingNode);
 
 	var activityNode = new DOMElement("activity");
	activityNode.setStringValue("templatepath", "c:\\pe\\activitylogtemplate.xls");
	root.addContent(activityNode);
}	

function initializeDocumentDocument(document) {
	document.setStringValue("/document/status", "New");
}	

function initializeSupportDocument(document) {
	document.setStringValue("/supportrequest/status", "New");
}	

function initializeChangeRequestDocument(document) {
	document.setStringValue("/changerequest/status", "New");
}

function populateDefaultForWeeklyTimeSheet(timesheetNode){
	var siteId = timesheetNode.getStringValue("siteid");
	var projectId = timesheetNode.getStringValue("projectid");
	try{
		workflowDb = session.openDatabase("tg_pe_workflow");
		var workflowDoc = getDefaultWorkflowDocument(workflowDb,"pe_weekly_timesheet",siteId,projectId);
		if(workflowDoc!=null){
			var workflowNode = workflowDoc.nodes("//workflow")[0];
			if(workflowNode!=null){
				//attach workflow to the DOM Element
				var metadataNode = timesheetNode.nodes("metadata")[0];
				if(metadataNode == null){
					metadataNode = new DOMElement("metadata");
					timesheetNode.addContent(metadataNode);
				}
				workflowNode.detach();
				
				// replace supervisor by user dn
				replaceSupervisorInWorkflowNode(timesheetNode, workflowNode);
				
				metadataNode.addContent(workflowNode);
			}
		}
	}catch(e){
		print(e.toString());
	}finally{
		if(workflowDb!=null){
			workflowDb.close();
		}
	}
	
}

function replaceSupervisorInWorkflowNode(timesheetNode, workflowNode) {
	var approversNodes = workflowNode.nodes("step/approver[dn='TG_PE_SUPERVISOR']");
	if (approversNodes != null && approversNodes.length > 0) {
		// get supervisor from Connection
		var supervisorDn = "";
		var supervisorCn = "";
				
		// if connections -> get supervisor
		if (com.triloggroup.pe.util.PEUtil.isProjExecConnections()) {
			var userDn = timesheetNode.getStringValue("requester/dn");
			try {
				if (context != null) {
					supervisorDn = com.triloggroup.sitemanager.util.UserUtil.getLCSupervisorForUser(context, userDn);
					supervisorCn = com.triloggroup.pe.user.UserCache.getUserCn(session, supervisorDn);
				}
			}
			catch(e) {
				print("Error while retrieving supervisor for user: " + userDn);
			}	
		}
				
		// if not found , replace by PM
		if (supervisorDn == null || supervisorDn == "") {
			// take project manager instead
			import pe_administration_util;
			var siteId = timesheetNode.getStringValue("siteid");
			var projectId = timesheetNode.getStringValue("projectid");
		
			var projectManagers = getProjectManagerDns(siteId,projectId);
			for (var i = 0 ; i < projectManagers.length; i++) {
				
				if (com.triloggroup.pe.user.UserCache.isUserRegistered(session, projectManagers[i])) {
					supervisorDn = projectManagers[i];
					supervisorCn = com.triloggroup.pe.user.UserCache.getUserCn(session, supervisorDn);
				}	
			}	
		}	
				
			
		for (var i = 0 ; i < approversNodes.length; i++) {
			approversNodes[i].setStringValue("dn", supervisorDn);
			approversNodes[i].setStringValue("cn", supervisorCn);
		}	
	}	
		
}	
function updateDefaultWorkflow(siteId,projectId, projectManagers){
	import pe_util;
	import pe_administration_util;
	import pe_workflow;
	var allSchemas = new Array("pe_issue_type","pe_weekly_timesheet","pe_changerequest");
	var allFilePaths = new Array("/projexec/data/pe_defaultworkflow_issue.xml","/projexec/data/pe_defaultworkflow_timesheet.xml","/projexec/data/pe_defaultworkflow_change.xml");
	if (projectManagers == null || projectManagers.length == 0) {
		projectManagers = getProjectManagers(siteId,projectId);
	}
	projectManagers = getRegisteredUsers(projectManagers);
	
	var isTemplate = isTemplate(siteId, projectId);
	
	var db = null;
	try{
		db = session.openDatabase("tg_pe_workflow");
		
		var definedSchemas = session.getLookupValues("tg_pe_workflow","alldefaultworkflowsbysiteidprojectidandschema",siteId+"|"+projectId,"schema");
		for(var i=0;i<allSchemas.length;i++){
			if(!inArray(allSchemas[i],definedSchemas)){
				try{
					//create default security document for this schema
					var doc = db.createNewDocument("pe_defaultworkflow");
					var dom = doc.getDOM();
					dom.loadResource(allFilePaths[i]);
					doc.setStringValue("/defaultworkflow/siteid",siteId);
					doc.setStringValue("/defaultworkflow/projectid",projectId);
					if (isTemplate) {
						doc.setBooleanValue("/defaultworkflow/istemplate", true);
					}
					//set project managers as default approvers and add them to notification list
					var steps = doc.nodes("/defaultworkflow/workflow/step");
					var notificationRoot = doc.nodes("/defaultworkflow/workflow/notificationlist/field[name='user']")[0];
					var notifiedUsers = doc.getStringValues("/defaultworkflow/workflow/notificationlist/field[name='user']/entry/value");
					var approveAllManagSchemas = new Array("pe_issue_type","pe_weekly_timesheet");//schemas where we should approve all managers
					var schema = allSchemas[i];
					var usersInNotList = new Array();
					for (var j=0;j<steps.length;j++){
						for (var k=0;k<projectManagers.length;k++){
							var hasApproverNode = (steps[j].getIntValue("count(approver)") > 0);
							//if the schema is pe_documenttype or pe_issue_type or pe_weekly_timesheet or (pe_changerequest for the case of estimators only)
							// then all project managers are added to the list
							if(inArray(schema,approveAllManagSchemas) || (!inArray(schema,approveAllManagSchemas) && !hasApproverNode) ||( schema=="pe_changerequest" && j==0)){
								var approver = new DOMElement("approver");
								var split =  @Explode(projectManagers[k], "|", 1);
								approver.setStringValue("cn",split[0]);
								approver.setStringValue("dn",split[1]);
								steps[j].addContent(approver);
								if ((schema == "pe_issue_type" || schema == "pe_changerequest") && @IsNotMember(split[1],usersInNotList)){
									if (@IsNotMember(split[1],notifiedUsers)){
										var entry = new DOMElement("entry");
										entry.setStringValue("type", "user");
										entry.setStringValue("value",split[1]);
										entry.setStringValue("label",split[0]);
										entry.setBooleanValue("inherited",false);
										entry.setBooleanValue("mandatory",true);
										notificationRoot.addContent(entry);
									}else{
										var entry = notificationRoot.nodes("entry[value=\""+split[1]+"\"]")[0];
										entry.setBooleanValue("mandatory",true);
									}
									usersInNotList.push(split[1]);
								}
							}
						}
					}
					doc.save();
					doc.close();
				}catch(e){
					print(e.toString());
				}
			}
		}
	}catch(e){
		print(e.toString());
	}finally{
		if(db != null){
			db.close();
		}
	}
}

function populateDefaultWorkflow(document){
	try{
		//check if workflow is already added
		var workflowNode = document.nodes("//metadata/workflow");
		if(workflowNode.length==0){
			//add workflow metadata
			var siteId = document.getStringValue("//siteid");
			var projectId = document.getStringValue("//projectid");
			if(siteId != ""){
				//get default workflow document
				var workflowDb = null;
				var schema = document.getSchema();
				if(schema=="pe_issue_type" || schema=="pe_changerequest" || schema=="pe_weekly_timesheet"){
					//copy default workflow from workflow database
					try{
						workflowDb = session.openDatabase("tg_pe_workflow");
						var workflowDoc = getDefaultWorkflowDocument(workflowDb,schema,siteId,projectId);
						if(workflowDoc!=null){
							attachWorkflow(workflowDoc,document);
						}
					}catch(e){
						e.printStackTrace();
					}finally{
						if(workflowDb!=null){
							workflowDb.close();
						}
					}
				}else{
					//pe_document pe_support_request and pe_discussion
					//copy default workflow from doc type, issue type or discussion category
					if(schema=="pe_support_request"){
						var issueType = document.getStringValue("/supportrequest/type");
						if(issueType!=""){
							var supportDB = null;
							try{
								supportDB = session.openDatabase("tg_pe_support");
								var doc = supportDB.getDocumentByKey("allissuetypesbysiteidprojectidandid",new Array(siteId,projectId,issueType));
								if(doc!=null){
									attachWorkflow(doc,document);
								}
							}catch(e){
								e.printStackTrace();
							}finally{
								if(supportDB!=null){
									supportDB.close();
								}
							}
						}
					}				
				}
			}
		}
	}catch(e){
		print("Error while populating default workflow for " + document.getSchema() + " " + document.getId());
		print(e.toString());
	}
}

function attachWorkflow(worklfowDoc,document){
	var workflowNode = worklfowDoc.nodes("//workflow")[0];
	if(workflowNode!=null){
		//attach workflow to the document
		var metadataNode = document.nodes("//metadata")[0];
		if(metadataNode == null){
			metadataNode = new DOMElement("metadata");
			var root = document.getRootElement();
			root.addContent(metadataNode);
		}
		workflowNode.detach();
		metadataNode.addContent(workflowNode);
		
		// if document is change requester, replace requester in workflow step by the document requester
		if (document.getSchema() == "pe_changerequest") {
			var requesterCn = document.getStringValue("/changerequest/requester/cn");
			var requesterDn = document.getStringValue("/changerequest/requester/dn");
			// get approvers nodes where requester is set to replace
			var approvers = workflowNode.nodes("step/approver[dn='TG_PE_REQUESTER']");
			for (var i = 0 ; i < approvers.length; i++) {
				approvers[i].setStringValue("dn", requesterDn);
				approvers[i].setStringValue("cn", requesterCn);
			}	
			var notifiedUsers = workflowNode.nodes("notificationlist/field/entry[value='TG_PE_REQUESTER']");
			var existingUsers = workflowNode.nodes("notificationlist/field/entry[value=\""+requesterDn+"\"]");
			for (var i = 0 ; i < notifiedUsers.length; i++) {
				//added by Lara Ferzli to detach the requester node in case it already exists
				//if the requester doesnt exist
				if(existingUsers.length==0)
				{
					notifiedUsers[i].setStringValue("value", requesterDn);
					notifiedUsers[i].setStringValue("label", requesterCn);
				}
				else
					notifiedUsers[i].detach();
			}
		}	
		else if (document.getSchema() == "pe_weekly_timesheet") {
			var timesheetNode = document.getRootElement();
			replaceSupervisorInWorkflowNode(timesheetNode, workflowNode);
		}
	}
}

function getDefaultWorkflowDocument(workflowDB,schema,siteID,projectID){
	return workflowDB.getDocumentByKey("alldefaultworkflowsbysiteidprojectidandschema",new Array(siteID,projectID,schema));
}

// upgrade=true -> add version
function saveAllDocuments(databaseName,schema,saveOnlyRootDocuments, upgrade){
	var database = null;
	try{
		database = session.openDatabase(databaseName);
		var allDocuments = database.getAllDocuments(schema);
		var document = allDocuments.getFirstDocument();
		while(document!=null){
			if (upgrade) {
				var metadata = document.nodes("//metadata")[0];
				if (metadata != null){
					var wfNode = metadata.nodes("workflow")[0];
					if (wfNode != null){
						wfNode.detach();
					}
				}
			}
			if(!saveOnlyRootDocuments || !document.hasParent()){
				try{
					try{
						if (upgrade) {
							setVersion(document);
						}
					}catch(e){
						print("Error while saving version in old data: " + e.toString());
					}
					document.save();
				}catch(e){
					print("Error while saving all documents " + e.toString());
				}
			}
			document = allDocuments.getNextDocument();
		}
	}catch(e){
		print("Error while saving all documents " + e.toString());
	}finally{
		if(allDocuments!=null){
			allDocuments.close();
		}
		if(database!=null){
			database.close();
		}
	}
}

function copyDefaultSecurity(){
	import pe_initialization;
	//1)save all site documents, to populate default security
	saveAllDocuments("tg_site_manager","tg_portalsite",false, false);
	//2)save issue types
	saveAllDocuments("tg_pe_support","pe_issue_type",false, false);
	//3)save documents, support requests, change requests
	saveAllDocuments("tg_pe_support","pe_support_request",false, false);
	saveAllDocuments("tg_pe_change","pe_changerequest",false, false);
	//4)propagate schedule security
	//get all root wbs
	var rootWBSDocIDs = session.getLookupValues("tg_pe_schedule","allwbsbywbssortedidandwbsid","0001","documentid");
	var scheduleDB = null;
	try{
		scheduleDB = session.openDatabase("tg_pe_schedule");
		for(var i=0;i<rootWBSDocIDs.length;i++){
			//for every root wbs, populate security and propagate it to children
			var wbsDoc = scheduleDB.getDocument(rootWBSDocIDs[i]);
			if(wbsDoc!=null){
				try{
					populateScheduleSecurity(wbsDoc);
					propagateSecurity(wbsDoc);
					try{
						setVersion(wbsDoc);
					}catch(e){
						print("Error while saving version in old data: " + e.toString());
					}					
					wbsDoc.save();
				}catch(e){
					print("Error while copying default security for schedule " + e.toString());
				}
			}
		}	
	}catch(e){
		print("Error while copying default security " + e.toString());
	}finally{
		if(scheduleDB!=null){
			scheduleDB.close();
		}
	}
}

function setVersion(document){
	var metadata = document.nodes("//metadata")[0];
	if (metadata == null){
		var root = document.getRootElement();
		metadata = new DOMElement("metadata");
		root.addContent(metadata);
	}
	var tracking = new DOMElement("tracking");
	tracking.setStringValue("version","3.0");
	metadata.addContent(tracking);
}

function setDefaultHoursForLocale(document, siteLanguage){
		document.setIntValue("/project/hoursperday" , getDefaultHoursPerDay(siteLanguage));
		document.setIntValue("/project/hoursperweek" , getDefaultHoursPerWeek(siteLanguage));
}
