// Compress Normal
/* Compress:
onscene.js
classes.js
geometry.sc
Mashup.GoogleEarth.js
Mashup.GoogleEarth2D.js
Mashup.VirtualEarth.js
*/

//        deleteCookie("RememberMe","","");    
//        deleteCookie("LoggedIn","","");    
//        deleteCookie("Totd","","");    
var tips = [];
tips[tips.length] = "Welcome to OnScene, a 3D exploration of the world of a book. We're adding new place names daily! Click on the <b>Location Index</b> tab for a list of place names you can fly-to. Once there, click on an icon for more.";
tips[tips.length] = "If you meet the operating system and browser requirements, Virtual Earth&trade; and Google Earth&trade; will run simultaneously. Click the Google Earth or Virtual Earth button above the map to switch between them.";
tips[tips.length] = "In Virtual Earth, when this globe is full, map loading is complete:<br /><center><img src='/images/ve_globe.gif' border='0' align='center' ></center>";
tips[tips.length] = "After clicking the book cover to open the book, click the right and left arrows to move through the pages.<br /><center><img src='/images/arrow_left.jpg' border='0' float='left' ><img src='/images/arrow_right.jpg' border='0' float='right' ></center>"
                  + "<span style='background:yellow'><strong>When you reach an underlined place name, click it.</strong></span>";
tips[tips.length] = "Blurry 3D image? Make sure loading is complete. If so, click the place name again, or the <strong>Recycle</strong> button:<br /><center><img style='margin: 10px 0 0 0' src='/images/recycle.png' border='0' ></center>";
tips[tips.length] = "If you already have a username and password for www.clydeford.com you don't have to re-register. You can use them to log-in to OnScene.";
tips[tips.length] = "Want to remove the map controls from view? Click the <strong>Controls</strong> button:<br /><center><img style='margin: 10px 0 0 0' src='/images/controls_on.png' width='20' height='20' border='0' ></center>";
tips[tips.length] = "Click on the <b>FAQ</b> tab for more information about using OnScene.";
tips[tips.length] = "Want to learn more about the Google Earth&trade;? Click below:<br /><center><a href='http://earth.google.com/' target='_blank'>Learn more about Google Earth&trade;.</a></center>";
tips[tips.length] = "Want to learn more about the Virtual Earth&trade;? Click below:<br /><center><a href='http://www.microsoft.com/virtualearth' target='_blank'>Learn more about Virtual Earth&trade;.</a></center>";
tips[tips.length] = "Want your book or project enhanced with Google Earth&trade; or Virtual Earth&trade;? Click below:<br /><center><a href='mailto:info@clydeford.com' target='_blank'>Interested in OnScene for my project.</a></center>";
var ge=null,bCover=false,bookPages=null,rotInfo=null,startPMTries=0,
pinID=0,MAP_WIDTH=542,MAP_HEIGHT=546,innerPages=16,innerStart=41,bookStart=6,
guidePages=17,guideStart=1,locIndexPages=18,startPMTimer=null,
locIndexStart=1,tocPages=99,tocStart=1,notifyWin=null,faqWin=null,
specialPages=19,specialStart=1,loginWin=null,Tour=null,tourHelpWin=null,
totdWin=null,adminMenuWin=null,fillWin=null,tourWin=null,overviewWin=null,installWin=null,
veShapeType={Pushpin:0, Polyline:1, Polygon:2},
veDashboardSize={tiny:0, small:1, normal:2},task=null,
pmID=0,pmIndex=null,avPmIndex=null,tourIndex=null,RANGE_DIST_CONST=1.0,
GEVE_ALT_CONST=1.0,polyWin=null,pathWin=null,placemarkWin=null,helpWin=null,
optionsWin=null,Options=null,Descriptions=null,courseWin=null, rotVideo=null,
SECS=1000,MINS=SECS * 60,HRS=MINS * 60,DAYS=HRS * 24, YEARS=DAYS * 366, MAX_ACCESS=9999999,
bUserLoggedIn=false,GEFix=false,VEFix=false,RADS=Math.PI/180,VIDEO_DELAY_CONST=5000,
lookupAng=[0,0,4,6,8,8,12,16,20,0],T_geLoadFailure="ERROR: Google Earth Failed To Load.\n\nIf this is your first time using OnScene\nyou may need to load the special Google Earth plug-in.\nClick on the large blue button marked, 'Get\nthe Google Earth Plug-in' and follow the onscreen instructions.\nAfter installing the plug-in you will need to\nrestart your browser, and navigate back\nto the OnScene starting page.",
T_noSwap="It is currently not possible to show\nOnScene in "
;

function geAdminMenu(){
    var cookie=getCookie("LoggedIn");
    if ( cookie === null || cookie === undefined || cookie === 0 ) { return; }

    function onAdminCredentialsComplete(result) {
        if (result) { showAdminMenu(); }
    }
    
    function onAdminCredentialsFailed(result) {
    }
    PageService.AdminCredentials(cookie, onAdminCredentialsComplete, onAdminCredentialsFailed);
}

function showAdminMenu()
{
    if ( useVE ) { return; }
    var vScroll=Geometry.getVerticalScroll();
    var h=21;  
    var w=136;
    var pos=findPos($get('leftmap'));
    var left=pos.left + ((MAP_WIDTH - w)>>1);
    var top=pos.top+100 - vScroll;
    var html='<img src="' + docDomain + '/images/ge_admin_menu.gif" border="0" usemap="#ge_admin_map" />';
    var style='width='+w+'px,height='+h+'px,left=' + left + 'px,top=' + top + 'px,resize=0,scrolling=0,detail=0,controls=0,color=#F0F0F0';
    adminMenuWin=popupDiv.open('adminMenuWin', 'inline', html, '', style );
}

