// bottom.js: accessed by every page to chance color of tab, even home.html.
// bottom needs a few global vars such as ForumLink...(due to parallel loading, var set by home.html may not be seen...
// vars stored in index.html are accessed.
// v 1.6 goHome
// v 1.5 import from TEST mini with local oTop..
// v 1.4 forum redirect..
// v 1.3: move logout?
// working as of 5-31-10
var oTop = oGetTESTTopLocal(); //type Window, top page no matter who calls this
var iDEBUG = oTop.iDEBUG;
var bWEB = oTop.bWEB;
var  FORUMLINK = oTop.FORUMLINK; // does not work, picks up 'xxx' as oTop may not have been defined?
var  VIDEOLINK = oTop.VIDEOLINK;

//var SERVLETPATH = 'http://thermo.sdsu.edu/servlet';

var aiFlag=new Array();   //Associative Array used for coloring on click
aiFlag["home"]=0;
aiFlag["daemons"]=0;
aiFlag["rias"]=0;
aiFlag["tables"]=0;
aiFlag["map"]=0;
aiFlag["tutorial"]=0;
aiFlag["examples"]=0;
aiFlag["problems"]=0;
aiFlag["animations"]=0;
aiFlag["slides"]=0;
aiFlag["myAccount"]=0;
aiFlag["help"]=0;
aiFlag["blog"]=0;
aiFlag["logout"]=0;


var asTip=new Array();   //Associative Array
asTip["home"]= "Home page of TEST";
asTip["daemons"]="Systematic navigation to thermodynamic calculators";
asTip["rias"]="Simulation of thermal systems by rich internet apps. (RIA)";
asTip["tables"]="Traditional tables and charts in SI and English units.";
asTip["map"]="Jump to a daemon page";
asTip["tutorial"]="Hands-on instructions to get started with the daemons";
asTip["examples"]="Manual and TEST solutions of selected problems";
asTip["problems"]="Chapter-end problems";
asTip["animations"]="Illustrations of systems and fundamental concepts";
asTip["slides"]="Video instructions for daemons";
asTip["myAccount"]="Subscribe, order TEST-CD, download license file";
asTip["blog"]="Post a comment/question/answer";
asTip["logout"]="Click once to sign out from all parallel sessions";
asTip["release"]="Contact prof.bhattacharjee@gmail.com for a free academic site license";


//set the global vars during render
function setGlobals(){
    oTop = oGetTESTTopLocal(); //type Window, top page no matter who calls this
    iDEBUG = oTop.iDEBUG;
    bWEB = oTop.bWEB;
    VIDEOLINK = oTop.VIDEOLINK;
}
//get top window (thermofluids. local, vs test..),also in reg.js
function oGetTESTTopLocal(){
    //alert('top = ' +window.top.location +' parent= '+window.parent.location);
//    var bForward = (window.top != window.parent);
//    if(!bForward) return window.top;
//    else return window.top.frame[0]; // blocked by thermofluids domain...
    // the following logic moves up but never goes to thermofluids...
    var oTop = parent;
    while (oTop.frames[0].name !='main') oTop = oTop.parent;
    return oTop;
}

//forward to my account
function  handleToMyAccount(){

    // 0. try table cookie approach with 10...
    //alert('hi: ' +oTop.iACCOUNT);
    if(oTop.iACCOUNT == 10){
    // 0. test if local
        if(!oTop.bWEB){
            var oPopup = new PopupT('floatWindow');
            oPopup.alertFloat('Please logon to the Web edition of TEST at www.thermofluids.net and then click on this link.');
            return;
        }
        // 5. test if not logged in
        if(!oTop.bLOGIN){
            var oPopup = new PopupT('floatWindow');
            oPopup.alertFloat('You must be logged in before you can access your account. ');
            return;
        }
        // 5. test if not logged in
        if(oTop.bSiteLogin()){
            var oPopup = new PopupT('floatWindow');
            oPopup.alertFloat('You must be logged in to your personal account to access the \'myAccount\' page. ');
            return;
        }
        oTop.main.location = oTop.MYACCOUNTURL; // running myaccount.php from test or enthalpy..
        //oTop.main.location = 'myaccount.html';
        return;
    }




    // 0. legacy method..currently in production
    if(oTop.iACCOUNT == 5) oTop.main.location = 'myaccount.html'; //legacy

    // 15. change color
    changeClassName("myAccount");
}

