//====================================================================
//                                                                  
//stpancode.js
//
//
//last revision Kurt Dereli    19/11/07
//====================================================================

//this contains all my custom code for st pancras interactive
//plus a lot of standard turntool code with minor amendments
//for the purposes of this project





function switchsize(width, height){
    //this function is used by flash 
    //to set size of the turntool window
    //for the full screen version
    element("TNTCtrl").width=width
    element("TNTCtrl").height=height
} 



//=================================================

//main useful functions

//=================================================



var ismoving=false;
var movingobject="";
var mode="normal";
var level="platform";//'platform' or 'undercroft'
var camtype="free"; //'free' or 'walking' or 'flythrough'

function view_undercroft_map(){
  //displays the undercroft map view
//  if(camtype=="walking"){
//     view_undercroft();    
//  }else{
      element("explorediv").innerHTML="<a href='javascript:view_toggle_explore(false)'><p>Explore</p></a>"

      TNTDoCommand('CameraCtrl.SetCurrent("cam_map")');
      mode="normal";
    //hide stuff we don't need
      TNTDoCommand('Scenegraph.Objects("geom_*").SetEnable(false)')
      TNTDoCommand('Scenegraph.Objects("platformmap_*").SetEnable(false)')
      TNTDoCommand('Scenegraph.Objects("text_*").SetEnable(false)');  
    //unhide stuff we do need
      TNTDoCommand('Scenegraph.Objects("outside_*").SetEnable(true)');
      TNTDoCommand('Scenegraph.Objects("outside_*").SetVisible(true)');

      TNTDoCommand('Scenegraph.Objects("undercroftmap_*").SetEnable(true)');
      TNTDoCommand('Scenegraph.Objects("undercroftmap_*").SetVisible(true)');
    //but make sure destination marker is not there  
      TNTDoCommand('Scenegraph.Objects("undercroftmap_destination*").SetEnable(false)');
      TNTDoCommand('Scenegraph.Objects("undercroftmap_route*").SetEnable(false)');
           
      TNTDoCommand('Scenegraph.Objects("location_*").SetEnable(false)');
      //changeCamera("cam_map") ;
//  }
  level="undercroft";
}              

function view_platform_map(){
  //displays platform level map view
//  if(camtype=="walking"){
//      view_platform();    
//  }else{
    element("explorediv").innerHTML="<a href='javascript:view_toggle_explore(false)'><p>Explore</p></a>"

    TNTDoCommand('CameraCtrl.SetCurrent("cam_map")');
    mode="normal";
    //hide stuff we don't need
      TNTDoCommand('Scenegraph.Objects("geom_*").SetEnable(false)')
      TNTDoCommand('Scenegraph.Objects("undercroftmap_*").SetEnable(false)')
      TNTDoCommand('Scenegraph.Objects("text_*").SetEnable(false)');  
    //unhide stuff we do need
      TNTDoCommand('Scenegraph.Objects("platformmap_*").SetEnable(true)')
      TNTDoCommand('Scenegraph.Objects("platformmap_*").SetVisible(true)')
      TNTDoCommand('Scenegraph.Objects("outside_*").SetEnable(true)');
      TNTDoCommand('Scenegraph.Objects("outside_*").SetVisible(true)');      

      //changeCamera("cam_map") ;
//  }
  level="platform";
}

function view_move(){  
      TNTDoCommand('Scenegraph.Objects("exploretext").SetEnable(true)')
      TNTDoCommand('Scenegraph.Objects("exploretext").SetVisible(true)')
      
      TNTDoCommand('Scenegraph.Objects("text_*").SetEnable(false)');    
      //reset cameras
       TNTDoCommand('Scenegraph.Objects(*).ResetAnimation();')
       TNTDoCommand('Scenegraph.Objects(*).ResetTransformation();')
      //reset physics
       TNTDoCommand('Scenegraph.Physics.Reset();')

      TNTDoCommand('Scenegraph.Objects("flythroughtext").SetEnable(false)')
      TNTDoCommand('Scenegraph.Objects("flythroughtext").SetVisible(false)')
    //changeCamera("cam_move") ; 
      TNTDoCommand('CameraCtrl.SetCurrent("cam_move")')
      camtype="free";
}

function view_toggle_explore(isActive){ 
  if(isActive==false){
    element("explorediv").innerHTML="<a href='javascript:view_toggle_explore(true)'><p>Map</p></a>"
    //this is the code for the  higher poly version
    //first whiteout 
       TNTDoCommand('Scenegraph.Objects("location_*").SetEnable(false)');  
      TNTDoCommand('CameraCtrl.SetCurrent("cam_altfree")'); 
      TNTDoCommand('Scenegraph.Objects("whiteout*").SetEnable(true)')
      TNTDoCommand('Scenegraph.Objects("whiteout*").SetVisible(true)')   

      TNTDoCommand('Scenegraph.Objects("text_*").SetEnable(false)');          
      TNTDoCommand('Scenegraph.Objects("exploretext").SetEnable(true)')
      TNTDoCommand('Scenegraph.Objects("exploretext").SetVisible(true)')
    //reset cameras
       TNTDoCommand('Scenegraph.Objects(*).ResetAnimation();')
       TNTDoCommand('Scenegraph.Objects(*).ResetTransformation();')
      //reset physics
       TNTDoCommand('Scenegraph.Physics.Reset();')

    //changeCamera("cam_move") ; 
      TNTDoCommand('Scenegraph.Objects("undercroftmap_*").SetEnable(false)');
      TNTDoCommand('Scenegraph.Objects("undercroftmap_*").SetVisible(false)');
      
      TNTDoCommand('Scenegraph.Objects("platformmap_*").SetEnable(false)');
      TNTDoCommand('Scenegraph.Objects("platformmap_*").SetVisible(false)');

      TNTDoCommand('Scenegraph.Objects("outside_*").SetEnable(false)');
      TNTDoCommand('Scenegraph.Objects("outside_*").SetVisible(false)');


      TNTDoCommand('Scenegraph.Objects("geom_*").SetEnable(true)');
      TNTDoCommand('Scenegraph.Objects("geom_*").SetVisible(true)');

      TNTDoCommand('Scenegraph.Objects("whiteout*").SetEnable(false)');
      TNTDoCommand('Scenegraph.Objects("whiteout*").SetVisible(false)');   


      camtype="walking"
      if(level=="undercroft"){
        view_undercroft();
        
      }else{
        view_platform();
      }      
    }else{
      element("explorediv").innerHTML="<a href='javascript:view_toggle_explore(false)'><p>Explore</p></a>"
      camtype="free"
      
      if(level=="undercroft"){
        view_undercroft_map();
        
      }else{
        view_platform_map();
      }      

    }
}