function onClick_Install()
{
    var urlparts = document.URL.split('/');
    var baseURL = urlparts[0]+"//"+urlparts[2]+"/";

    var w=450, h=400;      
    var style='width='+w+'px,height='+h+'px,left=0px,top=0px,center=1,resize=0,scrolling=0,detail=0,controls=1,color=#0B55C4';
    installWin=popupDiv.open('installWin', 'iframe', baseURL + 'html/install.htm', 'Install Virtual and Google Earth Plugins', style );
}

function onClick_Fill(obj)
{
    var map = findMap();
    var id = map._shapeId;
    
    if (obj.checked )
    {
        map._redraw_polyshapes(1);
    }
    else
    {
        map._redraw_polyshapes(0);
    }
    return false;
}

function showFillControl()
{
return;
    var center="";
    if ( fillWin !== null )
    {
        if ( !fillWin.isClosed )
        {
            return;
        }
    }
    var vScroll=Geometry.getVerticalScroll();
    var h=20;  
    var w=80;
    var pos=findPos($get('leftmap'));
    var left=pos.left + MAP_WIDTH + 8 - w;
    var top=pos.top+ 8 - vScroll;
    if ( !useVE && (AppMode.GE.Mode == OnScene.Mode2D) )
    {
        left-=(MAP_WIDTH-w)>>1;
    }
    
    var html='<div style="width:80px;font:bold 8pt/1em arial, helvetica, sans-serif"><input onclick="onClick_Fill(this);" type="checkbox" checked id="fill" />Show Fill</div>';
    var style='width='+w+'px,height='+h+'px,left=' + left + 'px,top=' + top + 'px,resize=0,scrolling=0,detail=0,controls=0,color=#F0F0F0';
    fillWin=popupDiv.open('fillWin', 'inline', html, '', style );
}
           
function pageLoad() {

    updateStats("Home");
    bookPages=new BookPages($get("page_display"), "Clyde W. Ford", "Precious Cargo", true);
    rotInfo=new Rotator("rotator", 1.125, 1.125, 10);
    initDOM();
    getRequestVars();
    getBookPages();
    getPlacemarkIndex();
    getAVPlacemarkIndex();
    getTourIndex();
    getInfoContent();
    setUserInfo();
    initInstall();
//    initTrailer();
    doTask();
}

function initInstall()
{
    // If partial installed then show install screen before TOTD
    if ( (!AppMode.GE.Installed && AppMode.GE.Available) || (!AppMode.VE.Installed && AppMode.VE.Available) ) {
        if ( AppMode.OS != 'Mac' ) onClick_Install();
        return;
    }
}

function doTask()
{
    
    if ( task === "favorite" )
    {
        showTourIndex(1,0);
    }
    
    if ( startID > 0 )
    {
        showStartPM();        
    }

}

function showStartPM()
{
    // Get the map we're using
    var map = findMap();
    
    // Have we gone beyond 10 seconds of trying
    if ( ++startPMTries > 20 )
    {
        // Timed out waiting for virtual globe to initialize
        clearTimeout( startPMTimer );
        alert("Please click on the green Location Index tab, to find this place mark.");
        return;
    }
    if ( map._bLoaded && ge !== null )
    {
        // Virtual globe is initialized, fly to the placemark
        syncGlobes();
        getPM( startID );
    }
    else
    {
        // Virtual globe is not initialized, set timer and wait
        startPMTimer = setTimeout( showStartPM, 500 );
    }
}

function syncGlobes() {
    if (AppMode.OS == 'Mac') return;
    if ( useVE && $get('VEMap').style.visibility==="hidden" )
    {
        $get('VEMap').style.visibility="visible";    
        if ( AppMode.GE.Mode == OnScene.Mode3D )
        {
            $get('GEMap').style.visibility="hidden";
        }
        else 
        {
            $get('GEMap2D').style.visibility="hidden";
        }
    }

    if ( !useVE && ($get('GEMap').style.visibility="hidden"
    || $get('GEMap').style.visibility==="hidden") )
    {
        $get('VEMap').style.visibility="hidden";    
        if ( AppMode.GE.Mode == OnScene.Mode3D )
        {
            $get('GEMap').style.visibility="visible";
        }
        else 
        {
            $get('GEMap2D').style.visibility="visible";
        }
    }

    swapImages();
}

function swapImages(){
    $get('img_globe').src="images/" + (!useVE?'ve':'ge') + "_view.png";
    $get('img_globe').title="Show map in " + (!useVE?"Virtual Earth ":"Google Earth");
}

function swapGlobes(){

    closeAllPops();

    if ( useVE ) {
        var geMap = (AppMode.GE.Mode == OnScene.Mode2D) ? 'GEMap2D' : 'GEMap';
        $find(geMap).init_view();
        $get('VEMap').style.visibility="hidden";
        useVE=false;
    }
    else {
        if ( AppMode.GE.Mode == OnScene.Mode3D ) 
        {
            // 3D visibility to false
            if ( ge !== null ) ge.getWindow().setVisibility(false);
        }
        else
        {
            $get('GEMap2D').style.visibility='hidden';
        }
        
        $get('VEMap').style.visibility="visible";
        useVE=true;
    }
    
    swapImages();
}

function totd(start){
    return;
    //deleteCookie("Totd");
    // Is totd off cookie enabled?
    if ( start === undefined ){
        start = 0;
    }
    var totdCookie=getCookie("Totd");

    // If totd cookie exists then user doesn't want to show totd screen
    if ( totdCookie !== null ) { return; }
    
    getTotdHTML(start);
}

