//functions to action on context selection
function AddAQWATreeItem(type, init){
    AddAQWATreeItem2(type, init, "");
}

function AddAQWATreeItem2(type, init, selectedFile){
    wb.DoWaitCursor(1);
    var parentid=tv.selectedItem.Tag.ID;
    var initialcount = tv.selectedItem.Tag.ChildrenCount;
    var i= gettype_as_int(type);
    var outputFile ="";
    
    if (type== "KAQWASnapshot" && (init == "KToFile" || init == "KToTempFile" ))
    {
        IsAeroOn=gfx.CheckForWin7Aero()
	    if (IsAeroOn==true)
	    {
	        wbWarningMsgBox("The display settings are Windows Aero and image capture might not work. Please change them to another theme.","AnsysWB");
	        //break;
	    }
    }
    
    if (type == "KAQWAWind" && init == "KWindTimeImport" && selectedFile == "")
    {
        var filePath = "";
        var filter = "*.WVT";
        var directory = "";
        selectedFile = wbGetFileSelection(filePath, directory, filter, false);
    }
    
    if (type == "KAQWAIrregularWave" && init == "KWaveTimeImport" && selectedFile == "")
    {
        var filePath = "";
        var filter = "*.WHT";
        var directory = "";
        selectedFile = wbGetFileSelection(filePath, directory, filter, false);
    }
    if (type == "KAQWAStructureForce" && init == "KStrFrcFile" && selectedFile == "")
    {
        var filePath = "";
        var filter = "*.XFT";
        var directory = "";
        selectedFile = wbGetFileSelection(filePath, directory, filter, false);
    }
    
    if(type=="KAQWASnapshot"){
       
        updatetreepick(-1,parentid,"refreshparentlight",parentid);//prevents the screen capture getting any of the menu dropdown captured
        if(init=="KFromFile"){
            var filePath = "";
            var filter = stringTable.String("ID_FilterImagesFiles");
            var directory = "";
            selectedFile = wbGetFileSelection(filePath, directory, filter, false);
            
        }else if(init=="KToFile"){
            var ch_png = localString("ID_FilterPNGFiles");
	        var ch_jpg = localString("ID_FilterJPEGFiles");
	        var ch_tif = localString("ID_FilterTIFFFiles");
	        var ch_bmp = localString("ID_FilterBMPFiles");
	        var ch_eps = localString("ID_FilterEPSFiles");
	        var filter = ch_png + ch_jpg + ch_tif + ch_bmp + ch_eps;

            var filePath = wb.GetLastFileName(str_imageCapture, "AQWAApplet");
	        if(filePath.length == 0)
	        {
		        var startPg = wb.AppletList.Applet("StartPage").App;
		        if( startPg )
			        filePath = startPg.WBDB.Location + "file";
	        }

	        var fName = wbGetFileSelection(filePath, "", filter, true);

	        if(fName == "")
		        return;
		    outputFile = fName;
		    
		    var thisclass = JAQWAClassID[tv.selectedItem.Tag.Class];
	        if(thisclass == "KAQWAResultsHydrodynamicGraphs"){
		        doImageCaptureForCharts(outputFile);
		        wb.DoWaitCursor(2);
		        return;
		    }
		    
		    if(i>-1){
                var picked = aqwaprojmgr.AddTreeItem(parentid,i, getinit_as_int(init));
                var obj = aqwaprojmgr.GetObject(picked);
	            if( !parentid )doImageCaptureForGraphics(obj,outputFile);
    	        
	            if(thisclass == "KAQWAResultsHydrostatics"){
	                doImageCaptureForGraphics(obj, outputFile);
    	         
	            }else doImageCaptureForGraphics(obj,outputFile);
    	        
	            aqwaprojmgr.RemoveTreeItem(picked);
            }
            wb.DoWaitCursor(2);
		    return;

        }
    }
    if(i>-1)
    {
        var picked = aqwaprojmgr.AddTreeItem(parentid,i, getinit_as_int(init));
        initialcount++;
        updatetreepick(initialcount,parentid,"parent",picked);
    }
    if(selectedFile.length>0)
    {
        switch(type)
        {
        case "KAQWASnapshot":
            tv.Nodes.Item("a"+picked).Tag.SnapshotCopyFile(selectedFile);
            break;
        case "KAQWAWind":
            tv.Nodes.Item("a"+picked).Tag.ReadWVTFile = selectedFile;
            break;
        case "KAQWAIrregularWave":
            tv.Nodes.Item("a"+picked).Tag.THFile = selectedFile;
            break;    
        case "KAQWAStructureForce":
            tv.Nodes.Item("a"+picked).Tag.StructureForceFile = selectedFile;
            break;    
        }       
        lvUpdateProps();
    }
    aqwaprojmgr.putChangeAffects(picked);
    tv_click();
    wb.DoWaitCursor(2);
}

function doShowOutputWindow(){
 if((prm.Hidden) || (!prm.Visible)){
        showPrmPane(true);
    }else{
        showPrmPane(false);
    }
}

function ToolbarAddAQWATreeItem(type, init){
    wb.DoWaitCursor(1);
    var objroot =getProjectRoot();
    var parentid=objroot.Tag.ID;
    var initialcount = objroot.Tag.ChildrenCount;
    var i= gettype_as_int(type);
    var outputFile ="";
    if(type=="KAQWASnapshot"){
        if(init=="KFromFile"){
            var filePath = "";
            var filter = stringTable.String("ID_FilterImagesFiles");
            var directory = "";
            selectedFile = wbGetFileSelection(filePath, directory, filter, false);
            
        }else if(init=="KToFile"){
            var ch_png = localString("ID_FilterPNGFiles");
	        var ch_jpg = localString("ID_FilterJPEGFiles");
	        var ch_tif = localString("ID_FilterTIFFFiles");
	        var ch_bmp = localString("ID_FilterBMPFiles");
	        var ch_eps = localString("ID_FilterEPSFiles");
	        var filter = ch_png + ch_jpg + ch_tif + ch_bmp + ch_eps;

            var filePath = wb.GetLastFileName(str_imageCapture, "AQWAApplet");
	        if(filePath.length == 0)
	        {
		        var startPg = wb.AppletList.Applet("StartPage").App;
		        if( startPg )
			        filePath = startPg.WBDB.Location + "file";
	        }
	        var fName = wbGetFileSelection(filePath, "", filter, true);

	        if(fName == "")
		        return;
		    outputFile = fName;
		    
		    var thisclass = JAQWAClassID[tv.selectedItem.Tag.Class]
	        if(thisclass == "KAQWAResultsHydrodynamicGraphs"){
		        doImageCaptureForCharts(outputFile);
		        wb.DoWaitCursor(2);
		        return;
		    }
		    
		    if(i>-1){
                var picked = aqwaprojmgr.AddTreeItem(parentid,i, getinit_as_int(init));
                var obj = aqwaprojmgr.GetObject(picked);
	            if( !parentid )doImageCaptureForGraphics(obj,outputFile);
    	        
	            if(thisclass == "KAQWAResultsHydrostatics"){
	                doImageCaptureForGraphics(obj, outputFile);
    	         
	            }else doImageCaptureForGraphics(obj,outputFile);
    	        
	            aqwaprojmgr.RemoveTreeItem(picked);
            }
            wb.DoWaitCursor(2);
		    return;

        }
    }
    if(i>-1){
        var picked = aqwaprojmgr.AddTreeItem(parentid,i, getinit_as_int(init));
        initialcount++;
        updatetreepick(initialcount,parentid,"parent",picked);
        if(selectedFile.length>0){
             tv.Nodes.Item("a"+picked).Tag.SnapshotCopyFile(selectedFile);
        }
    }
    wb.DoWaitCursor(2);

}

function AddAqwaCSVFileForTestBench(selectedFile) {
    wb.DoWaitCursor(1);
    tv.selectedItem.Tag.ImportCSVFileName = selectedFile;
}

///////////////////////////////////////////////////////////////////////////////////

function doImageCaptureForGraphics(Obj,fName)
{

	if(fName == "")
		return;

	// wait for dialog to go away and refresh graphics screen
	var obj = CreateActiveXObject(GenWBProgId("WBControls.WBTestHelper"));
	obj.Wait(500);
	
	var png = /.png$/i;   // $=end of string,  i=case insensitive
	var jpg = /.jpg$/i;
	var tif = /.tif$/i;
	var bmp = /.bmp$/i;
	var eps = /.eps$/i;
	var imode = 0;

	if (fName.search(png) > -1) imode = 0;
	if (fName.search(jpg) > -1) imode = 1;
	if (fName.search(tif) > -1) imode = 2;
	if (fName.search(bmp) > -1) imode = 3;
	if (fName.search(eps) > -1) imode = 4;

	Obj.CaptureToFile(fName, imode);
	wb.PutLastFileName(str_imageCapture,fName,"AQWAApplet");
}