var flythroughnumber=1;

function view_panaround(){
  //displays rotating camera
      
    //first whiteout 
    TNTDoCommand('CameraCtrl.SetCurrent("cam_altfree")');  
    TNTDoCommand('Scenegraph.Objects("whiteout*").SetEnable(true)')
    TNTDoCommand('Scenegraph.Objects("whiteout*").SetVisible(true)')   

    mode="normal";
 
      TNTDoCommand('Scenegraph.Objects("text_*").SetEnable(false)');
     TNTDoCommand('Scenegraph.Objects("location_*").SetEnable(false)');
       
      //choose a random camera
      var rand1=  Math.round(Math.random()*6)+1 ;
      switch(flythroughnumber++){
        case 1:
          //unhide stuff
          TNTDoCommand('Scenegraph.Objects("text_arcade").SetEnable(true)');
          TNTDoCommand('Scenegraph.Objects("text_arcade").SetVisible(true)');
          
          TNTDoCommand('Scenegraph.Objects("geom_*").SetEnable(true)');
          TNTDoCommand('Scenegraph.Objects("geom_*").SetVisible(true)');
          //hide stuff  
          TNTDoCommand('Scenegraph.Objects("undercroftmap*").SetEnable(false)');
          TNTDoCommand('Scenegraph.Objects("platformmap*").SetEnable(false)');
           
          TNTDoCommand('CameraCtrl.SetCurrent("cam_fly_arcade")')         
        break;
        case 2:
          //unhide stuff
          TNTDoCommand('Scenegraph.Objects("text_circle").SetEnable(true)');
          TNTDoCommand('Scenegraph.Objects("text_circle").SetVisible(true)');

          TNTDoCommand('Scenegraph.Objects("geom_*").SetEnable(true)');
          TNTDoCommand('Scenegraph.Objects("geom_*").SetVisible(true)');
          //hide stuff  
          TNTDoCommand('Scenegraph.Objects("undercroftmap*").SetEnable(false)');
          TNTDoCommand('Scenegraph.Objects("platformmap*").SetEnable(false)');
        
          TNTDoCommand('CameraCtrl.SetCurrent("cam_fly_circle")')         
        break;
        case 3:
          //unhide stuff
          TNTDoCommand('Scenegraph.Objects("text_firstcapitalconnect").SetEnable(true)');
          TNTDoCommand('Scenegraph.Objects("text_firstcapitalconnect").SetVisible(true)');

          TNTDoCommand('Scenegraph.Objects("geom_*").SetEnable(true)');
          TNTDoCommand('Scenegraph.Objects("geom_*").SetVisible(true)');
          //hide stuff  
          TNTDoCommand('Scenegraph.Objects("undercroftmap*").SetEnable(false)');
          TNTDoCommand('Scenegraph.Objects("platformmap*").SetEnable(false)');
          
          TNTDoCommand('CameraCtrl.SetCurrent("cam_fly_firstcapitalconnect")')         
        break;
        case 4:
          //unhide stuff
           TNTDoCommand('Scenegraph.Objects("text_eurostardepartures").SetEnable(true)');
          TNTDoCommand('Scenegraph.Objects("text_eurostardepartures").SetVisible(true)');
                   
          TNTDoCommand('Scenegraph.Objects("geom_*").SetEnable(true)');
          TNTDoCommand('Scenegraph.Objects("geom_*").SetVisible(true)');
         //hide stuff  
          TNTDoCommand('Scenegraph.Objects("undercroftmap*").SetEnable(false)');
          TNTDoCommand('Scenegraph.Objects("platformmap*").SetEnable(false)');
          
          TNTDoCommand('CameraCtrl.SetCurrent("cam_fly_eurostardepartures")')         
        break;
        case 5:
          //unhide stuff
          TNTDoCommand('Scenegraph.Objects("text_champagnebar").SetEnable(true)');
          TNTDoCommand('Scenegraph.Objects("text_champagnebar").SetVisible(true)');

          TNTDoCommand('Scenegraph.Objects("geom_*").SetEnable(true)');
          TNTDoCommand('Scenegraph.Objects("geom_*").SetVisible(true)');
          //hide stuff  
          TNTDoCommand('Scenegraph.Objects("undercroftmap*").SetEnable(false)');
          TNTDoCommand('Scenegraph.Objects("platformmap*").SetEnable(false)');
          
          TNTDoCommand('CameraCtrl.SetCurrent("cam_fly_champagnebar")');
          flythroughnumber=1;          
        break;
        case 6:
          //hide stuff we don't need
          TNTDoCommand('Scenegraph.Objects("geom_*").SetEnable(false)')
       
          //unhide stuff we do need
      
          if(level=="undercroft"){
            TNTDoCommand('Scenegraph.Objects("undercroftmap_*").SetEnable(true)');
            TNTDoCommand('Scenegraph.Objects("undercroftmap_*").SetVisible(true)');
          }
          if(level=="platform"){
            TNTDoCommand('Scenegraph.Objects("platformmap_*").SetEnable(true)');
            TNTDoCommand('Scenegraph.Objects("platformmap_*").SetVisible(true)');
          }
          TNTDoCommand('Scenegraph.Objects("outside_*").SetEnable(true)');
          TNTDoCommand('Scenegraph.Objects("outside_*").SetVisible(true)');
    
          TNTDoCommand('Scenegraph.Objects("exploretext").SetEnable(false)')
          TNTDoCommand('Scenegraph.Objects("exploretext").SetVisible(false)')
          TNTDoCommand('Scenegraph.Objects("flythroughtext").SetEnable(true)')
          TNTDoCommand('Scenegraph.Objects("flythroughtext").SetVisible(true)')
          TNTDoCommand('CameraCtrl.SetCurrent("cam_map")')
          flythroughnumber=1;         
        break;              
        default:
          //old version
          //this should never fire but its here just in case
          TNTDoCommand('CameraCtrl.SetCurrent("cam_flyaround")')        
        break;
      
      } 
       
                
      //TNTDoCommand('Scenegraph.Objects("location_*").SetEnable(false)')

      camtype="flythrough"
      
      //kill whiteout
      TNTDoCommand('Scenegraph.Objects("whiteout*").SetEnable(false)');
      TNTDoCommand('Scenegraph.Objects("whiteout*").SetVisible(false)');   

}