function showTOTD(html, start) {
    return;
    if ( start === undefined ){
        start = 0;
    }
    // Pop-up user logon
    var w=400, h=300;      
    var style='width='+w+'px,height='+h+'px,left=0px,top=0px,center=1,resize=0,scrolling=0,detail=0,controls=1,color=#0000FF';
    totdWin=popupDiv.open('totdWin', 'inline', html, 'OnScene: Tip of the Day', style );
    
    // Set the timer
    //setTimeout(closeTotd, 20000);
    loadTotd(start);
}

function closeTotd(){
    if ( totdWin !== null ) totdWin.close();
}

function getRequestVars(){
    var url=document.URL;
    var querystring=url.substring( url.indexOf("?")+1 );        
    var pairs=querystring.split("=");
    var key=pairs[0];
    var value=pairs[1];
    
    if ( key !== 'usn' ) { return; }
    
    deleteCookie("LoggedIn","","");

    function onIsLoggedInComplete(result) {
       setCookie("LoggedIn", result, 20*MINS, "/", "", "" );
       setUserInfo();
    }
    
    function onIsLoggedInFailed() {
    }
    PageService.IsLoggedIn( value, onIsLoggedInComplete, onIsLoggedInFailed );
}

function getUserInfo()
{
    var User;
    var userInfo=getCookie("LoggedIn");
    if (userInfo === null) 
    {
        User={Userid:null, Password:null};
    }
    else
    {
        var userArray=userInfo.split("+");
        User={Userid:userArray[0],Password:userArray[1]};
    }
    return User;
}

function setUserInfo(userid)
{          
    var usn, bRegister=false, bLogin=false;
    
    if ( userid === undefined )
    {
        usn=getUserInfo().Userid;
    }
    else
    {
        usn=userid;
    }
    
    if ( usn === null || usn === '' || usn === undefined || usn === 'default'
        || usn === 'Guest')
    {    
        usn="Guest";
        bRegister=true;
        bLogin=true;
    }
    
    if ( $get("welcome") )
    {            
        $get("welcome").innerHTML="Welcome, " + usn;
        $get("login").innerHTML=bLogin ? "Login" : "Logout";
        $get("register").style.display=bRegister ? "block" : "none";            
        $get("register").innerHTML="Register";
    }
}

function getUserCookies(){
    // Check for access count cookie
    if ( getCookie("AccessCount") === null )
    {
        setCookie("AccessCount","0", 366*DAYS, "/", "", "" );
    }
        
    // Check for logged-in
    bUserLoggedIn=isUserLoggedIn();
    if ( bUserLoggedIn ) { return; }
    

    // Check for remember me cookie. If present, log-in.
    var rememberMe=getCookie("RememberMe");
    if ( rememberMe !== null ) 
    {
        userAutoLogin( rememberMe ); 
    }
}

function userAutoLogin( usnPwd ){ 
    var logonString=usnPwd.split("+");
    
    function onAutoLogonComplete(result) {
       setCookie("LoggedIn", result, 20*MINS, "/", "", "" );
       setUserInfo();
    }
    
    function onAutoLogonFailed() {
        alert("Autologon Failed.");
    }
    PageService.UserLogon(logonString[0], logonString[1], onAutoLogonComplete, onAutoLogonFailed);
}

function isUserLoggedIn(){
    var cookieLoggedIn=getCookie("LoggedIn");
    if ( cookieLoggedIn === null || cookieLoggedIn === "" ) 
    {
        getUserInfo();
        setUserInfo();
        return false;
    }
    deleteCookie("LoggedIn","","");
    setCookie("LoggedIn", cookieLoggedIn, 20*MINS, "/", "", "" );
    return true;
}

function getBookPages() {        
        function onGetPageComplete(result) {
            bookPages.load_pages(result,0);
            loadTocDiv();
        }
        
        function onGetPageFailed() {
            alert("Get Page Failed.");
        }
        PageService.GetBookPages(6, innerPages, innerStart, onGetPageComplete, onGetPageFailed);
}

function getPlacemarkIndex() {        
        function onGetIndexComplete(result) {
            pmIndex=result;
        }
        
        function onGetIndexFailed() {
            alert("Get Index Failed.");
        }

        PageService.GetPlacemarkIndex(1, 1, onGetIndexComplete, onGetIndexFailed);        
}

function getAVPlacemarkIndex() {        
        function onGetAVIndexComplete(result) {
            avPmIndex=result;
        }
        
        function onGetAVIndexFailed() {
            alert("getAV Index Failed.");
        }

        PageService.GetAVPlacemarkIndex(1, 1, onGetAVIndexComplete, onGetAVIndexFailed);        
}

function getTourIndex() {        
        function onGetIndexComplete(result) {
            tourIndex=result;
        }
        
        function onGetIndexFailed() {
            alert("Get Tour Index Failed.");
        }

        // 99 = My Favorite places. Call this with different catid and store
        PageService.GetTourIndex(1, 99, onGetIndexComplete, onGetIndexFailed);        
}

function showTourIndex(sect, cat){
    updateStats("Favorites");
    function onGetTourFailed() {
        alert("Get Guide Pages Failed.");
    }

    function onGetTourComplete(result) {
        bookPages.load_pages(result,0);
        bookPages._show_page(0);
        this._bClickCover=false;
    }            

    PageService.GetHTMLFramePage(0, docDomain + "/html/tour_index.htm", onGetTourComplete, onGetTourFailed);
}

function showPMIndex(){
    updateStats("Placemarks");
    closeTourWin();
    function onGetLocFailed() {
        alert("Get Guide Pages Failed.");
    }

    function onGetLocComplete(result) {
        bookPages.load_pages(result,0);
        bookPages._show_page(0);
        this._bClickCover=false;
    }            

    PageService.GetHTMLFramePage(locIndexStart, docDomain + "/html/pm_index.htm", onGetLocComplete, onGetLocFailed);
}