function doImageCaptureForCharts(fName)
{
    if(fName == "")
		return;

	// wait for dialog to go away and refresh graphics screen
	var obj = CreateActiveXObject(GenWBProgId("WBControls.WBTestHelper"));
	obj.Wait(500);
	
    GraphControl_update(tv.selectedItem.Tag.ID);

	var png = /.png$/i;   // $=end of string,  i=case insensitive
	var jpg = /.jpg$/i;
	var bmp = /.bmp$/i;
	var imode = 0;

	if (fName.search(png) > -1) imode = 0;
	if (fName.search(jpg) > -1) imode = 1;
	if (fName.search(bmp) > -1) imode = 3;

	var width = 800;
	var height = 600;
	switch( imode )
	{
		case 0:  //png
			aqwaResultsMgr.GraphControl.WritePngFile( fName, width, height, true );
			break;
			
		case 1:  //jpg
			aqwaResultsMgr.GraphControl.WriteJpgFile( fName, width, height, true );
			break;
			
		case 3:  //bmp
			aqwaResultsMgr.GraphControl.WriteBmpFile( fName, width, height, true );
			break;
			
		default :
			break;
	}	
	wb.PutLastFileName( str_imageCapture, fName, "AQWAApplet" );
}

///////////////////////////////////////////////////////////////////////////////////

function DeleteAQWATreeItem(ConfirmDelete)
{
    var picked=tv.selectedItem.Tag.ID;
    var parent = tv.selectedItem.Parent;
    var DoDelete = true;
    var FullUpdate = false;
    if (ConfirmDelete) {
        var HasCousins = tv.selecteditem.Tag.IsPropagated;
        if (HasCousins) {
            DoDelete = wbYesNo(localString("ID_QuestionDeleteLinkedItems"), localString("ID_DesignSpace"));
            FullUpdate = DoDelete;
        }
        else {
            DoDelete = wbYesNo(localString("ID_MessageBoxDelete"), localString("ID_DesignSpace"));
        }
    }
    if (DoDelete)
    {
        aqwaprojmgr.DisconnectTable();
        aqwaprojmgr.RemoveTreeItem(picked);
        aqwaprojmgr.Project.Title = aqwaprojmgr.Project.Title;
        RecursiveRemoveNodes(tv.selectedItem);
        if (FullUpdate) {
            updatetreepick(0, 0, "full", 0);        // We need to do a full update here, as propagated items will not have the same parent
        }
        else {
            if (parent)
            {
                updatetreepick(1, projrootID, "partial", parent);
            }
            else{
                updatetreepick(1, projrootID, "partial", projrootID);
            }
        }
	    var tmpstr = "";
	 }
 }
 
 function AddModel()
 {
    wb.DoWaitCursor(1);
    var objroot =getProjectRoot();
//    var initialcount = objroot.Tag.ChildrenCount;
    var picked = aqwaprojmgr.CreateModelGroup();
    if (picked>-1){
  //      initialcount++;
        updatetreepick(objroot.Tag.ChildrenCount,projrootID,"parent",picked);
     }
     wb.DoWaitCursor(2);
 }
function AddAnalysis(AnalysisType)
{
    wb.DoWaitCursor(1);
    var parentid=tv.selectedItem.Tag.ID;
    var initialcount = tv.selectedItem.Tag.ChildrenCount;
    var i= getAnalysis_as_int(AnalysisType);
    if(i>-1)
    {
        var picked = aqwaprojmgr.CreateAnalysisGroup(parentid, i,"","","","");
        initialcount++;
        updatetreepick(initialcount,parentid,"parent",picked);
    }
    wb.DoWaitCursor(2);    
}
function ToolbarAddAnalysis(AnalysisType)
{
    wb.DoWaitCursor(1);
    var objroot =getProjectRoot();
    var parentid=objroot.Tag.ID;
    var obj =objroot.Tag;
    var initialcount = obj.ChildrenCount;
    var i= getAnalysis_as_int(AnalysisType);
    if(i>-1)
    {
        var picked = aqwaprojmgr.CreateAnalysisGroup(parentid, i,"","","","");
        initialcount++;
        updatetreepick(initialcount,parentid,"parent",picked);
    } 
    wb.DoWaitCursor(2);
}
function Solve()
{
    aqwaapp.Applet.App.PM.Analyse(tv.selectedItem.Tag.ID, false);
    aqwaResultsMgr = aqwaprojmgr.ResultsMgr;
    
    var paramset = aqwaapp.Applet.App.ParameterSet;
    aqwaprojmgr.SendUpdateOutputParameters(paramset);
    aqwaprojmgr.ParamHandler.RefreshParameters();    
  
    lvUpdateProps();
}
function SolveHydrostatics()
{
    aqwaapp.Applet.App.PM.Analyse(tv.selectedItem.Tag.ID, true);
    lvUpdateProps();
}

function EvaluateAllResults()
{
    aqwaprojmgr.ResultsMgr.UpdateResults();
    lvUpdateProps();

    if ((aqwaprojmgr.FindTreeItemClass(tv.selectedItem.Tag.ID) == gettype_as_int("KAQWAResultsPressuresMotions")) ||
    (aqwaprojmgr.FindTreeItemClass(tv.selectedItem.Tag.ID) == gettype_as_int("KAQWAResultsTimeHistoryMotions")))
    {
        fully_updateHull(1);
    }
    if (aqwaprojmgr.FindTreeItemClass(tv.selectedItem.Tag.ID) == gettype_as_int("KAQWAResultsTimeHistoryMotions"))
    {
        aqwaprojmgr.CheckItemState(tv.selectedItem.Tag.ID);
        tv_click();
    }
    if (aqwaprojmgr.FindTreeItemClass(tv.selectedItem.Tag.ID) == gettype_as_int("KAQWAResultsHydrodynamicGraphs"))
    {
        GraphControl_update(tv.selectedItem.Tag.ID);
    }
    
    aqwaprojmgr.WB2PublishState(tv.selectedItem.Tag.ID, false);

}

function ClearResults() 
{
    DoClear = wbYesNo( localString("ID_QuestionClearResults"), localString("ID_DesignSpace") );
    if (DoClear)
    {
        aqwaprojmgr.ClearResults(tv.selectedItem.Tag.ID)
        aqwaprojmgr.WB2PublishState(tv.selectedItem.Tag.ID, false);
        gfxMgr.UpdateGFXObjects(true);
        gfxMgr.gfxDraw();
        lvUpdateProps();
    }
}

function ClearMesh() {
    DoClear = wbYesNo(localString("ID_QuestionClearMesh"), localString("ID_DesignSpace"));
    if (DoClear) {
        aqwaprojmgr.ClearMesh(tv.selectedItem.Tag.ID)
        aqwaprojmgr.WB2PublishState(tv.selectedItem.Tag.ID, false);
        gfxMgr.UpdateGFXObjects(true);
        gfxMgr.gfxDraw();
        lvUpdateProps();
    }
}

function GenerateMesh(){
    var picked=tv.selectedItem.Tag.ID;
    aqwaprojmgr.MeshGenerate(picked);
    updatetreepick(-1,picked,"refreshparentlight",picked);
}


function InsertGeom(geotype, init){
    var parentid=tv.selectedItem.Tag.ID;
    var picked;
    var sPath;

    if (geotype==""){
        //Geometry from file
        sPath=wbGetFileSelection("*.agdb",GetLastDir(),"DesignModeler (*.agdb)|*.agdb", false);
        
        if (sPath=="")return true;
        
        var pArray=sPath.split("\\");
	    var nPath="";
	    for (var i=0; i<pArray.length-1; i++) {
		    nPath=nPath+pArray[i]+"\\";
	    }
	    SetLastDir(nPath);
	    
        wb.DoWaitCursor(1);
        TreeRemoveChilds(parentid);
        picked = aqwaprojmgr.AttachGeometry(parentid,sPath,"");
        updatetreepick(-1,parentid,"refreshparent",picked);
        
        SetInitialView();
        picked = parentid;
        
    }else{
        var i= gettype_as_int(geotype);
        //Point Mass - Point Buoyancy
        wb.DoWaitCursor(1);
        TreeRemoveChilds(parentid);
        picked = aqwaprojmgr.AddTreeItem(parentid,i, getinit_as_int(init));
        if (picked>-1){
            updatetreepick(-1,parentid,"refreshparent",picked);
        }
    }
    wb.DoWaitCursor(2);
}

function DoChangeActorVis(state,showorhide){
    var i= getstate_as_int(state);
    var SelectedID=tv.selectedItem.Tag.ID;
    aqwaprojmgr.SetTreeItemState(SelectedID,i,showorhide);
    if (i != 1)//KVisibility
    {
        aqwaprojmgr.putChangeAffects(SelectedID);
    }
    aqwaprojmgr.WB2PublishState(SelectedID, true);
    updatetreepick(-1,SelectedID,"refreshparentlight",SelectedID);
}