function view_undercroft(){
    //first whiteout  
      //TNTDoCommand('Scenegraph.Objects("whiteout*").SetEnable(true)')
      //TNTDoCommand('Scenegraph.Objects("whiteout*").SetVisible(true)')   


    //reset cameras
       TNTDoCommand('Scenegraph.Objects(*).ResetAnimation();')
       TNTDoCommand('Scenegraph.Objects(*).ResetTransformation();')
      //reset physics
       TNTDoCommand('Scenegraph.Physics.Reset();')
  
  
  
    mode="normal";
  //unhide stuff
    TNTDoCommand('Scenegraph.Objects("geom_*").SetEnable(true)')
    TNTDoCommand('Scenegraph.Objects("geom_*").SetVisible(true)')
    
  //hide stuff  
    TNTDoCommand('Scenegraph.Objects("undercroftmap_*").SetEnable(false)')
    TNTDoCommand('Scenegraph.Objects("platformmap_*").SetEnable(false)')
    TNTDoCommand('Scenegraph.Objects("outside_*").SetEnable(false)')
    TNTDoCommand('Scenegraph.Objects("text_*").SetEnable(false)');
 //camera
    //changeCamera("cam_roam1") ;
    TNTDoCommand('CameraCtrl.SetCurrent("cam_roam1")');
    //kill whiteout  
      TNTDoCommand('Scenegraph.Objects("whiteout*").SetEnable(false)')
      TNTDoCommand('Scenegraph.Objects("whiteout*").SetVisible(false)')   

}

function view_platform(){
    //first whiteout  
     //TNTDoCommand('Scenegraph.Objects("whiteout*").SetEnable(true)')
      //TNTDoCommand('Scenegraph.Objects("whiteout*").SetVisible(true)')   

    //reset cameras
       TNTDoCommand('Scenegraph.Objects(*).ResetAnimation();')
       TNTDoCommand('Scenegraph.Objects(*).ResetTransformation();')
      //reset physics
       TNTDoCommand('Scenegraph.Physics.Reset();')
    mode="normal";
  //unhide stuff
    TNTDoCommand('Scenegraph.Objects("geom_*").SetEnable(true)');
  //hide stuff  
    TNTDoCommand('Scenegraph.Objects("undercroftmap*").SetEnable(false)');
    TNTDoCommand('Scenegraph.Objects("platformmap*").SetEnable(false)');
      TNTDoCommand('Scenegraph.Objects("text_*").SetEnable(false)');
  //camera
    //changeCamera("cam_roam2") ;
    
    TNTDoCommand('CameraCtrl.SetCurrent("cam_roam2")');
    //kill whiteout  
      TNTDoCommand('Scenegraph.Objects("whiteout*").SetEnable(false)')
      TNTDoCommand('Scenegraph.Objects("whiteout*").SetVisible(false)')   

}

function highlight_location(locationname,level1){
     
    if(level1=="lower"){
        view_undercroft_map();
       level="undercroft";
    }else if(level1=="upper"){
       view_platform_map();
       level="platform";
    }

     TNTDoCommand('CameraCtrl.SetCurrent("cam_move")')
     TNTDoCommand('Scenegraph.Objects("location_*").SetEnable(false)')
     TNTDoCommand('Scenegraph.Objects("location_' + locationname +  '").SetEnable(true)')
     TNTDoCommand('Scenegraph.Objects("location_' + locationname +  '").SetVisible(true)')

}