function showAVPMIndex(){
    updateStats("Special");
    closeTourWin();
    function onGetLocFailed() {
        alert("Get Guide Pages Failed.");
    }

    function onGetLocComplete(result) {
        bookPages.load_pages(result,0);
        bookPages._show_page(0);
        this._bClickCover=false;
    }            

    PageService.GetHTMLFramePage(locIndexStart, docDomain + "/html/av_pm_index.htm", onGetLocComplete, onGetLocFailed);
}

function getInfoContent() {
    function onGetInfoComplete(result) {
        rotInfo.load(result);
        infoRotatorLoad();
    }
    
    function onGetInfoFailed(error) {
        alert(error.get_message());
    }
    PageService.GetInfoContent("OnScene", onGetInfoComplete, onGetInfoFailed);

}

function getTotdHTML(start){
    if ( start === undefined ){
        start = 0;
    }
    closeTourWin();
    function onGetTotdComplete(result) {
       showTOTD(result,start);
    }
    
    function onGetTotdFailed(error) {
        alert(error.get_message());
    }
        
    PageService.GetHTMLPg(docDomain + "/html/totd.htm", onGetTotdComplete, onGetTotdFailed);
}

function updateAccessCounter(){
   // Get the current access count
   var accessCount=getCookie("AccessCount");
   if ( accessCount === null ) { accessCount=0; }
   ++accessCount;
   if ( accessCount >= MAX_ACCESS ) { return false; }
   setCookie("AccessCount", accessCount, 366*DAYS, "/", "", "" );
   return true;
}

function getPM( id ){
    closeTourWin();
    
    // If an error in placemark data retrieval
    function onGetPMFailed(result) {
        alert("GE get Placemark Error: " + result.get_message());
    }

    // Success, show the placemark
    function onGetPMComplete(result) {
        // Close pop-up windows
        closeAllPops();
    
        showPM( result );
    }
    
    if ( !isNaN(parseInt(id,10)) )
    {
        id=parseInt(id,10);
        if ( id < 1 ) 
        { 
            return;
        }
        else
        {
            
        }
    }
    
    // If user not logged in then update access counter
    var bContinue=true;
    if ( !isUserLoggedIn() ) {
        bContinue=updateAccessCounter();
    }
              
    // TODO: Everyone gets through
    bContinue=true;
          
    // Get the placemark data from the GE database
    if ( bContinue )
    {
        if (typeof id === 'string') 
        {
            PageService.GEGetPlacemarkByTitle(id, onGetPMComplete, onGetPMFailed);
        }
        else 
        {
            PageService.GEGetPlacemarkById(id, onGetPMComplete, onGetPMFailed);
        }
    }
    else
    { 
        userLogon(id);
        return; 
    }          
}

function getTour( id ){
    
    // If an error in placemark data retrieval
    function onGetTourFailed(result) {
        alert("Get Tour Error: " + result.get_message());
    }

    // Success, show the placemark
    function onGetTourComplete(result) {
        // Close pop-up windows
        closeAllPops();   
        showTour( result );
    }
    
    if ( !isNaN(parseInt(id,10)) )
    {
        id=parseInt(id,10);
        if ( id < 1 ) 
        { 
            return;
        }
        else
        {
            
        }
    }
    
    // If user not logged in then update access counter
    var bContinue=true;
    if ( !isUserLoggedIn() ) {
        bContinue=updateAccessCounter();
    }
                    
    // Get the placemark data from the GE database
    if ( bContinue )
    {
       PageService.GetCourseById(id, onGetTourComplete, onGetTourFailed);
    }
    else
    { 
        userLogon(0);
        return; 
    }          
}

function VEConvert( data ){
    // Add a VE pm properties
    data.VEPitch=getVEPitch( data.Pitch );
    data.VEAltitude=getVEAltitude( data.Pitch, data.Range, data.VEPitch ) * GEVE_ALT_CONST;
//            alert( "Convert GoogleEarth Range=" + data.Range + " Pitch= " + data.Pitch + 
//                "\nTO Virtual Earth Altitude=" + data.Altitude3D + " Pitch= " + data.Pitch3D );
    
    return data;
}


function getVEAltitude( gePitch, geRange, vePitch ){
   var geAlt=geRange/Math.sin(RADS * (90.0-gePitch));
   var veAlt=geAlt * Math.sin(RADS * -vePitch);
   return Math.abs(veAlt);
}

function getGERange( veAlt, vePitch ){
   var geRange=veAlt * Math.sin(RADS * vePitch)/GEVE_ALT_CONST;
   return Math.abs(geRange);
}

function getVEPitch( angle ){
    angle=90.0-angle;
    for ( var i=0; i< 10; ++i )
    {
        if ( angle <= (i * 10) ) {
            if ( i > 1 && i < 9)
            {
                angle -= lookupAng[i]-(((i*10)-angle)*0.1);
            }
            break;
        }
    }
    return -angle;
}

function getGEPitch( angle ){
    angle=-angle;
    for ( var i=0; i< 10; ++i )
    {
        if ( angle <= (i * 10) ) {
            if ( i > 1 && i < 9)
            {
                 angle += lookupAng[i]-(((i*10)-angle)*0.1);
            }
            break;
        }
    }
    return 90.0-angle;
}