function CopyItem() {
    var SelectedID = tv.selectedItem.Tag.ID;
    aqwaprojmgr.CopyItem(SelectedID, true);     // true means do clear any existing clipboard data
}

function PasteItem() {
    var SelectedID = tv.selectedItem.Tag.ID;
    var initialcount = tv.selectedItem.Tag.ChildrenCount;
    aqwaprojmgr.PasteItem(SelectedID, gettype_as_int("KAQWAInitalisation"), 0);
    initialcount++;
    updatetreepick(initialcount, SelectedID, "refreshparent", SelectedID);
}

function DuplicateItem() {
    var SelectedID = tv.selectedItem.Tag.ID;
    var Parent = tv.selectedItem.Parent;
    var initialcount = Parent.Tag.ChildrenCount;
    var ParentID = Parent.Tag.ID;
    aqwaprojmgr.DuplicateItem(SelectedID);
    initialcount++;
    updatetreepick(initialcount, ParentID, "refreshparent", ParentID);
}

function PropagateItem() {
    var SelectedID = tv.selectedItem.Tag.ID;
    aqwaprojmgr.PropagateItem(SelectedID);
    updatetreepick(0, 0, "full", 0);
}

function BreakLink() {
    var SelectedID = tv.selectedItem.Tag.ID;
    aqwaprojmgr.BreakLink(SelectedID);
    updatetreepick(-1, SelectedID, "refreshparentlight", SelectedID);
}

function getTreeObjectMatchingID(ID){
   
    var obj=null;
    for(i=1;i<=tv.Nodes.Count;i++){
         obj = tv.Nodes.Item(i);
         if(obj.Tag.ID==ID){
            return obj;
         }
    }
   
	return obj;

}
function getProjectRoot(){
    if (!tv.selectedItem) {
        return tv.Nodes.Item(1);
    }
    var Project=tv.selectedItem;
    while (Project.Tag.ID!=aqwaprojmgr.Project.ID) {
	    Project=Project.Parent;
    }
	return Project;
}

//Menu functions
function doExit() {
    try{
	    wb.FileExit();
	    }
	    catch(e){

	        wb.Close();
	    }
	return 0;
}

function AQWA_OnTerminate(){

   if(tv){
        if(tv.selectedItem){
            if(tv.selectedItem.Tag){
                var Obj = tv.selectedItem.Tag;
                if(JAQWAClassID[Obj.Class] == "KAQWAComment" )
                    saveCommentEditorText();
            }
        }
    }
        
    if (IsAlive){
            IsAlive  = false;
            doExit();
    }
    return 0;
}
function doCloseAqwa() {
    if (aqwaprojmgr){
        var i = aqwaprojmgr.IsProjectSaved();
        if(i == 1 ){
            //already in saved state just close
            aqwaprojmgr.ProjectClose(false);
            aqwaapp.Applet.App.CanExit= true;
        }else{
            var wb2ver =aqwaprojmgr.WB2connected;
            if (wb2ver==true){
                aqwaprojmgr.ProjectClose(true);
                aqwaapp.Applet.App.CanExit= true;
            }else{
                var i = wbYesNoCancel("Save project before continuing?","Warning!");
	            if(i ==-1){
	                return false;
	            }
	            aqwaapp.Applet.App.CanExit= true;
                if(i ==1){
                    aqwaprojmgr.ProjectClose(true);
                }else{
                    aqwaprojmgr.ProjectClose(false);
                }
            }
        }    
    }
    return true;
}

function doSaveProject() {
    if(tv){
        if(tv.selectedItem){
            if(tv.selectedItem.Tag){
                Obj = tv.selectedItem.Tag;
                if(JAQWAClassID[Obj.Class] == "KAQWAComment" )
                    saveCommentEditorText();
            }
        }
    }
    var wb2ver =aqwaprojmgr.WB2connected;
    if (wb2ver==true){
        wb.DoWaitCursor(1);	
        EventMgr = aqwaapp.Applet.EventManager;
        EventMgr.Fire_OnSaveProject(0);
        wb.DoWaitCursor(2);	

    }else{


        var FileName=aqwaprojmgr.FileName;
	    if (FileName) {
	        wb.DoWaitCursor(1);
            if(aqwaprojmgr.OverWriteAsk){
                if (aqwaapp.Applet.App.FileExists(FileName)){
                    var i = wbYesNo("Overwrite existing project?","Warning!");
                    if(i != 1){
                        aqwaapp.Applet.App.CanExit= false;
                        return true;
                    }
                }	
            }
            
            aqwaprojmgr.ProjectSave();
		    aqwaapp.Applet.App.CanExit= true;
		    wb.PutLastFileName("AQWALastFile",FileName,"AQWA");
		    wb.DoWaitCursor(2);	
	    } else {	    
		    doSaveAsProject();
	    }
	 }
}

function doSaveAsProject() {
    var wb2ver =aqwaprojmgr.WB2connected;
    if (wb2ver==true){
        wb.DoWaitCursor(1);	
        EventMgr = aqwaapp.Applet.EventManager;
        EventMgr.Fire_OnSaveProject(1);
        wb.DoWaitCursor(2);	

    }else{
	    var FileName=aqwaprojmgr.FileName;
	    if (FileName) {
		    var pArray=FileName.split("\\");
		    var nPath="";
		    for (var i=0; i<pArray.length-1; i++) {
			    nPath=nPath+pArray[i]+"\\";
		    }
		    sPath=wbGetFileSelection(FileName,nPath,"AQWA (*.aqdb)|*.aqdb", true );
	    } else {
		    sPath=wbGetFileSelection("*.aqdb",GetLastDir(),"AQWA (*.aqdb)|*.aqdb", true );			
	    }
	    if (sPath=="") return;
    	    
	    FileName=sPath;
	    wb.PutLastFileName("AQWALastFile",sPath,"AQWA");
	    AddLastProject(sPath);
	    //UpdateRecentFileMenu();
	    var pArray=sPath.split("\\");
	    var nPath="";
	    for (var i=0; i<pArray.length-1; i++) {
		    nPath=nPath+pArray[i]+"\\";
	    }
	    SetLastDir(nPath);
	    wb.DoWaitCursor(1);	
        aqwaprojmgr.ProjectSaveAs(FileName,true);
	    aqwaapp.Applet.App.CanExit= true;
	    wb.DoWaitCursor(2);	
	 }
}

function ProjectDo(ftype){
    if (ftype ==1)doNewProject();
    if (ftype ==2)doOpenProject("");
}

function doAskProject(ftype){
     if (aqwaprojmgr){
        var i = aqwaprojmgr.IsProjectSaved();
        if(i == 1 ){
            ProjectDo(ftype);
            aqwaapp.Applet.App.CanExit= true;
            return true;
        }
        var i = wbYesNo("Current project is not saved!  Continue?","Warning!");
        if(i == 1){
            ProjectDo(ftype);
            aqwaapp.Applet.App.CanExit= true;
            return true;
        }
    }
}

function AQWADisplayControlPanel(){

    DisplayControlPanel("CATNAME_AQWA", "wb_aqwa_options");
    

}
  
function doEditDuplicate(){
    var i = tv.selectedItem.Key;
    var t = tv.Nodes.Item(i).Tag;
    EventMgr = aqwaapp.Applet.EventManager;
    EventMgr.Fire_OnDuplicate(t.Hash);
    
}
function doOpenProject(sPath) {
    if (sPath==""){
        sPath=wbGetFileSelection("*.aqdb",GetLastDir(),"AQWA (*.aqdb)|*.aqdb", false );	
    }	
	if (sPath=="") return;

	var pArray=sPath.split("\\");
	var nPath="";
	for (var i=0; i<pArray.length-1; i++) {
		nPath=nPath+pArray[i]+"\\";
	}
	wb.DoWaitCursor(1);
	tvnodecount = 0;
    RecursiveRemoveNodes(getProjectRoot());
    SetLastDir(nPath);
    gfxMgr.Clear();
    
    SetInitialView();
	aqwaprojmgr.ProjectOpen(sPath);
	aqwaResultsMgr = aqwaprojmgr.ResultsMgr;
    AddLastProject(sPath);
	//UpdateRecentFileMenu();
	updatetreepick(1,projrootID,"full",projrootID);
	completeVisibility();
	InValidLVCount = 0;
	wb.DoWaitCursor(2);
}

function doNewProject() {
    wb.DoWaitCursor(1);
    aqwaprojmgr.ProjectClose(false);
	var picked=aqwaprojmgr.ProjectNew();
	aqwaprojmgr.Project.AttachCamera();
	aqwaResultsMgr = null;
	gfxMgr.set_pickedarnull();
    gfxMgr.set_pickedar(projrootID);
    gfxMgr.Clear();
    aqwaapp.Applet.App.ClearOldMessages(0);
    SetInitialView();
    updatetreepick(1,projrootID,"full",projrootID);
    completeVisibility();
    InValidLVCount = 0;
    wb.DoWaitCursor(2);
    aqwaapp.Applet.App.CanExit= true;
}