function zoneenter(zone,physics){
  var a1=zone.substr(0,19)
  var a2=zone.substr((zone.length-2),2)
  //for lifts and escalators
  if(level=="undercroft" && physics=="geom_Sphere01" && a1=="liftstuff_undercrof"){
    //cam_roam1
    //first reset the camera
    changeCamera("cam_roam2") ;
    //set the new camera to the right position and orientation
    var endpoint="liftstuff_platform_end" + a2;
    var x1=0;
    var y1=0;
    var z1=0;
    x1= TNTDoCommand('Scenegraph.Objects("' + endpoint + '").GetPositionWorldX()')
    y1= TNTDoCommand('Scenegraph.Objects("' + endpoint + '").GetPositionWorldY()')
    z1= TNTDoCommand('Scenegraph.Objects("' + endpoint + '").GetPositionWorldZ()')
    r1= TNTDoCommand('Scenegraph.Objects("' + endpoint + '").GetRotationWorldZ()')
    TNTDoCommand('Scenegraph.Objects("geom_Sphere02").SetPositionWorld(' + x1 + ',' + y1 + ','+z1+')');    
    TNTDoCommand('Scenegraph.Objects("geom_Sphere02").SetRotationWorld(,,'+r1+')');    

    level="platform";
    
    window.status=("undercroft fired");
  
  } else if(level=="platform" && physics=="geom_Sphere02" && a1=="liftstuff_platform_"){
    //cam_roam2
    //first reset the camera
    changeCamera("cam_roam1") ;
    //set the new camera to the right position and orientation
    var endpoint="liftstuff_undercroft_end" + a2;
    var x1=0;
    var y1=0;
    var z1=0;
    x1= TNTDoCommand('Scenegraph.Objects("' + endpoint + '").GetPositionWorldX()')
    y1= TNTDoCommand('Scenegraph.Objects("' + endpoint + '").GetPositionWorldY()')
    z1= TNTDoCommand('Scenegraph.Objects("' + endpoint + '").GetPositionWorldZ()')
    r1= TNTDoCommand('Scenegraph.Objects("' + endpoint + '").GetRotationWorldZ()')

    TNTDoCommand('Scenegraph.Objects("geom_Sphere01").SetPositionWorld(' + x1 + ',' + y1 + ','+ z1 +')');   
    TNTDoCommand('Scenegraph.Objects("geom_Sphere01").SetRotationWorld(,,'+ r1 +')');   
    level="undercroft"; 
    
    window.status=("platform fired");
  }

}

//=================================================

//node movement code

//needs some optimisation to get rid of rather choppy
//movement in the tnt

//=================================================



function showroute(){
  //this is a cheat
  //it needs to be replaced with code
  //to dynamically create route marker 
  TNTDoCommand('Scenegraph.Objects("undercroftmap_destination*").SetEnable(true)')
  TNTDoCommand('Scenegraph.Objects("undercroftmap_route*").SetEnable(true)')
}

function makeroute(nodelist){
  //send a string with node info in
  //this disagregates the string and starts
  //processing it into a valid route

  //disaggregate node list
  wparray=String(nodelist).split(",")
  
  //set off going at nodes
  view_undercroft_map();
  showroute();
}









var startnodex=0
var startnodey=0
var startnoderot=0

var startx=0
var starty=0
var startrot=0

var endx=0
var endy=0
var endrot=0

var currentx=0
var currenty=0
var currentrot=0

var xstep=0
var ystep=0
var rotstep=0

var steps=100
var rsteps=20;

var ismoving=false;

var firstmove=true

var currentnode=0;

var wparray = new Array()
wparray[0]="wp01"
wparray[1]="wp02"
wparray[2]="wp03"
wparray[3]=0;


function moveto(){
    if(ismoving==false){
      //hide/unhide bits of geometry
      TNTDoCommand('Scenegraph.Objects("undercroftmap*").SetEnable(false)')
      TNTDoCommand('Scenegraph.Objects("platformmap*").SetEnable(false)')
      TNTDoCommand('Scenegraph.Objects("geom*").SetEnable(true)')
      TNTDoCommand('CameraCtrl.Match("cam_moveto",2000)');
      grabcamerasettings("cam_mycam", "cam_moveto")    

      if(firstmove==true){
        //first time through 
        //pick up the starting coordinates of the block
        //pick up the block x-y
        startnodex = TNTDoCommand('SceneGraph.Objects("wpfollower").GetPositionWorldX()');
        startnodey = TNTDoCommand('SceneGraph.Objects("wpfollower").GetPositionWorldY()');  
        startnoderot = TNTDoCommand('SceneGraph.Objects("wpfollower").GetRotationWorldZ()');  
        
        firstmove=false;
      }else{
        //set the block back to its starting coordinates
        TNTDoCommand('SceneGraph.Objects("wpfollower").SetPositionWorld(' + startnodex + ',' + startnodey + ',)');
        TNTDoCommand('SceneGraph.Objects("wpfollower").SetRotationWorld(,,' + startnoderot + ')');        
      }
      //flip ismoving flag   
      ismoving=true
      currentnode=0  
      endx= startnodex;
      endy = startnodey;
      endrot=startnoderot;
      mode="flyto"
      setTimeout("moveto1()",2500)
      
    } else{
        //reset all this stuff
        //wait for everything to timeout and then
        //restart
        ismoving=false;
        if (mode=="flyto"){
          setTimeout("movetox()",2500)
        }else{
          setTimeout("movetox()",100)
        }
    }
}

function movetox(){
  //like moveto without the zoom in
    if(ismoving==false){
      //hide/unhide bits of geometry
      TNTDoCommand('Scenegraph.Objects("undercroftmap*").SetEnable(false)')
      TNTDoCommand('Scenegraph.Objects("platformmap*").SetEnable(false)')
      TNTDoCommand('Scenegraph.Objects("geom*").SetEnable(true)')
      TNTDoCommand('CameraCtrl.Match("cam_moveto",2000)');
      grabcamerasettings("cam_mycam", "cam_moveto")    

      if(firstmove==true){
        //first time through 
        //pick up the starting coordinates of the block
        //pick up the block x-y
        startnodex = TNTDoCommand('SceneGraph.Objects("wpfollower").GetPositionWorldX()');
        startnodey = TNTDoCommand('SceneGraph.Objects("wpfollower").GetPositionWorldY()');  
        startnoderot = TNTDoCommand('SceneGraph.Objects("wpfollower").GetRotationWorldZ()');  
        
        firstmove=false;
      }else{
        //set the block back to its starting coordinates
        TNTDoCommand('SceneGraph.Objects("wpfollower").SetPositionWorld(' + startnodex + ',' + startnodey + ',)');
        TNTDoCommand('SceneGraph.Objects("wpfollower").SetRotationWorld(,,' + startnoderot + ')');
      }
      //flip ismoving flag   
      ismoving=true
      currentnode=0  
      endx= startnodex;
      endy = startnodey;
      endrot=startnoderot;
      //next camera
      TNTDoCommand('CameraCtrl.SetCurrent("cam_findnode")')
      //calculate where its going
      calcnodemove();
      
    } else{
        //reset all this stuff
        //wait for everything to timeout and then
        //restart
        ismoving=false;
        if (mode=="flyto"){
          setTimeout("movetox()",2500)
        }else{
          setTimeout("movetox()",100)
        }
    }
}