//forward to forum
function  handleToForum(){
    // 0. test if local
    if(!oTop.bWEB){
        var oPopup = new PopupT('floatWindow');
        oPopup.alertFloat('The forum is accessible only online, and not from local installations. Please logon to the Web edition of TEST at www.thermofluids.net and try again.');
        return;
    }
    // 5. test if not logged in
    if(!oTop.bLOGIN){
        var oPopup = new PopupT('floatWindow');
        oPopup.alertFloat('You must login before you can access the forum. ');
        return;
    }
//    oTop.main.location = "http://thermo.sdsu.edu/testcenterdev/testhome/blog/MyBlog.html";
//    return;
    // 10. allow every host to link to FORUMLINK set in Global.js
    oTop.main.location = oTop.FORUMLINK;
    changeClassName("blog");
    return;

}

// draw the bottom taskbar
function renderTaskBar(){
    setGlobals();
   //while on web, oTop does not get updated info from home.html as they load parallel
    //alert('in bottom.js renderTaskBar'+     FORUMLINK+" "+oTop.FORUMLINK + " ");
    document.write(getTableHTML());
    //alert('in render bot: '+oTop.bLOGIN);
    //if not logged in or local, do not show logout.
    //alert(oTop.bWEB);
    if(!oTop.bLOGIN && oTop.bWEB){
        xRemoveClass($('logout'),'notSelected');
        xRemoveClass($('logout'),'logoutStyle');
        xAddClass($('logout'),'hide');
    }
    if(!oTop.bWEB){
        xRemoveClass($('logout'),'notSelected');
        xRemoveClass($('logout'),'logoutStyle');
        xAddClass($('logout'),'hide');
    }
}

    // draw the lgout button, called from Home.js
    function showLogout(){
      //alert('showing logout in bottom.js');
        if($('logout')){
            $('logout').style.display = 'inline';
            xAddClass($('logout'),'logoutStyle');
            xRemoveClass($('logout'),'hide');
            //alert('set classes');
        }
    }

    //logout accessible from all pages..even called from Home.js
    function handleLogout(){

        //construct inJson
        var sID = oTop.asCOOKIEITEM[6];//hardcode needed as reg.js is unknown at this point.
        var sCEXP = oTop.sSERVEREXP; //mysql time stamp..in server time
        var sInJSON = sInJSON = '{' + '"sID":"' + sID + '"' + ', "sCEXP":"' + sCEXP + '"' + '}';
        var oBlogSynch = new SynchronizerPHP("ajaxcodes/phpcurl/", oTop.PHPSERVLETPATH);
        oBlogSynch.standardUpdate(sInJSON, 'logout.php', this.logOutCallback, this);


        //removing (resetting) cookie, must be done at teh very end after logout call to remove server cookie.

        var oNow = new Date();
        var sCookieName = 'ThermoCookie';
        document.cookie = sCookieName+"="+oTop.GLOBALCOOKIEWDEFAULT + "; expires="+oNow.toGMTString()+"; path=/";
        //var sRead = document.cookie;
       // alert('cookie reset: '+sRead);

        oTop.tEXPIRATION = 0;
        oTop.bLOGIN = false;
        oTop.setGlobalVars(); // reset ram cookie to Mr. Guest

    }


    // callback after all the cookie arrive
    function  goHome() {
        //alert('in bottom');
        oTop.location = parent.location; //"home.html";
    }
    // callback after all the cookie arrive
    function  logOutCallback() {
        var args = $A(arguments);
        var oSynchronizer = args.shift(); // to nullify
        var sJSON = args.shift();  // all info comes back in it
        var oThis = args.shift();   // want this

        try{

            $('logout').style.display = 'none';
            var oRpatt = /\{.*\}/; //extract json from verbose return string
            var asJson = sJSON.match(oRpatt);
            if( asJson!=null && asJson.length == 1) sJSON = asJson[0];
            var oInData = eval("(" + sJSON + ")"); // object containing form data

            //alert('call back after ajax logout in bot'+sJSON+' '+oInData.iError);
            oTop.bLOGIN = false;
            // need to reset cookie...
            oTop.main.location = "home.html";
            }
            catch(err){
                oSynchronizer = null;
                alert("The operation could not be completed; please check your network connection and try again.");
                return;
            }
            oSynchronizer = null;
        return;
    }