function UpdateGFXCompleteVisibility(){
    updateGFXlist(0);
    completeVisibility();
}
function completeVisibility(){
    gfxMgr.gfxDraw();
    wb.DoWaitCursor(2);
}
function doTriadVisibility()
{
	doStopAnimation();
	triadOn = gfx.TriadVisible;
	gfx.TriadVisible = !triadOn;
    completeVisibility();
}

function doLegendVisibility()
{
	doStopAnimation();
	var legendOn = gfx.DrawLegend;
	gfx.DrawLegend = !legendOn;
    UpdateGFXCompleteVisibility();
}

function doRulerVisibility()
{
	doStopAnimation();
	var rulerOn = gfx.RulerVisible;
	gfx.RulerVisible = !rulerOn;
	wb.PutLastFileName(str_RulerVisible, gfx.RulerVisible, "AQWAApplet");
    completeVisibility();
}

function doOpenRecentFile(num) {
	var fso = CreateActiveXObject("Scripting.FileSystemObject");
	var Arr=GetLastProject();
	num=num*1.0;
	if (num<1 || num>Arr.length) return false; 
	if (fso.FileExists(Arr[num-1])) {
		doOpenProject(Arr[num-1]);
		return true;
	}else{
	    WBScript.out("Failed to find project!",true);
	    return false;
	}
	
}	

function StoreWindowSettings() {
	aqwaapp.Frame.SaveLayoutInMemory();
}

function RestoreWindowSettings() {
    aqwaapp.Frame.InitWindowPosFromRegistry();
}

function doEditDeSelectAll(){
    gfx.SelectionManager.Clear();
    completeVisibility();
}
function doEditSelectAll(){
    gfx.SelectionManager.SelectAll();
//    statusbar.sbUpdateSelectionPaneString();
//   	if ( tvPane.FirstSelectedItem.Class == id_VirtualCell || tvPane.FirstActiveObject.Class == id_VirtualCellGroup )
//        aqwaapp.GUIState.UpdateVirtualTopologyToolbar();
	completeVisibility();
}

function SetUnit(kind,unit) {
    if (Lockcheck()){
	    switch (kind) {
		    case "length":
			    switch (unit) {
				    case "km":
					    UnitLength=KAQWAKM;
					    break;
				    case "m":
					    UnitLength=KAQWAMetre;
					    break;
				    case "cm":
					    UnitLength=KAQWACM;	
					    break;
				    case "mm":
					    UnitLength=KAQWAMM;
					    break;
				    case "foot":
					    UnitLength=KAQWAFoot;
					    break;
				    case "inch":
					    UnitLength=KAQWAInch;
					    break;
			    }
			    SetLength(UnitLength);
			    break;
		    case "mass":
			    switch (unit) {
				    case "g":
					    UnitWeight=KAQWAGram;
					    break;
				    case "kg":
					    UnitWeight=KAQWAKGram;
					    break;
				    case "tonnes":
					    UnitWeight=KAQWATonne;
					    break;
				    case "pound":
					    UnitWeight=KAQWAPound;
					    break;
				    case "tonUK":
					    UnitWeight=KAQWATonUK;
					    break;
			    }
			    SetWeight(UnitWeight);
			    break;
		    case "force":
			    switch (unit) {
				    case "N":
					    UnitForce=KAQWANewton;
					    break;
				    case "kN":
					    UnitForce=KAQWAKNewton;
					    break;
				    case "lbf":
					    UnitForce=KAQWAlbf;
					    break;
				    case "kips":
					    UnitForce=KAQWAKips;
					    break;					    
			    }
			    SetForce(UnitForce);
			    break;
		    case "angle":
			    switch (unit) {
				    case "rad":
					    UnitAngle=KAQWARAD;
					    break;
				    case "deg":
					    UnitAngle=KAQWADeg;
					    break;
			    }
			    SetAngle(UnitAngle);
			    break;
		    case "frequency":
			    switch (unit) {
				    case "Hz":
					    UnitFreq=KAQWAHz;
					    break;
				    case "w":
					    UnitFreq=KAQWAw;
					    break;
			    }
			    SetFreq(UnitFreq);
			    break;
        }
	    aqwaprojmgr.PutUnits(UnitAngle, UnitForce, UnitLength, UnitWeight, UnitTime, UnitFreq);
	    tv_click();
	}
}

function IsUnit(kind,unit) {
	switch (kind) {
		case "length":
			switch (unit) {
				case "km":
					return GetLength()==KAQWAKM;
				case "m":
					return GetLength()==KAQWAMetre;
				case "cm":
					return GetLength()==KAQWACM;	
				case "mm":
					return GetLength()==KAQWAMM;
				case "foot":
					return GetLength()==KAQWAFoot;
				case "inch":
					return GetLength()==KAQWAInch;
			}
			break;
		case "mass":
			switch (unit) {
				case "g":
					return GetWeight()==KAQWAGram;
				case "kg":
					return GetWeight()==KAQWAKGram;
				case "tonnes":
					return GetWeight()==KAQWATonne;
				case "pound":
					return GetWeight()==KAQWAPound;
				case "tonUK":
					return GetWeight()==KAQWATonUK;
			}
			break;
		case "force":
			switch (unit) {
				case "N":
					return GetForce()==KAQWANewton;
				case "kN":
					return GetForce()==KAQWAKNewton;
				case "lbf":
					return GetForce()==KAQWAlbf;
				case "kips":
					return GetForce()==KAQWAKips;
			}
			break;
		case "angle":
			switch (unit) {
				case "rad":
					return GetAngle()==KAQWARAD;
				case "deg":
					return GetAngle()==KAQWADeg;
			}
			break;
		case "frequency":
			switch (unit) {
				case "Hz":
					return GetFreq()==KAQWAHz;
				case "w":
					return GetFreq()==KAQWAw;
			}
			break;	}
	return false;
}
function AQWAref() {
	 wb.ShowHelpDocument("aqwa_ref");
}

function About() {
    //OpenModalWindow("AQWAAboutDlg.htm", null, 500, 300);
    var xfer = CreateActiveXObject(str_DlgArgsProgId);
    var dlg = CreateActiveXObject(str_WBHTMLDialogProgId);
    xfer("workbench") = wb;

    dlg.DoDialog(wb.hWnd, installDirNoLocale + str_PathSeparator + "html" + str_PathSeparator + "AQWAAboutDlg.htm", xfer, false, 500, 323, 5, localString("ID_About"));
}

function Help() 
{
    wb.ShowHelpDocument("wb_aqwa");
}



///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

function doPlayAnimation()
{
	var anim = gfx.AnimationControl;
	if(!anim)
	{
		return;
	}

	if(anim.Animating)
	{
		//currently animating, pause
		doAnimation(8081);
	}
	else
	{
		//currently paused or need to play first time
		doAnimation(8080);
	}
}

function doPauseAnimation()
{
    doAnimation(8081);
}

function doStopAnimation()
{
    doAnimation(8082);
}


function doSaveResultAVIFile(file)
{
    doAnimationFilename(file);

}

function doSaveResultAVI()
{
    doAnimation(8083);

}


function CanAnimateDistributedPoints()
{
	var anim = gfx.AnimationControl;
	if(!anim)	return false;
	if(anim.Animating)
		return false;
	return true;
}

function setPlayLengthCombo(isel)
{
	var sec = animplaylength;
	switch(isel)
	{
		case 0:		sec = .5;	break;
		case 1:		sec = 1;	break;
		case 2:		sec = 2;	break;
		case 3:		sec = 3;	break;
		case 4:		sec = 4;	break;
		case 5:		sec = 10;	break;
	}
	var anim = gfx.AnimationControl;
	if(!anim)	return 0;
	anim.PlayLength = sec;
	animplaylength = sec;
}

function getPlayLengthCombo()
{
	var anim = gfx.AnimationControl;
	if(!anim)	return 0;
	var isel = -1;
	var sec = animplaylength;
	switch(sec)
	{
		case .5:	isel = 0;	break;
		case 1:		isel = 1;	break;
		case 2:		isel = 2;	break;
		case 3:		isel = 3;	break;
		case 4:		isel = 4;	break;
		case 10:	isel = 5;	break;
		default:	isel = 2;	break;
	}
	return isel;
}

function getPlayLengthComboText()
{
	var anim = gfx.AnimationControl;
	if(!anim)	return 0;
	var sec = anim.PlayLength;
	return "" + sec + " " + localString("ID_Sec");
}