function moveto1(){
  if(ismoving==true){
    mode="normal";
    //next camera
    TNTDoCommand('CameraCtrl.SetCurrent("cam_findnode")')
    
    //hide a bunch of stuff serupticious like
    TNTDoCommand('Scenegraph.Objects("geom_depart*").SetEnable(false)')
    TNTDoCommand('Scenegraph.Objects("geom_vip*").SetEnable(false)')
    TNTDoCommand('Scenegraph.Objects("geom_champbar*").SetEnable(false)')
    
    //calculate where its going
    calcnodemove();  
   }     
}

function calcnodemove(){
  //calculate the correct node movement
  
  if(wparray[currentnode]!=0){
    //reset leftright
    leftright=0;
    
    
    //first work out x/y increments for position
    startx=Number(endx)
    starty=Number(endy)
    startrot=Number(endrot)
    
    endx= Number(TNTDoCommand('SceneGraph.Objects("' + wparray[currentnode]+ '").GetPositionWorldX()'));
    endy = Number(TNTDoCommand('SceneGraph.Objects("' + wparray[currentnode]+ '").GetPositionWorldY()'));
    endrot = Number(TNTDoCommand('SceneGraph.Objects("' + wparray[currentnode]+ '").GetRotationWorldZ()'));
    while((endrot-startrot)>180){
        endrot-=360;
    }
    while((endrot-startrot)<-180){
        endrot+=360;
    }  
    xstep= (endx-startx)/steps;
    ystep=  (endy-starty)/steps;
    rotstep = (endrot-startrot)/rsteps;

    movetonewnode(0)
  }else{
    ismoving=false;
  }
}

function movetonewnode(nodestep){
  if(ismoving==true){
  
    currentx=0.0+ startx + ( nodestep* xstep);
    currenty=0.0 +starty + (nodestep* ystep);
    if (nodestep>steps-rsteps){
      currentrot= 0.0 + startrot + ((nodestep-(steps-rsteps)-1)*rotstep)
    } else{
      currentrot=startrot
    }
    
    TNTDoCommand('SceneGraph.Objects("wpfollower").SetPositionWorld(' + currentx + ',' + currenty + ',)');
    TNTDoCommand('SceneGraph.Objects("wpfollower").SetRotationWorld(,,' + currentrot + ')');

    //repeat until we're no longer moving
    if(nodestep<=100){
      setTimeout("movetonewnode("+ (nodestep+1)+")",1);
    }else{
      currentnode++;
      calcnodemove();
    }
  }
}




function towalk(){
    moveto();
    TNTDoCommand('CameraCtrl.SetCurrent("cam_wp04")');
}


function tostart(){
    var x1=Number(startnodex);
    var y1=Number(startnodey);
    var r1=Number(startnoderot);
    TNTDoCommand('SceneGraph.Objects("wpstatic").SetPositionWorld(' + x1 + ',' + y1 + ',)');
    TNTDoCommand('SceneGraph.Objects("wpstatic").SetRotationWorld(,,' + r1 + ')');   
    TNTDoCommand('CameraCtrl.SetCurrent("cam_staticnode")');
}
function toend(){
    var x1=Number(TNTDoCommand('SceneGraph.Objects("' + wparray[2]+ '").GetPositionWorldX()'));
    var y1=Number(TNTDoCommand('SceneGraph.Objects("' + wparray[2]+ '").GetPositionWorldY()'));
    var r1=Number(TNTDoCommand('SceneGraph.Objects("' + wparray[2]+ '").GetRotationWorldZ()'));
    TNTDoCommand('SceneGraph.Objects("wpstatic").SetPositionWorld(' + x1 + ',' + y1 + ',)');
    TNTDoCommand('SceneGraph.Objects("wpstatic").SetRotationWorld(,,' + r1 + ')');   
    TNTDoCommand('CameraCtrl.SetCurrent("cam_staticnode")');
}



var leftright=0;
var leftrightstep=5

function toleft(){
    if (leftright<0){
      leftright=0;
    }else{
      leftright+=leftrightstep;
    }
    var r1 = leftright//Number(startnoderot)+leftright;
    TNTDoCommand('SceneGraph.Objects("wp_rotate").SetRotationLocal(,,' + r1 + ')');

}
function toright(){
    if (leftright>0){
      leftright=0;
    }else{
      leftright-=leftrightstep;
    }
    var r1 = leftright//Number(startnoderot)+leftright;
    element()
    TNTDoCommand('SceneGraph.Objects("wp_rotate").SetRotationLocal(,,' + r1 + ')');

}

function grabcamerasettings(camto, camfrom){
    var x1= TNTDoCommand('Scenegraph.Objects("'+ camfrom + '").GetPositionWorldX()')
    var y1= TNTDoCommand('Scenegraph.Objects("'+ camfrom + '").GetPositionWorldY()')
    var z1= TNTDoCommand('Scenegraph.Objects("'+ camfrom + '").GetPositionWorldZ()')
    
    var x2= TNTDoCommand('Scenegraph.Objects("'+ camfrom + '").GetRotationWorldX()')
    var y2= TNTDoCommand('Scenegraph.Objects("'+ camfrom + '").GetRotationWorldY()')
    var z2= TNTDoCommand('Scenegraph.Objects("'+ camfrom + '").GetRotationWorldZ()')
    TNTDoCommand('Scenegraph.Objects("'+ camto + '").SetPositionWorld('+x1+','+y1+','+z1+')')
    TNTDoCommand('Scenegraph.Objects("'+ camto + '").SetRotationWorld('+x2+','+y2+','+z2+')')

}