// draw the bottom taskbar
function getTableHTML(){
    var s = '<div class="borders">';
    s += '<table valign="bottom"  height="100%"  width=100% bordercolor = "red"  border="0" cellpadding="0" cellspacing="0">';
    s += '<tr>';
    s += '<td valign="center" ><a id="home" class="notSelected" onclick=changeClassName("home"); onmouseover=mouseOver("home"); onmouseout=mouseout("home"); href="home.html" target="main" > Home&nbsp; </a></td>';
    s += '<td  valign="center" ><a id="map" class="notSelected" onclick=changeClassName("map") onmouseover=mouseOver("map") onmouseout=mouseout("map") href="Test/help/navigation.html" target="main"> Map&nbsp; </a></td>';
    s += '<td valign="center" ><a id="daemons" class="notSelected" onclick=changeClassName("daemons"); onmouseover=mouseOver("daemons"); onmouseout=mouseout("daemons"); href="Test/solve/solve.html" target="main"> Daemons&nbsp; </a></td>';
    s += '<td valign="center" ><a id="rias" class="notSelected" onclick=changeClassName("rias"); onmouseover=mouseOver("rias"); onmouseout=mouseout("rias"); href="Test/rias/rias.html" target="main"> RIAs&nbsp; </a></td>';
    s += '<td valign="center"><a id="tables" class="notSelected" onclick=changeClassName("tables") onmouseover=mouseOver("tables") onmouseout=mouseout("tables") href="Test/solve/basics/tables/tables.html" target="main"> Tables&nbsp; </a></td>';
    s += '<td valign="center"><a id="animations" class="notSelected" onclick=changeClassName("animations") onmouseover=mouseOver("animations") onmouseout=mouseout("animations") href="vtAnimations/index.html" target="main"> Animations&nbsp; </a></td>';
    s += '<td valign="center"><a id="problems" class="notSelected" onclick=changeClassName("problems") onmouseover=mouseOver("problems") onmouseout=mouseout("problems") href="Test/problems/problemsIndex.html" target="main"> Problems&nbsp; </a></td>';
    s += '<td valign="center"><a id="examples" class="notSelected" onclick=changeClassName("examples") onmouseover=mouseOver("examples") onmouseout=mouseout("examples") href="Test/problems/problemsIndexEx.html" target="main"> Examples&nbsp; </a></td>';
    s += '<td valign="center"><a id="tutorial" class="notSelected" onclick=changeClassName("tutorial") onmouseover=mouseOver("tutorial") onmouseout=mouseout("tutorial") href="Test/intro/introcontrols/introIndex.html" target="main"> Tutorial&nbsp; </a></td>';
    s += '<td valign="center"><a id="myAccount" class="notSelected" onclick=handleToMyAccount() onmouseover=mouseOver("myAccount") onmouseout=mouseout("myAccount")> <i>my</i>Account&nbsp;&nbsp; </a></td>';
    s += '<td valign="center"><a id="blog" class="notSelected" onclick=handleToForum() onmouseover=mouseOver("blog") onmouseout=mouseout("blog")> Forum&nbsp; </a></td>';
    //s += '<td valign="center"><a id="blog" class="notSelected" onclick=changeClassName("blog") onmouseover=mouseOver("blog") onmouseout=mouseout("blog") href="'+ oTop.FORUMLINK + '" target="main"> Forum&nbsp; </a></td>';
    s += '<td valign="center"><a id="logout" class="notSelected logoutStyle" onclick=handleLogout() onmouseover=mouseOver("logout") onmouseout=mouseout("logout") > Logout&nbsp;&nbsp; </a></td>';
    s += '<td valign="center" ><a id="release" class="notSelected" onclick=changeClassName("release") onmouseover=mouseOver("release") onmouseout=mouseout("release") href="help.html" target="main"> <nobr>' + parent.sVERSION + '; Copyright: Prof. Subrata Bhattacharjee</nobr></a></td>';

    s += '</tr>';
    s += '</table></div>';
    //alert('myAccount: '+oTop.tomyaccountURL);
    return s;


}

  //alert('in changename with '+sModule
//change background color of a module on task bar to green, module nams are keys at tht top, not what is in the test task bar.
function  changeClassName(sModuleName, sLevel){

  //alert('in changename with '+sModuleName+' '+sLevel);
    if(!sLevel) sLevel = 1;
    for (var sName in aiFlag) aiFlag[sName]=0;
    aiFlag[sModuleName]=1;
    var oDoc, oModule;
    for (var sName2 in aiFlag){
        if (sLevel==1 && parent.bottomPanel)oDoc = parent.bottomPanel.document;
        else if (sLevel==2 && parent.parent.bottomPanel) oDoc = parent.parent.bottomPanel.document;
        else if (sLevel==0)oDoc = document;
        if(oDoc){
          oModule = oDoc.getElementById(sName2);
          if(oModule){
            //if(sName2 != 'logout') Module.className="notSelected";
            if(sName2 != 'logout') oModule.className="notSelected";
            if(aiFlag[sName2]==1) oModule.className="selected";
          }
        }
    }
    //alert('in change: '+sModuleName+' '+aiFlag[sModuleName]);


}