function fillPlayLengthList(fillObj)
{
	fillObj.AddPair("0.5 " + localString("ID_Sec"),  0);
	fillObj.AddPair("1 "   + localString("ID_Sec"),  1);
	fillObj.AddPair("2 "   + localString("ID_Sec") + " (" + localString("ID_Auto") + ")",  2);
	fillObj.AddPair("3 "   + localString("ID_Sec"),  3);
	fillObj.AddPair("4 "   + localString("ID_Sec"),  4);
	fillObj.AddPair("10 "  + localString("ID_Sec"),  5);
}

function CanEnablePlayLengthCombo()
{
	var anim = gfx.AnimationControl;
	if(!anim)	return false;
	return true;
}
function doAnimationFilename(fName)
{
	var anim = gfx.AnimationControl;
	if(!anim)	return;
	anim.Stop();
	if(fName != "")
	{
		// wait for dialog to go away and refresh graphics screen
		var obj = CreateActiveXObject(GenWBProgId("WBControls.WBTestHelper"));
		obj.Wait(500);

		var saveAnimStyle = anim.AnimationStyle;
		var fps = anim.FramesPerSec;
		var factor = 25;
		fps = fps/factor;
		anim.FramesPerSec = fps;
		anim.Delay = anim.delay*factor;
		anim.AnimationStyle = 1;

		wb.DoWaitCursor(1);
		try
		{
    	    anim.SaveToFile(fName);
    	}
    	catch(Error)
    	{
    	    wbErrorMsgBox(wbGetLocalString( stringTable, "ID_Error_AviFileAlreadyInUse"), wbGetLocalString( stringTable, "ID_DesignSpaceError" ));
    	}
		wb.DoWaitCursor(2);

		anim.AnimationStyle = saveAnimStyle;
        completeVisibility();
	}
}
function AQWA_GetLic(){
    if (aqwaapp){
        if (aqwaapp.Applet){
            aqwaapp.Applet.App.GetLic();
        }
        lvUpdateProps() ;
    }
    return false;
}



function aqGenerateMesh(pos)
{
    var ID = aqwaprojmgr.ProjID;
    aqwaprojmgr.MeshForSystem(pos);
    updatetreepick(-1,ID,"refreshparentlight",ID);
}

function aqWB2SetModelName(newName){
    aqwaprojmgr.WB2SetModelName(newName);
    if (tv.selectedItem){
        var Root=tv.selectedItem;
        while (Root.Tag.Class!=gettype_as_int("KAQWAProject")) {
	        Root=Root.Parent;
        }
        TreeRefreshStateLoop(Root.Tag);
    }
}

function aqWB2ReleaseAcle(){
    if (aqwaapp){
        if (aqwaapp.Applet){
            aqwaapp.Applet.App.ReleaseACLE();
        }
        lvUpdateProps() ;
    }
}

function aqWB2NewProject(){
    wb.DoWaitCursor(1);
    aqwaprojmgr.ProjectClose(false);
	var picked=aqwaprojmgr.WB2ProjectNew();
	aqwaprojmgr.Project.AttachCamera();
	aqwaResultsMgr = null;
	gfxMgr.set_pickedarnull();
    gfxMgr.set_pickedar(projrootID);
    gfxMgr.Clear();
    aqwaapp.Applet.App.ClearOldMessages(0);
    SetInitialView();
    updatetreepick(1,projrootID,"full",projrootID);
    completeVisibility();
    InValidLVCount = 0;
    wb.DoWaitCursor(2);
    aqwaapp.Applet.App.CanExit= true;
}

function aqWB2SaveToLoc(FileLoc){
    wb.DoWaitCursor(1);
    aqwaprojmgr.WB2SaveToLoc(FileLoc);
    aqwaapp.Applet.App.CanExit= true;
    wb.DoWaitCursor(2);
}

function aqWB2PutModelHash(ModelHash){
    aqwaprojmgr.WB2PutModelHash(ModelHash); 
}

function aqExportLoadedGeometry(){
    var FileFound = aqwaprojmgr.WB2ExportGeometry();
    EventMgr = aqwaapp.Applet.EventManager;
    EventMgr.Fire_OnExportGeometry(FileFound);
}
function aqWB2UpdateHashForImport(OldHash, NewHash, found){
    aqwaprojmgr.ResetAllAnalysisHash();
    found= aqwaprojmgr.WB2UpdateHash(OldHash, NewHash);   
   
    return found;
}
function aqWB2UpdateHash(OldHash, NewHash, found){
    found= aqwaprojmgr.WB2UpdateHash(OldHash, NewHash);   
    return found;
}
function aqWB2PutTHUpstreamHash(SetupHash, SolutionHash){
    found= aqwaprojmgr.WB2PutTHUpstreamHash(SetupHash, SolutionHash);   
    return found;
}
function aqWB2SetAnalysisDir(SetupHash,Dir){
    aqwaprojmgr.WB2SetAnalysisDir(SetupHash, Dir);   
}


function aqWB2SetupID(Hash,val,WBCellID){
    var strWBCellID = "";
    strWBCellID =strWBCellID + WBCellID;
    var strHash = "";
    strHash = strHash + Hash;
    if (strWBCellID.length>8||strWBCellID==""){
        return;
    }
    aqwaprojmgr.WB2SetAnalysisID(strHash,strWBCellID);   
    if (tv.selectedItem){
        var Root=tv.selectedItem;
        while (Root.Tag.Class!=gettype_as_int("KAQWAProject")) {
	        Root=Root.Parent;
        }
        TreeRefreshStateLoop(Root.Tag);
    }
}

function aqWB2AddOrphans(){
    var picked = aqwaprojmgr.WB2HDOrphans();
    return picked;
}
function aqWB2AddTHOrphans(){
    var picked = aqwaprojmgr.WB2THOrphans();
    return picked;
}
function aqWB2RemoveOrphans(){
    var i = 0;
    var picked = aqwaprojmgr.WB2RemoveOrphans();
    while(picked>0 && i<30)
        {
            aqwaprojmgr.RemoveTreeItem(picked);
            aqwaprojmgr.Project.Title = aqwaprojmgr.Project.Title;
            RecursiveRemoveNodes(tv.Nodes.Item("a"+picked));
            i++;
            picked = aqwaprojmgr.WB2RemoveOrphans();
        }
    if (i>0) {
        updatetreepick(1,projrootID,"full",projrootID);
    }
    
}

function aqWB2PutModelRoot(DirLoc){
    aqwaapp.Applet.App.ModelDir = DirLoc;
    //aqwaprojmgr.WB2PublishState(projrootID,true);
}
function aqWB2Set(BetaOptionsOn){
    aqwaprojmgr.WB2Connected = true;
    aqwaprojmgr.BetaOptionsOn= BetaOptionsOn;
    IsBeta = BetaOptionsOn;
    AQWA_GetLic();
    aqwaapp.Applet.App.CanExit= true;
    
}

function aqAlterGeomLoc(GeomFile, IsForLiveAssembly){
    aqwaprojmgr.AlterGeomLoc(GeomFile,IsForLiveAssembly);
}
function aqWB2PutModelID(WBCellID){
    var strWBCellID = "";
    strWBCellID = strWBCellID+WBCellID;
    if(strWBCellID==""){
        aqwaprojmgr.WB2ID = "??";   
    }else{
        aqwaprojmgr.WB2ID = strWBCellID;   

    }
    //updatetreepick(1,projrootID,"full",projrootID);
    if (tv.selectedItem){
        var Root=tv.selectedItem;
        while (Root.Tag.Class!=gettype_as_int("KAQWAProject")) {
	        Root=Root.Parent;
        }
        TreeRefreshStateLoop(Root.Tag);
    }
}
function aqWB2SetName(sysName){
    Productstr = sysName;
    return true;
}
function aqWB2CompareLoadedFile(FileLoc){
    return aqwaprojmgr.WB2CompareLoadedFile(FileLoc);
}
function aqWB2import(FileLoc,WBCellID){
    wb.DoWaitCursor(1);
	tvnodecount = 0;
    RecursiveRemoveNodes(getProjectRoot());
    gfxMgr.Clear();
    
    SetInitialView();
	projrootID = aqwaprojmgr.WB2import(FileLoc);
	aqwaResultsMgr = aqwaprojmgr.ResultsMgr;
	var strWBCellID = "";
    strWBCellID = strWBCellID+WBCellID;
	if(WBCellID==""){
        aqwaprojmgr.WB2ID = "??";   
    }else{
        aqwaprojmgr.WB2ID = strWBCellID;   

    }
    updatetreepick(1,projrootID,"full",projrootID);
	completeVisibility();
	InValidLVCount = 0;
	
    aqwaprojmgr.WB2PublishState(projrootID, true);
    wb.DoWaitCursor(2);
}

function aqAttachFirstGeometry(GeomFile, plugin, Hash, type){
    aqAttachGeometry(1, GeomFile, plugin, Hash, type);
}