function showPM(pm) {
    // Mac Hack
    if (AppMode.OS == 'Mac') {
        FixGE = GEFix = true;
        useVE = FixVE = VEFix = false;
        useMap = 'GEMap';
        
        // Show the nav controls if hidden
        map = $find(useMap);
        if (map._bControls) { map.toggle_controls(); }

        var pmArray = [];
        pmArray[0] = pm;

        map.set_data(pmArray);
        closeTotd();
        return;
        
    }
    
//    useVE = true;    
    var useMap=(useVE?"VEMap":"GEMap");
    var map=null;
        
    // Show on the right globe
    if (GEFix) {
        if ( AppMode.GE.Mode == OnScene.Mode3D )
        {
            useMap='GEMap';
        }
        else
        {
            useMap='GEMap2D';
        }
    }
    else if (VEFix) 
    {
        useMap='VEMap';
    }
    else if (pm.VE)
    {
        if ( AppMode.VE.Available )
        {
            useMap='VEMap';
        }
        else
        {
            useMap='GEMap';
        }               
    }
    else if (!pm.VE)
    {
        if ( AppMode.GE.Available )
        {
            if ( AppMode.GE.Mode == OnScene.Mode3D )
            {
                useMap='GEMap';
            }
            else
            {
                useMap='GEMap2D';
            }
        }
        else
        {
            useMap='VEMap';
        }
    }
                
    // Check that we've got the right globe
    if ( (useMap === 'GEMap' && useVE) || (useMap === 'GEMap2D' && useVE) || (useMap === 'VEMap' && !useVE) ) { swapGlobes(); }
    
    // Convert VE data if that's what we have
    if ( useMap === 'VEMap' ) { pm=VEConvert( pm ); }
    
    // Show the nav controls if hidden
    map=$find(useMap);
    if ( map._bControls ) { map.toggle_controls(); }

    var pmArray=[];
    pmArray[0]=pm;
  
    map.set_data(pmArray);
    closeTotd();
}

function showTour(course) {

    function onGetTourPlacemarksFailed() {
        alert("Get Tour Placemarks Failed.");
    }

    function onGetTourPlacemarksComplete(result) {
        Tour = CTour;
        Tour.init(course, result);
    }            

    PageService.GetTourPlacemarks( course.id, onGetTourPlacemarksComplete, onGetTourPlacemarksFailed);
}

function showTourController(course)
{    
    var center="";
    if ( tourWin !== null )
    {
        if ( !tourWin.isClosed )
        {
            return;
        }
    }
    var vScroll=Geometry.getVerticalScroll();
    var h=20;  
    var w=328;
    var pos=findPos($get('leftmap'));
    var left=pos.left+550-w;
    var top=pos.top + 8;
    var style='width='+w+'px,height='+h+'px,left=' + left + 'px,top=' + top + 'px,resize=0,scrolling=0,detail=0,controls=0,color=#FF0000';
    tourWin=popupDiv.open('tourWin', 'iframe', 'html/tour.htm', '', style );
}

function showTourHelp()
{
    var center="";
    if ( tourHelpWin !== null )
    {
        if ( !tourHelpWin.isClosed )
        {
            return;
        }
    }
    closeAllPops();
    var vScroll=Geometry.getVerticalScroll();
    var h=216;  
    var w=386;
    var html="<img src='images/tour_help.jpg' border='0' />";
    var style='width='+w+'px,height='+h+'px,center=1,resize=0,scrolling=0,detail=0,controls=1,color=navy';
    tourHelpWin=popupDiv.open('tourHelpWin', 'inline', html, '', style );
}


function tourEnded(){
    function endNotify()
    {
        notifyWin.close();
    }

    var w=76,h=76;    
    var html="<div style='color:aqua;height:70px;width:70px;background:black;padding: 4px 0 2px 0;'><center><img src='images/earth-06-june.gif' border='0' align='center' /><br/><div style='color:#10BDFF;font:bold 10pt/1em arial,helvetica,sans-serif;margin:10px 0 0 0;'>THE END</div></center></div>";
    var style='width='+w+'px,height='+h+'px,center=1,resize=0,scrolling=0,detail=0,controls=0,color=black';
    notifyWin=popupDiv.open('notifyWin', 'inline', html, '', style );
    
    setTimeout( endNotify, 7500 );
}

function closeTourWin()
{
    if ( tourWin !== null )
    {
        if ( !tourWin.isClosed )
        {
            tourWin.close();
        }
    }
    
    if ( Tour !== null && Tour._play )
    {
        Tour.stop();
    }
}

function loadToc(){
    updateStats("Contents");
    closeTourWin();
    function onGetTocFailed() {
        alert("Get TOC Pages Failed.");
    }

    function onGetTocComplete(result) {
        bookPages.load_pages(result,0);
        bookPages._show_page(0);
        this._bClickCover=false;
    }
    PageService.GetBookPages(0, tocPages, tocStart, onGetTocComplete, onGetTocFailed);
}

function loadTocDiv(){
    var html=tocDiv();

    function onGetLoadTocFailed(result) {
        alert("Load TOC Div Failed");
    }

    function onGetLoadTocComplete(result) {
    }            
    PageService.LoadToc(99, html, onGetLoadTocComplete, onGetLoadTocFailed);
}

function returnToBook(pageShow){
    closeTourWin();
    
    var me=this;
    this.page=0 ;
    if ( pageShow !== undefined ) { this.page=pageShow; }
    
    function onRTBFailed() {
        alert("Get Book Pages Failed.");
    }

    function onRTBComplete(result) {
        bookPages.load_pages(result,me.page);
        bookPages._show_page(me.page);
    }            
    PageService.GetBookPages(bookStart, innerPages, innerStart, onRTBComplete, onRTBFailed);
}

function onClick_TourAdd()
{
    var w=525, h=570;      
    var style='width='+w+'px,height='+h+'px,left=0px,top=0px,center=1,resize=0,scrolling=0,detail=0,controls=1,color=#000066';
    courseWin=popupDiv.open('courseWin', 'iframe', 'html/courses.htm', 'Add Path', style );
}