var isblock=false;
function swapoutblock(){
  if(isblock==true){
    TNTDoCommand('Scenegraph.Objects("*block").SetEnable(true)')
    TNTDoCommand('Scenegraph.Objects("*noblock").SetEnable(false)')
  }
  else{
    TNTDoCommand('Scenegraph.Objects("*block").SetEnable(false)')
    TNTDoCommand('Scenegraph.Objects("*noblock").SetEnable(true)')  
  } 
}








//===============================

//PVS groups

//to be called internally 
//to hide unneeded geometry
//where necessary

//===============================
      //======================================
      //set up basic objects
      //======================================
			var group1vis=true;
			var group2vis=true;


      function Visgroup(subscript1){
        this.visible=true;
        this.subscript=subscript1; 
        this.killvis=false;
      }
      function Boundingarea(x1,x2,y1,y2,z1,z2,v1){
        this.lowxbound=x1;
        this.highxbound=x2;
        this.lowybound=y1;
        this.highybound=y2;
        this.lowzbound=z1;
        this.highzbound=z2;
        this.testpoint=testpoint;
        this.visgroups=v1;       
      }
      function testpoint(x1,y1,z1){
        if(
              x1>this.lowxbound && x1<this.highxbound
           && y1>this.lowybound && y1<this.highybound
           && z1>this.lowzbound && z1<this.highzbound 
        ){
          return true;
        }else{
          return false;
        }
      }
      
      //==========================================
      //set up actual visgroups and bounding boxes
      //==========================================  
      var vgroups = new Array();
      var areas = new Array();    
      
      //defines each group and its subscripts 
      vgroups[0] = new Visgroup("g0_");
      vgroups[1] = new Visgroup("g1_");
      vgroups[2] = new Visgroup("g2_");
 
      //defines bounding area bounds and a list of associated visgroups to hide
      // in the form (lowerxbound, upperxbound, lowerybound, upperybound,...[list of vgroup numbers to hide]);
      areas[0]=new Boundingarea(-50,0,-50,50,-250,250, [1]);
      areas[1]=new Boundingarea(0,50,-50,50,-250,250, [2] );
      
      //======================================
      //set up main loop
      //======================================
			function testpvs(){
        //this code should probably be integrated with the settimeout loop
        //in the movement code for efficiency
        var g1new =true
         var g2new = true

         //test physics sphere for bounds
         var mainviewx = TNTDoCommand('SceneGraph.Objects("mainview").GetPositionWorldX()')
         var mainviewy = TNTDoCommand('SceneGraph.Objects("mainview").GetPositionWorldY()')
         var mainviewz = TNTDoCommand('SceneGraph.Objects("mainview").GetPositionWorldZ()')

         for(i=0; i<areas.length; i++){
                 if( areas[i].testpoint(mainviewx, mainviewy, mainviewz)==true){
                    //hide the appropriate areas
                    for(j=0; j<areas[i].visgroups.length; j++){
                      //hide the item in the visgroup
                      vgroups[areas[i].visgroups[j]].killvis=true;
                    }
                 }
         }
         for(i=0; i<vgroups.length; i++){
                  if( vgroups[i].killvis==true && vgroups[i].visible==true){
                      TNTDoCommand('SceneGraph.Objects("'+ vgroups[i].subscript+ '*").SetVisible(false)');
                      vgroups[i].killvis=false;
                      vgroups[i].visible=false;
                  }else if( vgroups[i].killvis==false && vgroups[i].visible==false ){
                      TNTDoCommand('SceneGraph.Objects("'+ vgroups[i].subscript+ '*").SetVisible(true)');
                      vgroups[i].visible=true
                  }else{
                      vgroups[i].killvis=false;
                  }
         }

          setTimeout("testpvs()",100);

      }
      setTimeout("testpvs()",10);







//=============================================

//probably useless functions

//to check later

//=============================================


 function clicker(obj){
	//doesn't do anything at the moment
	//just here so I can keep my code all in one place
	//I'll prtobably need to implement this eventually
}

function obj_layout(x1,y1,z1){
  //can't remember what this does
  this.x=x1;
  this.y=y1;
  this.z=z1;
}

function setoption(optnum){
  //hide everything
  TNTDoCommand('Scenegraph.Objects("opt*").SetEnable(false)')
  //unhide the right option
  TNTDoCommand('Scenegraph.Objects("opt'+optnum+'*").SetEnable(true)')
  TNTDoCommand('Scenegraph.Objects("opt'+optnum+'*").SetVisible(true)')
  
}

function setdefaultlayout(){
  //doesn't do much yet
  TNTDoCommand('Scenegraph.Objects("opt*").SetEnable(false)')  
  
}

function setarea(areaname){
    //move to a specific area in the model


    //identify current
}













//=============================================

// the following is a bunch of predefined TurnTool Stuff

//with minor changes