function aqSetGeometryImportOptions(ImportSolid,ImportSurface,ImportLine){
    aqwaprojmgr.SetGeometryImportOptions(ImportSolid,ImportSurface,ImportLine);
}

function aqWB2RemoveAnalysis(Setuphash){
    wb.DoWaitCursor(1);
    
    var picked = aqwaprojmgr.FindAnalysisWithHash(Setuphash);
    if(picked>0){
        updatetreepick(1,projrootID,"partial",projrootID);
        aqwaprojmgr.RemoveTreeItem(picked);
        aqwaprojmgr.Project.Title = aqwaprojmgr.Project.Title;
        RecursiveRemoveNodes(tv.Nodes.Item("a"+picked));
    }

    completeVisibility();
    
    wb.DoWaitCursor(2);
}

function aqWB2AddAnalysis(analysistype, Setuphash, SolutionHash, ResultHash, AnalysisID, CopyHash){
    wb.DoWaitCursor(1);
    var i = getAnalysis_as_int(analysistype);    // analysistype will come through from the Add-in code as "Hydrodynamic Diffraction" (i = 0) or "Hydrodynamic Response" (i = 1)
    var parentid = aqwaprojmgr.Project.ID;
    
    if(CopyHash=="??"){
        
        if(i>-1) {
            
            var picked = aqwaprojmgr.CreateAnalysisGroup(parentid, i, Setuphash, SolutionHash, ResultHash, AnalysisID);
            updatetreepick(parentid, parentid, "full", parentid);
            var localcount = analysisCountHD;
            if (i == 1) localcount = analysisCountTR;
            var obj = tv.Nodes("a"+picked).Tag;
            if (obj!=null){
                if (localcount > 1) {

                    obj.Name = analysistype + " " + localcount;
                }else{
                    obj.Name = analysistype;
                }
                localcount++;
            }
            if (i == 1) {
                analysisCountTR = localcount;
            } else {
                analysisCountHD = localcount;
            }
            

        }
    }else{
        if(i>-1)
        {
            //To do: implement copy instead of new so it also duplicates user input of copied system
            //Clone
            var picked = aqwaprojmgr.FindAnalysisWithHash(CopyHash);
            if(picked>0){
                aqwaprojmgr.CloneTreeItem(picked,true);
            }
           
            //var picked = aqwaprojmgr.CopyAnalysisGroup(parentid, i, Setuphash, SolutionHash, ResultHash, AnalysisID, CopyHash);
            //this next call will use an existing orphan and assing these hashes instead
            picked = aqwaprojmgr.CreateAnalysisGroup(parentid, i, Setuphash, SolutionHash, ResultHash, AnalysisID);
            updatetreepick(parentid, parentid, "full", parentid);
            var localcount = analysisCountHD;
            if (i == 1) localcount = analysisCountTR;
            
            var obj = tv.Nodes("a"+picked).Tag;
            if (obj!=null){
                if (localcount > 1) {

                    obj.Name = analysistype + " " + localcount;
                }else{
                    obj.Name = analysistype;
                }
                localcount++;

                if (i == 1) {
                    analysisCountTR = localcount;
                } else {
                    analysisCountHD = localcount;
                }
                
            }

        }
    
    }
    completeVisibility();
    wb.DoWaitCursor(2);
}
function aqAttachGeometry(Pos, GeomFile, plugin, Hash, type){

    wb.DoWaitCursor(1);
    var geom;
    var picked =-1;
    
    if (tv.Nodes.count>0){
        var GeomRoot=tv.selectedItem;
        //if (GeomRoot==null)
        //    GeomRoot=tv.Nodes[tv.Nodes.count-1];
        while (GeomRoot.Tag.Class!=gettype_as_int("KAQWAProject")) {
	        GeomRoot=GeomRoot.Parent;
        }
        geom = FindTreeItemName(GeomRoot.Tag,"KAQWAGeometry");
        if(geom!= null){
            TreeRemoveChilds(geom.ID);
        }
    }
    //update from Design Point
    if(type == 2){
        picked = aqwaprojmgr.UpdateAQWAGeometry(geom.ID, GeomFile, plugin, true);
        updatetreepick(-1,picked,"refreshparent",picked);
    }
    else if(type == 1){
        picked = aqwaprojmgr.UpdateAQWAGeometry(geom.ID, GeomFile, plugin, false);
        updatetreepick(-1,picked,"refreshparent",picked);
    }else{
        //initial

        picked = aqwaprojmgr.AttachGeometryForSystem(Pos, GeomFile, plugin, Hash);
        if (picked>-1){
            updatetreepick(-1,picked,"refreshparent",picked);
        }
        SetInitialView();
    }
    
    wb.DoWaitCursor(2);
}

function aqWB2getHasLicense() {
    var hasLicense = 1;
    
    if (aqwaapp.Applet.App.ShowLicRetry) {
        hasLicense = 0;
    }
    
    return hasLicense;
}

function aqWB2getBusyState(){
    var busystate = 0;
    if (aqwaapp.Applet.App.IsGuiLocked)busystate = 1;
    return busystate;
}
function aqWB2getCanSolve(){
    var solve = aqwaapp.Applet.App.CanSolve;
    return solve;
}
function aqWB2getHasPMAS(){
    var HasPMAS = aqwaprojmgr.HasPMAS;
    return HasPMAS;
}
function aqWB2ReState(){
    aqwaprojmgr.WB2PublishState(projrootID, true);
}

function aqWB2CloseAQWAWB()
{
    aqwaprojmgr.ProjectClose(false);
    aqwaapp.Applet.App.CanExit= true;
    doExit();
}

function aqWB2Solve(Hash, HydroStaticOnly){
    aqwaprojmgr.AnalyseForSystem(Hash, HydroStaticOnly);
}
function WB2UpdatePreferences(args){
    wb.UpdatePreferences(args,aqwaapp.StringTable);
    wb.PreferenceMgr.Save();
    gfx.PreferenceMgr = wb.PreferenceMgr;
    gfx.WBGfx.LoadPreferences();
}
function WB2UpdatePreferences2(){
    
    gfx.WBGfx.LoadPreferences();
}
function aqWB2UdpateResults(Setuphash){
    wb.DoWaitCursor(1);    
    var picked = aqwaprojmgr.FindAnalysisWithHash(Setuphash);
    if(picked>0){
        var obj = getTreeObjectMatchingID(picked);
        if(obj){
           for (var i=1; i<=obj.Tag.ChildrenCount; i++) {
                if(JAQWAClassID[obj.Tag.Children(i).Class]=="KAQWAResults"){
                    tv.selectedItem=tv.Nodes.Item("a"+obj.Tag.Children(i).ID);
                    EvaluateAllResults();

                }
            }
        }
        
    }

    completeVisibility();
    wb.DoWaitCursor(2);
    
}

function getReportFolderPath()
{
	return currentReportDir + str_ReportFolderName + str_PathSeparator;
}

function getUDFPath()
{
	return userDataFolder;
}

function doMSOutlookAttach()
{
	var tempFolder = getUDFPath();
	//send to outlook as an attachment
	var ol = null;

	try
    {
        ol = new ActiveXObject(str_OutlookApplicationProgId);
    }
	catch(e)
    {
        wbErrorMsgBox(wbGetLocalString( stringTable, "ID_MSPowerOfficeError" ), wbGetLocalString( stringTable, "ID_DesignSpaceError" ));
        return 0;
    }

	if(ol)
	{
		//if in report preview
		if(tb.ActiveTab.Key == localString("ID_ReportPreview"))
		{
			var fso = CreateActiveXObject(str_FileSystemObjectProgId);

			//create outlook instance
			var ns = ol.GetNamespace("MAPI");
			var mail = ol.CreateItem(0);

			//create body and add htm file
			mail.subject = aqwaprojmgr.Project.Name;

			//create temp dir
			var tmpFolderpath = getUDFPath() + "\\TMP";
			var filepath = tmpFolderpath + ReportFileName + ".htm";
			if(!fso.FolderExists(tmpFolderpath))
				fso.CreateFolder(tmpFolderpath);

           
		        eReportPublishType = { SingleFile:1, FiguresSubFolder:2, SingleFolder:3 }; // corresponds to ID_FilterWebFiles    

			try
			{
				publishReport(filepath,eReportPublishType.SingleFile);
			}
			catch(e)
			{
				publishReport(filepath,eReportPublishType.SingleFolder);
			}
			//add mht file as attachment to email
			if(aqwaprojmgr.Project == null)
				mail.Attachments.Add(getReportFolderPath() + "DSReportBlank.htm").DisplayName = ReportFileName + ".htm";
			else
				mail.Attachments.Add(filepath).DisplayName = ReportFileName + ".htm";

			//delete TMP folder
			try
			{
				fso.DeleteFolder(tmpFolderpath,true);
			}
			catch(e)
			{
				fso.DeleteFile(filepath);
			}
		}
		//if in print preview mode
		else if(tb.ActiveTab.Key == localString("ID_PrintPreview"))
		{
			var imode = getImageMode();
			var ext = getImageExt(imode);

			//create outlook instance
			var mail = ol.CreateItem(0);
			mail.subject = localString("ID_PrintPreview");
			mail.body = localString("ID_PrintPreview") + "\n\n";

			//attach Prewiew file
			mail.Attachments.Add(tempFolder + "preview" + ext).DisplayName = "Preview" + ext;
		}

		//display outlook
		mail.Display();
	}

}