function findMap()
{
    if ( useVE )
    {
        return $find('VEMap');
    }
    else
    {
        if ( AppMode.GE.Mode == OnScene.Mode2D )
        {
            return $find('GEMap2D');
        }
        return $find('GEMap');
    }
    
}

function findGEMap()
{
    if ( AppMode.GE.Mode == OnScene.Mode2D )
    {
        return $find('GEMap2D');
    }
    else
    {
        return $find('GEMap');
    }
}
function onClick_Swap(){    
    var bContinue=true;
    if ( VEFix || GEFix ) { bContinue=false; } // Forcing VE or GE usage?
    var globe=findMap(); // Get the current globe
    if (!globe.get_isInitialized()) { bContinue=false; } // Must be initialized
    
    // Check that we can switch to the opposite globe
    if ( useVE )
    {
        if ( AppMode.GE.Mode == OnScene.Mode3D )
        {
            if ( ge === null )
            {
                bContinue = false;
            }
        }
        else
        {
            if ( $find('GEMap2D').map === null )
            {
                bContinue = false;
            }
        }
    }
    else
    {
        if ( $find('VEMap')._instance === null )
        {
                bContinue = false;            
        }
    }
    
    if ( !bContinue )
    {
        
        alert( T_noSwap + (useVE?'Goggle':'Virtual') + " Earth." );
        return;
    }
    
    var pm=globe._pm;    
    if ( pm === null || pm === undefined )
    {
        // No PM, just swap the globes
        swapGlobes();    
    }    
    else
    {       
        // PM clicked. Show the PM from the other globe
        var saveVE=pm.VE;
        pm.VE=!useVE;
        showPM(pm);
        pm.VE=saveVE;
    }
}

function initOptions(bLogon)
{
    if ( bLogon === undefined ) { bLogon=true; }
    var usn=getUserInfo().Userid;
    if ( usn === 'Guest' || usn === null || usn === undefined || usn === '') { usn="default"; }
    
    function onOptionsComplete(options) {
        Options=options;
        if ( bLogon ) {
            setGEOptions(Options);
            setVEOptions(Options);
        }
        setCookie("GEStartUp", Options.GEStartUp,DAYS,"/","","");
    }
    
    function onOptionsFailed() {
        alert("Options retrieval failed");
    }
    PageService.GetUserOptions( usn, onOptionsComplete, onOptionsFailed);
}

function onClick_Options()
{
    var usn=getUserInfo().Userid;
    if ( usn === 'Guest' || usn === null || usn === undefined || usn === '' ){
        alert("You must be logged-in as a user to set OnScene options.");
        return;
    }
    
    function onOptionsComplete(options) {
        Options=options;
        getOptionsDescriptions();
    }
    
    function onOptionsFailed() {
        alert("Options retrieval failed");
    }
    PageService.GetUserOptions( usn, onOptionsComplete, onOptionsFailed);
}

function getOptionsDescriptions()
{    
    function onGetComplete(descriptions) {
        eval("Descriptions=" + descriptions );
        displayOptions();
    }
    
    function onGetFailed() {
        alert("Options descriptions retrieval failed");
    }
    PageService.GetOptionsDescriptions( onGetComplete, onGetFailed);

}

function saveUserOptions( data, names )
{
    function onOptionsComplete(result) {
        alert( "Your options have been saved.");
    }
    
    function onOptionsFailed() {
        alert("Options saving failed.");
    }
    PageService.SaveUserOptions(getUserInfo().Userid , names, data, onOptionsComplete, onOptionsFailed);

}

function displayOptions()
{
    var w=400, h=440;      
    var style='width='+w+'px,height='+h+'px,left=0px,top=0px,center=1,resize=0,scrolling=0,detail=0,controls=1,color=#000066';
    optionsWin=popupDiv.open('optionsWin', 'iframe', 'html/options.htm', 'OnScene Options', style );
}

function convertToBoolean( value )
{
    if ( value === null || value === '' ) { return false; }
    if ( value.toString().toLowerCase() === 'true' ) { return true; }
    if ( value.toString().toLowerCase() === 'false' ) { return false; }
    return false;
}

function setGEOptions( options )
{
    Options=options;
    var map=findGEMap();
    if ( map !== null ) { map._set_options(Options); }
}

function setVEOptions( options )
{
    var map=$find('VEMap'), bSwapBack=false;
    if ( options === null || map === null ) { return; }
    map._set_options(options);
    
    if ( map._dashboardSize != options.VEDashSize ){
        map._dashboardSize=parseInt(options.VEDashSize,10);
        setCookie("dashSize", options.VEDashSize, 10000*DAYS, "/", "", "" );
        if ( !useVE ) {
            swapGlobes();
            bSwapBack=true;
        }
        map.initialize();
        if (bSwapBack) { swapGlobes(); }
    }
}

function onClick_Register(){
    var msg="After pressing OK, you will be taken to a registration\n";
    msg +=    "screen. When you have completed your registration please\n";
    msg +=    "return to this screen and log-in to OnScene.\n\nThank You.";
    msg = "Registering to use OnScene is not necessary at this time.";
    alert(msg);
    return;
    location.href="http://www.clydeford.com/index.php?option=com_user&task=register";
}

function onClick_Login(){

    var msg="Logging-in/out to use OnScene is not necessary at this time.";
    alert(msg);
    return;
    if ( isUserLoggedIn() )
    {
        deleteCookie("LoggedIn","","");
        location.href="http://www.clydeford.com/index.php";
    }
    else
    {
        userLogon(0);
    }
}