//change background color and tooltip
function mouseOver(sModuleName){
    //document.write(aiFlag[sModuleName]);
    document.getElementById(sModuleName).className="hover";
    var sTip = this.asTip[sModuleName];
    Tip(sTip, OFFSETY, -4, OFFSETX, 20, DELAY, 1000);
}

//mouse has moved out of a bottom block
function mouseout(sModuleName){
    UnTip('');
    //alert('muse out: '+sModuleName+' '+aiFlag[sModuleName]);
    if(aiFlag[sModuleName]==0){
        document.getElementById(sModuleName).className="notSelected";
        if(sModuleName == 'logout') document.getElementById(sModuleName).className="logoutStyle";
    }
    else
        document.getElementById(sModuleName).className="selected";
}

//instead of using this function use changeClassName directly.
// this is called by most pages to change the hightlight of the selected item on task bar.
function highlight(){
    if(!parent.main) return;
    var ref = parent.main.location.href;
    //alert('in  hightlishg refrence'+ref);
    //alert(document.getElementsByTagName(moduleNames[1]).style);
    if ( ref.indexOf("/myaccount.html")!= -1){
        changeClassName("myAccount");
        return ;
    }
    if ( ref.indexOf("/solve/")!= -1){
        changeClassName("daemons");
        return ;
    }
    if ( ref.indexOf("/rias/")!= -1){
        changeClassName("rias");
        return ;
    }
    if ( ref.indexOf("/intro/")!= -1){
        changeClassName("tutorial");
        return ;
    }

    if ( ref.indexOf("/problems/")!= -1&& ref.indexOf("Ex.html")!= -1){
        changeClassName("examples");
        return ;
    }
    if ( ref.indexOf("/problems/")!= -1){
        changeClassName("problems");
        return ;
    }
    if ( ref.indexOf("/vtAnimations/")!= -1){
        changeClassName("animations");
        return ;
    }
    if ( ref.indexOf("/visualtour/")!= -1){
        changeClassName("slides");
        return ;
    }
    if ( (ref.indexOf("help.html")!= -1)
        || (ref.indexOf("faq")!= -1)){
        //top.bottomPanel.changeIt(9);
        changeClassName("help");
        return ;
    }
    if ( ref.indexOf("navigation")!= -1){
        //top.bottomPanel.changeIt(2);
        changeClassName("map");
        return ;
    }
    if ( ref.indexOf("/testhome/")!= -1){
        changeClassName("home");
        return ;
    }
}


  // display a specific chapter from the visual tour (called from tutorial toc.html)
  function displayClip(sChapter){
      //alert('display clip'+ getActualMedia()+ ' '+iDEBUG);
      if (oTop.sMEDIA == 'LOCAL' && oTop.iDEBUG==0){
      //if (getActualMedia()=='LOCAL'){
          alert('Please switch to www.thermofluids.net to access the video clips.');
          return;
      }
      changeClassName('slides',2);
      var sLocation = '../../visualtour/clips/'+sChapter+'/index.html';
      window.parent.parent.frames[0].location.replace(sLocation);
  }

//static way to write stuff in a header...bottom.html calls it from the head... a dynamic way
function loadCss(){
    document.write('<link href="ajaxcodes/login/global.css" rel="stylesheet" type="text/css">');
    if (parent.bIE) {
        document.write('<link rel="stylesheet" href="jscripts/styleSheetBottomIE.css" type="text/css">');
    }
    else{
        document.write('<link rel="stylesheet" href="jscripts/styleSheetBottomM.css" type="text/css">');
    }
}

// the dynamic way also require an url, not already loaded codes.
function dhtmlLoadScript(url){
   var e = document.createElement("script");
   e.src = url;
   e.type="text/javascript";
   document.getElementsByTagName("head")[0].appendChild(e);
}


// this alert can be called from any page, mostly by applets through pageMaker.
function alertAppletBottom(s){
    var oPopup = new PopupT('floatWindow');
    oPopup.alertApplet(s);
}