function publishReport(path, publishType)
{
    var sourceFolderPath = fso.BuildPath( wb.UserDataFolder, ReportFileDirName );
    var sourceFilePath = fso.BuildPath(sourceFolderPath, ReportFileName + ".htm");
    var sourceSubFolderPath = fso.BuildPath(sourceFolderPath, ReportSubFolderName);

    var sourceFile = fso.GetFile(sourceFilePath);
    var textStream = sourceFile.OpenAsTextStream(1 /*ForReading*/, -2 /*unicode*/);
    var html = textStream.ReadAll();
    textStream.Close();
    

	eReportPublishType = { SingleFile:1, FiguresSubFolder:2, SingleFolder:3 }; // corresponds to ID_FilterWebFiles    


    if((publishType == eReportPublishType.SingleFile) )
    {
        var cdo = CreateActiveXObject("CDO.Message");
        cdo.HTMLBody = html;
        var sourceSubFolder = fso.GetFolder(sourceSubFolderPath);
        for(enumFiles = new Enumerator(sourceSubFolder.Files); !enumFiles.atEnd(); enumFiles.moveNext())
        {
            var sourceSubFile = enumFiles.item();
            cdo.AddRelatedBodyPart(sourceSubFile.Path, ReportSubFolderName + "/" + sourceSubFile.Name, 1 /*cdoRefTypeLocation */);
        }
        var stream = cdo.GetStream();
        stream.SaveToFile(path, 2 /*adSaveCreateOverWrite*/);
        stream.Close();
    }
    else
    {
        if(publishType == eReportPublishType.FiguresSubFolder)
        {
            var destinationFileBaseName = fso.GetBaseName(path);
            var destinationSubFolderName = destinationFileBaseName + localString("ID_ReportSubfolderSuffix");
            var figuresFolderPath = fso.BuildPath(fso.GetParentFolderName(path), destinationSubFolderName);
            var pattern = ReportSubFolderName;
            var replaceText = destinationSubFolderName;
        }
        else
        {
            var figuresFolderPath = fso.GetParentFolderName(path);
            var pattern = ReportSubFolderName + "\/";
            var replaceText = "";
        }

        var re = new RegExp(pattern, "g");
        html = html.replace(re, replaceText);

		textStream = fso.CreateTextFile(path, true /*overwrite*/, true /*unicode*/);

        
        textStream.Write(html);
        textStream.Close();
        fso.CopyFolder(sourceSubFolderPath, figuresFolderPath, true /*overwrite*/);
    }
}

function doMSWord()
{
	var rephtml;

	//make sure at least geometry is attached
	if(aqwaprojmgr.Project.Name ==null)
		rephtml = getReportFolderPath() + "DSReportBlank.htm";
	else
	{
		//rephtml = getUDFPath() + "\\Simulation_Report\\Simulation_Report.htm";
		var reportPath = fso.BuildPath( wb.UserDataFolder, ReportFileDirName );
        rephtml = fso.BuildPath(reportPath, ReportFileName + ".htm");
	}

	var tempFolder = getReportFolderPath();

	//open up in word
	if(tb.ActiveTab.Key == localString("ID_ReportPreview"))
	{
		var wApp = null;

		try
        {
            wApp = new ActiveXObject(str_WordApplicationProgId);
        }
		catch(e)
        {
            wbErrorMsgBox(wbGetLocalString( stringTable, "ID_MSPowerOfficeError" ), wbGetLocalString( stringTable, "ID_DesignSpaceError" ));
            return 0;
        }

		if (wApp)
		{
			try
			{
				var doc = new ActiveXObject(str_WordDocumentProgId);//"Word.Document"
				doc = wApp.Documents.Open(/*tempFolder +*/ rephtml);
				wApp.Visible = true;

				var fields = wApp.ActiveDocument.Fields;
				for(var e = new Enumerator(fields); !e.atEnd(); e.moveNext())
				{
					var linkFormat = e.item().LinkFormat;
					if(linkFormat)
					{
						linkFormat.Update();
						linkFormat.BreakLink();
					}
				}
			}
			catch(e)
			{
			}

			wApp = null;
		}
	}
	else if(tb.ActiveTab.Key == localString("ID_PrintPreview"))
	{
		var imode = getImageMode();
		var ext = getImageExt(imode);

		var wApp = null;

		try
        {
            wApp = new ActiveXObject(str_WordApplicationProgId);
		}
		catch(e)
        {
            wbErrorMsgBox(wbGetLocalString( stringTable, "ID_MSPowerOfficeError" ), wbGetLocalString( stringTable, "ID_DesignSpaceError" ));
            return 0;
        }

		if(wApp.Documents.Count > 0)
			wApp.Documents(1).Shapes.AddPicture(getUDFPath() + "preview" + ext);
		else
		{
			var wDoc = wApp.Documents.Add();
			wDoc.Shapes.AddPicture(getUDFPath() + "preview" + ext);
		}
		
		wApp.Visible = true;
		wApp = null;
	}
	else
	{
		var imode = getImageMode();
		var ext = getImageExt(imode);

		var wApp = null;

		try
        {
            wApp = new ActiveXObject(str_WordApplicationProgId);
		}
		catch(e)
        {
            wbErrorMsgBox(wbGetLocalString( stringTable, "ID_MSPowerOfficeError" ), wbGetLocalString( stringTable, "ID_DesignSpaceError" ));
            return 0;
        }

		if(wApp.Documents.Count > 0)
			wApp.Documents(1).Shapes.AddPicture(installDir + "preview" + ext);
		else
		{
			var wDoc = wApp.Documents.Add();
			wDoc.Shapes.AddPicture(installDir + "preview" + ext);
		}
		
		wApp.Visible = true;
		wApp = null;
	}
}

function doMSPowerPoint()
{
	//TODO: rewrite export to powerpoint code to make more maintainable
	//regarding adding new features with graphs and displaying graph titles

	//all the figures are in the project folder subdirectory. we need to loop through them and append them to a presentation

	//get the project folder subdirectory first
	var fso = GetFileSystemObject();
	var reportPath = fso.BuildPath( wb.UserDataFolder, ReportFileDirName );
    var reportFullPath = fso.BuildPath( reportPath, ReportFileName + ".htm" );
	var reportSubFolderPath = fso.BuildPath( reportPath, ReportSubFolderName );

	//open in powerpoint
	var oPPT, oPres;

	//Create a new presentation in PowerPoint
	try
    {
        oPPT = new ActiveXObject(str_PowerPointApplicationProgId);//"PowerPoint.Application"
    }
	catch(e)
    {
        wbErrorMsgBox(wbGetLocalString( stringTable, "ID_MSPowerOfficeError" ), wbGetLocalString( stringTable, "ID_DesignSpaceError" ));
        return 0;
    }

	oPres = oPPT.Presentations.Add(true);

	if(tb.ActiveTab.Key == localString("ID_ReportPreview"))
	{
		//title page
		oPres.Slides.Add(oPres.Slides.Count + 1, 1);
		var objTitle = oPres.Slides(1);
		objTitle.Shapes(1).TextFrame.TextRange.Text =  localString("ID_DesignSpaceReport");
		objTitle.Shapes(2).TextFrame.TextRange.Text = aqwaprojmgr.Project.Name;

		//add all figures and graphs as slides
		var reportSubFolder = fso.GetFolder(reportSubFolderPath);
		for(enumFiles = new Enumerator(reportSubFolder.Files); !enumFiles.atEnd(); enumFiles.moveNext())
		{
			var sourceSubFile = enumFiles.item();
			//if the file name does not begin with "figure" or the extension is not png skip it (we might
	        //get some other files in there if we export to word and save)    - bug #55612
			var ext = "";
			var ps = sourceSubFile.Name.indexOf(".");
			ext = sourceSubFile.Name.substring(ps+1);
			if (sourceSubFile.Name.indexOf("Figure") == -1 || ext != "png")  continue;
			
			oPres.Slides.Add( oPres.Slides.Count + 1, 11 ); //12 is a blank slide, 11 is a title
            oPres.Slides( oPres.Slides.Count ).Shapes(1).TextFrame.TextRange.Text = sourceSubFile.Name;
			oPres.Slides( oPres.Slides.Count ).Shapes.AddPicture( reportSubFolderPath + "\\" + sourceSubFile.Name, false, true, 110, 135, 512, 386 );
		}
	}

	//set visible
	oPPT.Visible = true;
}
function doPrintProcessing()
{
	//WBScript.Out("Print Preview", true);
	if(tb.ActiveTab.Key == localString("ID_ReportPreview"))
		tb.ActiveTab.ActiveControl.HostedControl.Document.parentWindow.print();

	else if(tb.ActiveTab.Key == localString("ID_PrintPreview"))
	{
		//this will just do a portrait print
		pp.document.Script.MyPrint();
	}
}
function doPublishProcessing()
{
    try
    {
        with(CreateActiveXObject(wb_wbFileDialogProgid))
        {
			
			Filter = localString("ID_FilterWebFiles");

            FilterIndex = 1;
            Mode = 0x000400 /*PIS_FILESAVE*/;
            DefaultDirectory = GetMyDocumentsPath();
            DefaultFile = tv.Nodes.Item(1).Text;
            Popup(wb.hWnd);
            if(SelectedFile != "") publishReport(SelectedFile, FilterIndex);
        }
    }
    catch(e)
    {
        WBScript.Out(e.description, true);
    }
}
function doFontResize()
{
    var style = tb.ActiveTab.ActiveControl.HostedControl.Document.body.style;
    switch(style.zoom)
    {
        case "":        style.zoom = "120%"; break;
        case "120%":    style.zoom = "150%"; break;
        case "150%":    style.zoom = "80%"; break;
        case "80%":     style.zoom = "90%"; break;
        case "90%":     style.zoom = "";
    }
}
var eReportPublishType ; // corresponds to ID_FilterWebFiles