function userLogon(id){
    // Pop-up user logon
    var w=360, h=375;      
    var style='width='+w+'px,height='+h+'px,left=0px,top=0px,center=1,resize=0,scrolling=0,detail=0,controls=1,color=#0000FF';  
    loginWin=popupDiv.open('loginWin', 'iframe', docDomain + '/html/login.htm?id=' + id, 'Member Log-in', style );       
}
        
function processLogon( usn, pwd, rem, id ){

    function onLogonComplete(result) {
        function logonEnded()
        {
            loginWin.close();
        }
        
        if ( result !== "" ){
            setCookie("LoggedIn",result, 20*MINS, "/", "", "" );
            var msg="Thank you for logging in.";            
            initOptions(true);
            setUserInfo();
            window.frames["_iframe-loginWin"].document.getElementById('loginBtn').innerHTML = 
                "<center style='color: red; font: bold 12pt/1em arial,helvetica,sans-serif'><br />" + msg + "</center>";
            setTimeout( logonEnded, 3000 );                
            if ( rem ){
               setCookie("RememberMe", result, 366*100*DAYS, "/", "", "" );
             }
            else {
               deleteCookie("RememberMe","","");
            }
            getPM(id);
        }
        else 
        {
            loginWin.close();
            alert("Your logon falied. Please check your username\nand password, then try again.");
        }
    }
    
    function onLogonFailed() {
        loginWin.close();
        alert("Your logon falied. Please check your username\nand password, then try again.");
    }
    
    PageService.UserLogon( usn, pwd, onLogonComplete, onLogonFailed);
}

function onClick_PlacemarkAdd(){
    var w=450, h=480;      
    var style='width='+w+'px,height='+h+'px,left=0px,top=0px,center=1,resize=0,scrolling=1,detail=0,controls=1,color=#000066';
    placemarkWin=popupDiv.open('placemarkWin', 'iframe', docDomain + '/php/placemark.php', 'Add Placemark', style );
}

function onClick_PathAdd(){

    var w=450, h=444;      
    var style='width='+w+'px,height='+h+'px,left=0px,top=0px,center=1,resize=0,scrolling=0,detail=0,controls=1,color=#000066';
    pathWin=popupDiv.open('pathWin', 'iframe', 'html/path.htm', 'Add Path', style );
}

function onClick_PolyAdd(){

    var w=450, h=460;      
    var style='width='+w+'px,height='+h+'px,left=0px,top=0px,center=1,resize=0,scrolling=0,detail=0,controls=1,color=#000066';
    polyWin=popupDiv.open('polyWin', 'iframe', 'html/poly.htm', 'Add Polygon', style );
}

function GESavePlacemark( type, pmData, pmNames ){
    function SaveSuccess(result){    
        alert("Placemark data saved.");
    }

    function SaveFailed(result){    
        alert("FAILURE:\n\n"+result);
        //dumpProps ( result );
    }
    PageService.GESavePlacemark( type, pmData, pmNames, SaveSuccess, SaveFailed);

}

function GESaveShape( type, pathData, pathNames ){
    function SaveSuccess(result){    
        alert("Shape data saved.");
    }

    function SaveFailed(result){    
        alert("FAILURE:\n\n"+result);
        //dumpProps ( result );
    }
    PageService.GESaveShape( type, pathData, pathNames, SaveSuccess, SaveFailed);

}

function SaveCourse( type, courseData, courseNames, waypoints ){
    function SaveSuccess(result){    
        SaveWaypoints(result, waypoints);
    }

    function SaveFailed(result){    
        alert("FAILURE:\n\n"+result);
        //dumpProps ( result );
    }
    PageService.SaveCourse( type, courseData, courseNames, SaveSuccess, SaveFailed);
}

function SaveWaypoints( course_id, waypoints ){
    function SaveSuccess(result){    
        alert("Waypoint data saved.");
    }

    function SaveFailed(result){    
        alert("Waypoint save failure:\n\n"+result);
        //dumpProps ( result );
    }
    PageService.SaveWaypoints( course_id, waypoints, SaveSuccess, SaveFailed);
}

function getCurrentView(){   
    var longitude;
    var latitude;
    var altitude;
    var altitudeMode;
    var heading;
    var pitch;
    var currView={};
    var pm={};

    pm=findMap()._pm;    
    if ( pm === null )
    {
        pm={
            id              :   -1,
            AltitudeMode    :   1,
            Title           :   "",
            Description     :   "",
            InfoBoxWidth    :   150,
            InfoBoxHeight   :   300,
            IconURL         :   "",
            IconOffsetX     :   0,   
            IconOffsetY     :   0,   
            SectId          :   0,
            CatId           :   0,
            Audio           :   0,
            Video           :   0,
            Images          :   0,
            VE              :   0
        };
      }
    
    var lookAt=ge.getView().copyAsLookAt(pm.AltitudeMode);
    latitude=lookAt.getLatitude();
    longitude=lookAt.getLongitude();
    heading=lookAt.getHeading();
    altitude=lookAt.getAltitude();
    altitudeMode=lookAt.getAltitudeMode();
    range=lookAt.getRange();
    pitch=lookAt.getTilt();
    id=pm.id;
 
    currView={
        id              :   pm.id,
        Title           :   pm.Title,
        Description     :   pm.Description,
        InfoBoxWidth    :   pm.InfoBoxWidth,
        InfoBoxHeight   :   pm.InfoBoxHeight,
        Latitude        :   latitude,
        Longitude       :   longitude,
        Altitude        :   altitude,
        AltitudeMode    :   altitudeMode,
        Heading         :   heading,
        Pitch           :   pitch,
        Range           :   range,
        IconURL         :   pm.IconURL,
        IconOffsetX     :   pm.IconOffsetX,   
        IconOffsetY     :   pm.IconOffsetY,   
        SectId          :   pm.SectId,
        CatId           :   pm.CatId,
        Audio           :   pm.Audio,
        Video           :   pm.Video,
        Images          :   pm.Images,
        VE              :   pm.VE
    };
    
    return currView;
}