//=============================================




		var ie4 = (document.all && !document.getElementById);
		var ie5 = (document.all && document.getElementById);
		var ns6 = (!document.all && document.getElementById);
		
		function createTurnTool(width, height, file, color, transparent, install)
		{
 			 var turntoolObject = ''
 			 if (install)
 			 {
    			turntoolObject = '<center><input type="button" value="Install TurnTool Viewer" onclick="installTurnTool();" /></center>';
  			}
  			if (ie4||ie5)
 			 {
  				turntoolObject += '<object id="TNTCtrl" width="'+width+'" height="'+height+'" classid="CLSID:402ee96e-2ce8-482d-ada5-ceceea07e16d" codebase="http://www.turntool.com/ViewerInstall.exe#version=2,12,0,8"><param name="transparent" value="'+transparent+'"><param name="ctrl_color" value="'+color+'"><param name="tnt_back_color" value="'+color+'"><param name="src" value="'+file+'"></OBJECT>';
 			 	turntoolObject += '<scr'+'ipt type="text/javascript" for="TNTCtrl" event="TNTEvent(string);">execScript(string);</scr'+'ipt>';
 			 }
  			else
  			{
		      	if (install==false)
 				{
				  	turntoolObject += '<embed id="TNTCtrl" width="'+width+'" height="'+height+'" src="'+file+'" transparent="0" ctrl_color="'+color+'" tnt_back_color="'+color+'" pluginspage="http://www.turntool.com/download/" type="application/tntfile"></embed>';
				}
  			}
  			element('TurnTool').innerHTML = turntoolObject;
		}



		function element(id)
		{
			if(ie4)	// Explorer 4
				return document.all[id];
			else	// Explorer 5+ Netscape 6+ and Mozilla and Firefox
				return document.getElementById(id);
		}
		
		function initTurnTool()
		{
			var tntWidth 			= 520;
			var tntHeight 			= 360;
			var tntFilename 		= "http://www.stpancras.com/3d-model/blockmodel6.tnt";
			var tntColor 			= "#ffffff";
			var tntTransparent 		= 0;
			
			var tntInstalled 		= isTurnToolInstalled();
			//checker();
      if (tntInstalled==false)
			{
				createTurnTool(tntWidth,tntHeight,tntFilename,tntColor,tntTransparent,true);
				checkRefresh();
			}
			else
				createTurnTool(tntWidth,tntHeight,tntFilename,tntColor,tntTransparent,false);
		}
		
		function isTurnToolInstalled()
		{
			var tntInstalled = false;
			if(ie4||ie5)
			{
				try
				{
					var xObj = new ActiveXObject("TNT.TNTCtrl");
					if (xObj)
						tntInstalled = true;
				}
				catch (e){}
			}
			else
			{
				if(navigator.plugins.namedItem("TurnTool XPCOM Plugin"))
					tntInstalled = true;
			}
			return tntInstalled;
		}
		
		function installTurnTool()
		{
			if(ie4||ie5)
				window.location.href = "http://www.turntool.com/OfflineInstall.exe";
			else
			{
				var xpi = {'TurnTool Viewer Installation':'http://www.turntool.com/ViewerInstall.xpi'};
				InstallTrigger.install(xpi,installFinish);
			}
		}
		
		function installFinish(url, result)
		{
			window.location.href = window.location;
		}
		
		var checkCounter = 0;
		function checkRefresh()
		{
			var tntInstalled = isTurnToolInstalled();
			if(tntInstalled==false)
			{
				checkCounter++;
				if (checkCounter>120)
				{
					checkCounter=0;
					installTurnTool();
				}
				setTimeout('checkRefresh()',500);
			}
			else
				window.location.href = window.location;
		}
		
		function TNTDoCommand(string)
		{
			var control = element("TNTCtrl");
			if(control && control.ready)
				return control.TNTDoCommand(string);
			return "";
		}
		
		function focus()
		{
			if (!ns6)
				element("TNTCtrl").focus();
		}
		
		function doCommand()
		{
			var retval = TNTDoCommand( element("doCommandEdit").value );
			if(retval)
				element("returnval").innerHTML = 'Return Value = "' + retval + '"';
			else
				element("returnval").innerHTML = "";
		}
		
		function onDoCommandKeypress()
		{
			if(window.event.keyCode==13) // if return key was pressed
				doCommand();
		}
		
		var queuecam
		var camqueue ="Camera01"
		function OnReady()
		{
			loadExternalTextures();
			//makeCameraButtons();
			//makeAnimationButton();
			focus();
			//element("turntool").style.visibility="visible";
			//window.status = "TurnTool Ready";	
			TNTDoCommand('Scenegraph.Objects("location_*").SetEnable(false)')

		}
		
		var posx, posy ,posz, rotx, roty, rotz, productcam
		function OnClick( obj )
		{
			//if(TNTDoCommand('Objects(' + obj + ').GetStopFrame()')!=200)
			//	TNTDoCommand('Objects(' + obj + ').PlayAnimation(,200)');
			//else
			//	TNTDoCommand('Objects(' + obj + ').PlayAnimation(,0)');
			//window.status = "Object clicked: " + obj;

      
      

	     clicker(obj);	
		}
		
		moveobject=""
		function OnMouseEnter( obj )
		{
			//TNTDoCommand('Objects(' + obj + ').SetDiffuseColor(#0000FF)');
			
			if(!moving){
      
              //TNTDoCommand('SceneGraph.Objects(' + obj + ').SetDiffuseColor(#FF0000)');
              TNTDoCommand('Objects(' + obj + ').SetSelected(1)');
              moveobject=obj;      
      }
			//win dow.status = "Mouse Entered: " + obj;	
		}
		
		function moveselect(){
    TNTDoCommand('Selection.SetMoveDirectionX(1)')
    TNTDoCommand('Selection.SetMoveDirectionY(1)') 
    TNTDoCommand('Selection.SetMoveDirectionZ(0)') 
    TNTDoCommand('Selection.SetLeftMode(1)') 
    TNTDoCommand('Selection.SetRightMode(0)') 
}
		
		function OnMouseExit( obj )
		{
			//TNTDoCommand('Objects(' + obj + ').ResetMaterial()');
			
      TNTDoCommand('Objects(' + obj + ').SetSelected(0)');
		}
		
		var moving = false; 
  function OnMoveStart(obj )
		{
		  TNTDoCommand('Objects(' + moveobject + ').SetTransparency(0.5)');
      moving = true;
      TNTDoCommand('CameraCtrl.SetIgnoreInput(1)');
      TNTDoCommand('Selection.SetMoveDirectionX(1)')
      TNTDoCommand('Selection.SetMoveDirectionY(1)') 
      TNTDoCommand('Selection.SetMoveDirectionZ(0)') 
      TNTDoCommand('Selection.SetRightMode(0)')   		
     }
  function OnMoveEnd(obj )
		{
      moving = false;
      TNTDoCommand('CameraCtrl.SetIgnoreInput(0)'); 		
		  TNTDoCommand('Objects(' + moveobject + ').ResetMaterial()');
     }	
		function OnZoneEnter( zone, physics )
		{
		  //TNTDoCommand('SceneGraph.Objects("opendoor*").PlayAnimation(0,200,false,20)')
			zoneenter(zone,physics);
      focus();
			//window.status = "Zone Entered: " + zone + ", by physics object: " + physics;	
		}
		
		function OnZoneExit( zone, physics )
		{
		  //TNTDoCommand('SceneGraph.Objects("opendoor*").PlayAnimation(,0,false,20)')
			focus();
			//window.status = "Zone Exited: " + zone + ", by physics object: " + physics;	
		}               
		
		function OnKeyPress( keyCode, ascii )
		{
			//window.status = "KeyPress: KeyCode=" + keyCode + " Ascii=" + ascii;
		}
		
		function OnKeyRelease( keyCode, ascii )
		{
			//window.status = "KeyRelease: KeyCode=" + keyCode + " Ascii=" + ascii;
		}
		
		function Restart()
		{
			TNTDoCommand('SceneGraph.Physics.Reset()');
			TNTDoCommand('Objects(*).StopAnimation()');
			TNTDoCommand('Objects(*).SetFrame(0)');
			cameraName = TNTDoCommand('SceneGraph.Camera(0).GetName()');
			TNTDoCommand('CameraCtrl.SetCurrent("'+ cameraName+'")');
		}
		
		function HideShowObject(id)
		{
			var objname = TNTDoCommand('SceneGraph.Mesh('+ id + ').GetName()');
			var checkboxEl = element('checkbox' + id);
			TNTDoCommand('Objects(' + objname + ').SetVisible('+(!checkboxEl.checked)+')');
		}
		
		
		function changeCamera(newCamera)
		{
			var currentCamera = TNTDoCommand('CameraCtrl.GetCurrent()');
			var srcParentNodeIdx = TNTDoCommand('Objects('+currentCamera+').GetParentNodeIndex()');
			var desParentNodeIdx = TNTDoCommand('Objects('+newCamera+').GetParentNodeIndex()');
			if (srcParentNodeIdx == desParentNodeIdx)
				TNTDoCommand('CameraCtrl.Match("'+newCamera+'",2000)');
			else
				TNTDoCommand('CameraCtrl.SetCurrent("'+newCamera+'")');
		}
		
		function makeCameraButtons()
		{
			var cameraCount = TNTDoCommand('SceneGraph.GetCameraCount()');
			var html = '';
			for (var j=0; j<cameraCount; j++)
			{
				var cameraName = TNTDoCommand('SceneGraph.Camera('+j+').GetName()');
				html += '<input type="button" value="'+cameraName+'" class="button" onclick="changeCamera(\''+cameraName+'\')" />';
			}
			element('CameraCell').innerHTML = html;
		}
		
		function playAnimation()
		{
			if(TNTDoCommand('Objects(*).GetStopFrame()')!=200)
			{
				TNTDoCommand('Objects(*).PlayAnimation(,200)');
				element('PlayButton').value = "Play Backward";
			}
			else
			{	
				TNTDoCommand('Objects(*).PlayAnimation(,0)');
				element('PlayButton').value = "Play Forward";
			}
		}
		
		function makeAnimationButton()
		{
			frameCount = TNTDoCommand('SceneGraph.GetFrameCount()');
			if(frameCount > 1)
				element('AnimationCell').innerHTML +='<input type="button" id="PlayButton" value="Play Forward" class="button" onclick="playAnimation();" />';
		}
		
		function loadExternalTextures()
		{
			var texcnt = 0;
			texcnt = TNTDoCommand('SceneGraph.GetBitmapCount()');
			var bExternal = 64;
			var bHasAlpha = 32;
			for( var i=0; i<texcnt; i++ )
			{
				var props = 0;
				props = TNTDoCommand('SceneGraph.Bitmap(' + i + ').GetProperties()');
				if(props & bExternal)
				{
					var name = TNTDoCommand('SceneGraph.Bitmap(' + i + ').GetName()');
					if(props & bHasAlpha)
						name += '.png'; // alpha textures are exported as png
					else
						name += '.jpg'; // non-alpha textures are exported as jpg
					TNTDoCommand('SceneGraph.Bitmap(' + i + ').Load("' + name + '")');
				}
			}
		}
		
		function saveImage()
		{
			var index = element("ImageSize").selectedIndex;
			TNTDoCommand('Renderer.SaveImage("ScreenShot.bmp",'+index+')')
		}
		
		function addEvent( obj, type, fn )
		{
			if (obj.addEventListener)
		 		obj.addEventListener( type, fn, false );
		 	else if (obj.attachEvent)
		 	{
			  obj["e"+type+fn] = fn;
			  obj.attachEvent( "on"+type, function() { obj["e"+type+fn](); } );
		 	}
		}
		
		function removeEvent( obj, type, fn )
		{
			if (obj.removeEventListener)
		  	obj.removeEventListener( type, fn, false );
		 	else if (obj.detachEvent)
		 	{
			  obj.detachEvent( "on"+type, obj["e"+type+fn] );
			  obj["e"+type+fn] = null;
		 	}
		}

 	addEvent(window,"load",initTurnTool);