function getImageMode()
{
	var imode = 0;
    var prefObj = wb.PreferenceMgr;
    if(prefObj)
        imode = prefObj.Preference("PID_PNG");

	return imode;
}

function openCommentEditor( commentObject )
{

	aqwaprojmgr.EditorsHandler.OpenCommentEditor( commentObject );
	
}
function saveCommentEditorText()
{
   aqwaprojmgr.EditorsHandler.SaveActiveCommentEditorText();
   
}
function CloseActiveCommentEditor()
{
    aqwaprojmgr.EditorsHandler.CloseActiveCommentEditor();
}

//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
function IsAppDebug(){
    if (aqwaapp){
        if (aqwaapp.Applet){
            return aqwaapp.Applet.App.IsDebug;
        }
    }
    return false;
}
function DoDebug(){  
    debugger
    
    updateGFXlist(0);
    GUIDriver.MenuListener.FilterAllToolbars();
    completeVisibility();

    var x = gfx.Camera.PerspectViewAngle;
    
}
//TB helper functions
function get_ResultMin(){
    var val = 0.0;
    if (gfx!=null){
        
        if (gfx.WBGfx!=null){
            if (gfx.WBGfx.Legend!= null){
                val = gfx.WBGfx.Legend.resultMin;
            }
        }
    }
    return val;
}

function get_ResultMax(){
    var val = 0.0;
    if (gfx!=null){
        
        if (gfx.WBGfx!=null){
            if (gfx.WBGfx.Legend!= null){
                val = gfx.WBGfx.Legend.resultMax;
            }
        }
    }
    return val;
}

function get_Hydrostaticresult(Structure, type, component){
//string struct = structure name
//type
//component <3
//x = 0
//y = 1
//z = 2

var TYPE_Array = new Array(
"ActualDisplacedVolume",
"EquivilentDisplacedVolume",
"PrincipalAxisAngle",
"WaterPlaneArea",
"CoGToCoB",
"CentreOfFloatation",
"CoBtoMetaCentre",
"Principal2ndMofArea",
"MetacentricHt",
"RestoringMoment",
"SpecifiedGM",
"CentreOfBuoyancy",
"CentreOfGravity",
"HeaveStiffness",
"RollStiffness",
"PitchStiffness",
"OutOfBalanceForces",
"OutOfBalanceMoments",
"PanelDisplacedVolume",
"PanelCentreOfBuoyancy",
"NotHSLastElementNo")


    var result = 0.0;
    var type_int = -1;
    var iter;
    for (iter=0;iter<TYPE_Array.length;iter++){
        if (TYPE_Array[iter] == type){
            type_int = iter; 
            break;
        }
    }
    if (type_int>-1){
        var increment = 0; 
        if (type_int<18){
            increment = 1; 
        }if(type_int>17){
            increment = 13; 
        }
        if(type_int>19){
            increment = 21; 
        }
        type_int = type_int+increment;
    
        aqwaResultsMgr = aqwaprojmgr.ResultsMgr;
        var gotResults = aqwaResultsMgr.IniHydrostaticGetResult;
        var AQWAResultsHydrostatics = 30;
        var Structure_int = 0;
        var num_structures = aqwaResultsMgr.StructureCount(AQWAResultsHydrostatics);
        if (num_structures > 0)
        {
            AqwaStructure = aqwaResultsMgr.StructureList(AQWAResultsHydrostatics, 0, 0);
            if (aqwaResultsMgr.StructureName(AQWAResultsHydrostatics, AqwaStructure) == Structure)
            {
                Structure_int = 0;
                Structure_int++;
            }
            if (Structure_int > 0)
            {
                result = aqwaResultsMgr.HydrostaticGetSingleResult2(type_int, component);
            }
        }
    }
    return result;
}

function getNumberOfGraphResults(){
    if(aqwaResultsMgr.GraphControl){
        if(aqwaResultsMgr.GraphControl.Datasets){
            if(aqwaResultsMgr.GraphControl.Datasets.Count>0){
                return aqwaResultsMgr.GraphControl.Datasets.Item(0).Count;
            }
            
        }

    }
}


function getHydrodynamicGraphResultX(frequency_index){
    local_index = frequency_index-1;

    if(aqwaResultsMgr.GraphControl){
        if(aqwaResultsMgr.GraphControl.Datasets){
            if(aqwaResultsMgr.GraphControl.Datasets){
                if(aqwaResultsMgr.GraphControl.Datasets.Count>0){
                    return aqwaResultsMgr.GraphControl.Datasets.Item(0).ItemAt(local_index,0);
                }

            }
        }
    }
    return 0;
}

function getHydrodynamicGraphResultY(frequency_index){
    local_index = frequency_index-1;

    if(aqwaResultsMgr.GraphControl){
        if(aqwaResultsMgr.GraphControl.Datasets){
            if(aqwaResultsMgr.GraphControl.Datasets){
                if(aqwaResultsMgr.GraphControl.Datasets.Count>0){
                    return aqwaResultsMgr.GraphControl.Datasets.Item(0).ItemAt(local_index,1);
                }

            }
        }
    }
    return 0.0;
}
function getTableData(row,column){
    var obj = aqwaprojmgr.TableControl;
    if(obj){
        if(row>1){
            if(column>0){
                return eval(aqwaprojmgr.TableControl.cell(row,column)); 
            }
        }
    }
    return 0.0;

}
function getSolverStop(){
    return aqwaapp.Applet.App.SolverStopEval;

}
function AddAQWAUserTreeItem(registeredId){
    wb.DoWaitCursor(1);
    var parentid=tv.selectedItem.Tag.ID;
    
    var initialcount = tv.selectedItem.Tag.ChildrenCount;
    var picked = aqwaprojmgr.UserObjectAddToId(registeredId,parentid);
    initialcount++;
    updatetreepick(initialcount,parentid,"parent",picked);

    wb.DoWaitCursor(2);
}

function ImportAQWADataFile(type, init)
{
    wb.DoWaitCursor(1);
    
    if (type == "KAQWAWind" && init == "KWindTimeImport")
    {
        var filePath = "";
        var filter = "*.WVT";
        var directory = "";
        selectedFile = wbGetFileSelection(filePath, directory, filter, false);
        if(selectedFile.length>0)
        {
            tv.selectedItem.Tag.ReadWVTFile = selectedFile;
        }
    }
    
    if (type == "KAQWAIrregularWave" && init == "KWaveTimeImport")
    {
        var filePath = "";
        var filter = "*.WHT";
        var directory = "";
        selectedFile = wbGetFileSelection(filePath, directory, filter, false);
        if(selectedFile.length>0)
        {
            tv.selectedItem.Tag.THFile = selectedFile;
        }
    }
    if (type == "KAQWAStructureForce" && init == "KStrFrcFile")
    {
        var filePath = "";
        var filter = "*.XFT";
        var directory = "";
        selectedFile = wbGetFileSelection(filePath, directory, filter, false);
        if(selectedFile.length>0)
        {
            tv.selectedItem.Tag.StructureForceFile = selectedFile;
        }
    }
     
    lvUpdateProps();
    aqwaprojmgr.putChangeAffects(tv.selectedItem.Tag.ID);
    tv_click();
    wb.DoWaitCursor(2);
}