function deletePlacemark(){
    alert("Delete placemark");
}

function onClick_Help(){
    // Pop-up user logon
    var w=500, h=420;      
    var style='width='+w+'px,height='+h+'px,left=0px,top=0px,center=1,resize=0,scrolling=0,detail=0,controls=1,color=#0000FF';
    helpWin=popupDiv.open('helpWin', 'iframe', 'html/help.htm', 'Help', style );
}

function getEarthView(){
    var longitude=0;
    var latitude=0;
    var altitude=0;
    var altitudeMode=0;
    var heading=0;
    var pitch=0;
    var center=0;
    var range=0;    
    var view=null;

    if ( useVE ){
        var map=$find('VEMap')._instance;
        center=map.GetCenter();
        longitude=center.Longitude;
        latitude=center.Latitude;
        altitude=map.GetAltitude();
        heading=VEGetHeading(map);
        pitch=map.GetPitch();
        view={
               Longitude : longitude ,
              Latitude : latitude ,
              AltitudeVE : altitude ,
              AltitudeMode : 1,
              PitchVE : pitch,
              Heading : heading,
              Range : getGERange(altitude, pitch),
              Zoom : map.GetZoomLevel()
              };
    } else {
        if ( AppMode.GE.Mode == OnScene.Mode3D )
        {
            // Has the GE API had its first view?
            if ( $find('GEMap')._bInitView )
            {
                $find('GEMap').init_view();
            }
            var lookAt=ge.getView().copyAsLookAt(1);
            latitude=lookAt.getLatitude();
            longitude=lookAt.getLongitude();
            heading=lookAt.getHeading();
            altitude=lookAt.getAltitude();
            altitudeMode=lookAt.getAltitudeMode();
            range=lookAt.getRange();
            pitch=lookAt.getTilt();
            zoom=null;
        }
        else
        {
            var map=$find('GEMap2D').map;
            if ( map == null ) { return; }
            var center = map.getCenter();
            latitude = center.lat();
            longitude = center.lng();
            zoom = map.getZoom();
        }
        view={ Longitude : longitude ,
              Latitude : latitude ,
              Altitude : altitude,
              AltitudeMode : altitudeMode ,
              Pitch  : pitch ,
              Range : range,
              Heading : heading,
              Zoom : zoom
              };
    }              
    return view;
}

function VEGetHeading(map)
{
    if ( AppMode.VE.Mode == OnScene.Mode2D )
    {
        return 0;
    }
    var map3D=map.vemapcontrol.Get3DControl();
    var heading;
    var data=map3D.GetCameraViewpoint();
    eval(data);
    return heading;
}

function getSelectElement(table, attributes, conditions, keyField, valueField, callBack)
{
    function getSelectSuccess( select )
    {
        eval( callBack + "select);" );
    }
    
    function getSelectFailure()
    {
        alert('Selection element creation failed.');
    }
    window.parent.PageService.GetSelectionElement(table, attributes, conditions, keyField, valueField,
         getSelectSuccess, getSelectFailure);
        
}

function getPlacemarkFromDB(Id, callBack)
{
    function getPlacemarkSuccess( placemark )
    {
        eval( callBack + "(placemark);" );
    }
    
    function getPlacemarkFailure()
    {
        alert('Placemark retrieval error.');
    }
    window.parent.PageService.GEGetPlacemarkById(Id, getPlacemarkSuccess, getPlacemarkFailure);
        
}

function getPolyFromDB(shapeId, callBack)
{
    function getShapeSuccess( shape )
    {
        eval( callBack + "(shape);" );
    }
    
    function getShapeFailure()
    {
        alert('Shape retrieval error.');
    }
    window.parent.PageService.GEGetShapeById(shapeId, getShapeSuccess, getShapeFailure);
        
}

function getCourseFromDB(courseId, callBack)
{
    function getCourseSuccess( course )
    {
        getCourseWaypoints(course, callBack);
    }
    
    function getCourseFailure()
    {
        alert('Course retrieval error.');
    }
    window.parent.PageService.GetCourseById(courseId, getCourseSuccess, getCourseFailure);
        
}

function getCourseWaypoints(course, callBack)
{
    function getWPSuccess( waypoints )
    {
        eval( callBack + "(course, waypoints);" );
    }
    
    function getWPFailure()
    {
        alert('Waypoint retrieval error.');
    }
    window.parent.PageService.GetWPByCourseId(course.id, getWPSuccess, getWPFailure);        
}

function getCoordinateString(where, callBack)
{
    function getCoordsSuccess( coords )
    {
        eval( callBack + "(coords);" );
    }
    
    function getCoordsFailure()
    {
        alert('Coordinate retrieval error.');
    }
    window.parent.PageService.GetCourseCoords(where, getCoordsSuccess, getCoordsFailure);        
}

function loadFAQ(){    
    updateStats("FAQ");
    closeTourWin();
    // Pop-up the FAQ window
    var w=570, h=470;      
    var style = 'width='+w+'px,height='+h+'px,left=0px,top=0px,center=1,resize=0,scrolling=0,detail=0,controls=1,color=#0000FF';
    faqWin=popupDiv.open('faqWin', 'iframe', 'html/faq.htm', 'OnScene FAQ', style );       
}

function updateStats(item)
{
    function updateStatsSuccess( result )
    {
    }
    
    function updateStatsFailure()
    {
    }
    PageService.UpdateStats(item, updateStatsSuccess, updateStatsFailure);        
}

