// Global,js from index,  Home.js in home, bottom.js in bottom, but Reg.js. everywhere...
// 10-12-11: banner convert to div
// 10-11-11: change background to match taskbar at the banner.
// v 1.7 canada slight modification..
//  v 1.6 global routine for email checking?
//  v 1.5 introduce library function trim (used in Home.js) v 1.4  mansolproblems...


//0. connect to top page from anywhere (top will not work due to permission issue from thermofluids.net
var oTop = oGetTESTTop(); //type Window, top page no matter who calls this, most imp. var in this page

// 0.5. conv. variables, repeated in home.js and other places..
var saluteIndex=0,firstNameIndex=1, lastNameIndex=2,accessIndex=3,expiryIndex=4, mediaIndex=5,emailIndex=6,  jumbleIndex=7; // what is number 8 then?

//var absRegPath="http://energy.sdsu.edu/registrationdev/" // used in inviting people in home.html;

//  0.10 used in problems..
var mansolProbsURL = oTop.MANSOLPROBSURL; //used by frameDisplay.js
//var myaccountURL = oTop.MYACCOUNTURL;

//10. get some globals from index so that all pages can share .
var actualMedia=oTop.sMEDIA;
var ThermoCookie = oTop.GLOBALCOOKIE; //used only in SynchT.js
var ThermoCookieList = oTop.asCOOKIEITEM;
var iDEBUG = oTop.iDEBUG;
var footnote;
var bIE = oTop.bIE
var bWEB = oTop.bWEB;
var iDEBUG = oTop.iDEBUG; //  still used in places...
//
var SERVLETPATH = oTop.SERVLETPATH;  // used by myBlog...
//var FORUMLINK = oTop.FORUMLINK;
//var VIDEOLINK = oTop.VIDEOLINK;


//method to get oTop =  reference to index.html, keeping in mind that thermofluids.net may put index in a frame.
function oGetTESTTop(){
    var oTop = parent;
    while (oTop.frames[0].name !='main') oTop = oTop.parent;
    return oTop;
}

 //used in frameDisplay.js
 function  sGetMansolProbsURL(){
     //return registrationURL + "mansolProbs.php";
     return mansolProbsURL;
 }
//
//functions to get cookie values.
function getName(){
    var name=oTop.asCOOKIEITEM[saluteIndex]+" "+oTop.asCOOKIEITEM[lastNameIndex];
    return name;
}

//
function getEmail(){
    return oTop.asCOOKIEITEM[emailIndex];
}

//0: expired, no licnse, 5: guest: 10: academic: 15: professional
function getAccessLevel(){
    return oTop.asCOOKIEITEM[accessIndex];
}

// used by frameDisplay.js
function getActualMedia() {
    if(oTop.bWEB) return "WEB";
    else return "LOCAL";
}

//detect if dev edition or not??
function getDynamicFlag(folderName) { // decides if the current URL contains folderName.
    var flag="";
    return flag;
}

//number of days left for license expiration, get from cookie.
function getExpiryDays() {
    var expiryDate = new Date(oTop.asCOOKIEITEM[expiryIndex] * 1000);
    var today = new Date();
    var diff=((expiryDate.getTime()-today.getTime())/(24*3600*1000)).toFixed(0);
    return diff;
}


// moved to superform..returns formatted date
function getExpiryDate() {
    var expiryDate = new Date(oTop.asCOOKIEITEM[expiryIndex] * 1000);
    return expiryDate.toDateString();
}

//modernize: 5-1-10: a/c expired?
function getExpiryStatus() { //true means license has expired.
    //alert('in reg.js exp stat'+oTop.asCOOKIEITEM.length);
    var expiryDate = new Date(oTop.asCOOKIEITEM[expiryIndex] * 1000);
    var now = new Date
    return now.getTime() > expiryDate.getTime();  
}

function validUser(){
    return !(oTop.asCOOKIEITEM[accessIndex] == 0||getExpiryStatus());
}

//*********applet call with generated warning based on access level (expired account)
// web/local, and jumbletext. 
function getAppletTag(code,codebaseDepth,codebaseRel,width,height,browserColor) {
    var i = 0;  var codeDotStr="";
    while (i < codebaseDepth) { 
        codeDotStr=codeDotStr +"../"; i=i+1;
    }
    var codebase=codeDotStr+codebaseRel;
    var cipherText=oTop.asCOOKIEITEM[jumbleIndex]+":"+oTop.asCOOKIEITEM[8]; // what is in index 8?
    cipherText=oTop.asCOOKIEITEM[jumbleIndex];

//alert(cipherText);
    //*** necessary because of the delimeter being part of the string.
    //alert('jumbleIndex: '+ jumbleIndex+'jumble= '+oTop.asCOOKIEITEM[jumbleIndex]);
    var actualMedia = getActualMedia();
    var tag = new String(" code=\"" + code + "\" codebase=" + codebase + " width=" + width + " height=" + height + "><param name=BrowserColor value="+browserColor+"><param name=warning value="+oTop.asCOOKIEITEM[accessIndex]+"><param name=actualMedia value="+actualMedia+"><param name=jumble value=\"" + cipherText + "\">");

    return(tag);
}

//*********completes the applet tag. used by most  calling pages --maybe not used anymore, replaced by writeAppletTag
function openApplet(code,codebaseDepth,codebaseRel,width,height,browserColor) {
    var tag = getAppletTag(code,codebaseDepth,codebaseRel,width,height,browserColor);
    tag = "<applet"+ tag + "</applet>";
    document.write(tag);
}
//**********fluidType was added as a parameter later.--maybe not used anymore, replaced by writeAppletTag
function openAppletFluidModel(code,codebaseDepth,codebaseRel,width,height,browserColor,fluidType) {
    var tag = getAppletTag(code,codebaseDepth,codebaseRel,width,height,browserColor);
    tag = "<applet archive=openSL.jar"+ tag + "<param name=fluidtype value=" + fluidType + "></applet>";
    document.write(tag);
}
//**********Archive is being added, the latest call
function writeAppletTag(jarFile,code,codebaseDepth,codebaseRel,width,height,browserColor,fluidType) {
   // height = height-0+50; //mac problem...
    height = height-0;
    var tag = getAppletTag(code,codebaseDepth,codebaseRel,width,height,browserColor);
    tag = "<applet archive="+jarFile+ tag + "<param name=fluidtype value=" + fluidType + "></applet>";
        //alert("In jscript>registration>writeAppletTag(): tag is:" +tag);
    document.write(tag);
    //document.write('<iframe class="alertiframe">/<iframe>')
}

//**********same as writeAppletTag except for abs. url.
//writeAppletTag("CHEQSProject.jar","equilibrium/CsPoChemEqlDaemon.class",7,"daemons/states/chemEql","95%","510","88aa88","IG-GenMixModel");
function writeDirectAppletTag(jarFile,code,codebase,width,height,browserColor,fluidType) {
	
 

    var cipherText=oTop.asCOOKIEITEM[jumbleIndex]+":"+oTop.asCOOKIEITEM[8];
    cipherText=oTop.asCOOKIEITEM[jumbleIndex];
    //*** necessary because of the delimeter being part of the string.
  
    var tag = new String(" code=\"" + code + "\" codebase=" + codebase + " width=" + width + " height=" + height + "><param name=BrowserColor value="+browserColor+"><param name=warning value="+oTop.asCOOKIEITEM[accessIndex]+"><param name=actualMedia value="+actualMedia+"><param name=jumble value=\"" + cipherText + "\">");
	
    tag = "<applet archive="+jarFile+ tag + "<param name=fluidtype value=" + fluidType + "></applet>";
    document.write(tag);
}

//from inside applets
function alertPopup(n){ //for not logged,not activated, or expired account take them to home page.
    var i = 0;   var fileDotStr="";
    while (i < n) { 
        fileDotStr=fileDotStr +"../"; i=i+1;
    }
    var homeURL=fileDotStr+"index.html";
    if(!validUser()){
    //if(validUser()=="false"){
		
        //setTimeout("alert('Please log in (Web Edition) or activate your CD (Local Edition) to use this page. Clicking \"OK\" will take you to the home page, where you can log in, register, or obtain license file for activating your local installation. Creating an account takes only a minute or two, is free, and will give you complete access to TEST.\n\nTo check out what TEST is about without registering, go through the Tutorial. ')",15000);
        alert("You are seeing this message because of one of the following reasons: \n\n1. You are not logged in: If you don't have an account, you can create one in seconds and evaluate TEST for a month. Follow the 'Create Account' link from the home page. If you forgot your password, you can have it reset and sent to you by following the Forgot Password link from the home page. \n\n" +
            "2. Your account has expired: You can follow the myAccount link from the task bar to subscribe TEST. The academic version is quite affordable (costs less than 2 cups of coffee from a certain store). If you are an educator, just send a request to prof.bhattacharjee@gmail.com to get your license  upgraded.\n\n"+
            "3. You have not installed a license if you are running a locally installed version: If you have just installed TEST in your local drive, you need to download a license file for the daemons to work. Visit myAccount page to download your license file.\n\n"+
            "4. Your license has expired and has to be extended and downloaded again: Visit myAccount page, upgrade your license and download a new license file. \n\n"+
            "If you have already evaluated TEST for 30 days, we request that you consider some of the benefits of subscribing as opposed to creating another account. As a subscriber, any question you post in the Forum will be answered with priority. When you extend your license in the future, you will get significant discount. More importantly, you will feel good about supporting the TEST project as all proceeds from subscription go right back into continuously improving TEST.  ");
        //window.parent.location=homeURL;
        oTop.bottomPanel.goHome();
        //alertLocal("Please log in (Web Edition) or activate your CD (Local Edition) to use this page. Clicking \"OK\" will take you to the home page, where you can create an account in minutes and evaluate TEST for 30 days. \n\nTo check out what TEST is about without registering, go through the Tutorial. To obtain a permanent license, visit the myAccount page (linked from the task bar).");

    }
}

//the top banner with status etc. also copied to globalScriptsVT.js
function writeStatusBanner(depth) { //status line on top of each page
    var i = 0;   var dotStr="../";
    while (i < depth) {
        dotStr=dotStr +"../"; i=i+1;
    }

    var homeURL = dotStr + "home.html";
    var loginURLExpanded=dotStr+"index.html"; //takes you to home page.

    var userName=oTop.asCOOKIEITEM[saluteIndex]+" "+oTop.asCOOKIEITEM[lastNameIndex];

    //if(getExpiryStatus()=="true") oTop.asCOOKIEITEM[accessIndex]=0;
    if(getExpiryStatus()) oTop.asCOOKIEITEM[accessIndex]=0;
    switch(oTop.asCOOKIEITEM[accessIndex]) {
        case "0":
            classification = new String("Limited");
            break;
        case "5":
            classification = new String("Evaluation");
            break;
        case "10":
            classification = new String("Academic");
            break;
        case "15":
            classification = new String("Professional");
            break;
        default:
            classification = new String("Limited");
            break;
    }

	
    //var startBanner=new String('<table style = "margin-top: 0px;" width=100% border="0" cellpadding="2" cellspacing="0" bgcolor="aabbff"><tr>');
    var startBanner=new String('<table class = "topBanner" width=100% border="0" cellpadding="0" cellspacing="0" ><tr>');
    var idBanner =new String('<td width=240 align = "center"><font color="#000000" face="verdana" size="-2">Analyst: '+userName+' </font></td>');
    var accessBanner=new String('<td width=240 align = "center"><font color="#000000" face="verdana" size="-2">License: '+classification+' </font></td>');
    var expiryBanner;



    if(actualMedia=="LOCAL") mediaString=new String("TEST: Local");
    else mediaString=new String("TEST: Online");
    var mediaBanner=new String('<td width=110 align = "center"><font color="#000000" face="verdana" size="-2">'+mediaString+' </font></td>');

    var sUserCell = 'Analyst: '+userName;
    var sLicenseCell = 'License: '+classification;
    var sMediaCell = mediaString;
    var sUpdate = '', sExpiry = '';

    var updateBanner=new String("");
    if(oTop.asCOOKIEITEM[mediaIndex]=="WEB"){
        if(oTop.asCOOKIEITEM[accessIndex]=="0"){ //not logged in, no need for expiry banner.
            expiryBanner=new String("");
            updateBanner=new String('<td align = "center"><font color="#000000" face="verdana" size="-2">Please log in to use TEST effectively.</font></td>');
            sUpdate = 'Status: Not logged in (required for full access).';
            sExpiry = '';
        }
        else{ //logged out
            //expiryBanner=new String('<td><a href='+myaccountURLExpanded+' ><font color="#00aa00" face="verdana" size="-2">Renew License</a><font color="#5555ff" face="verdana" size="-2"> in '+(getExpiryDays()-1)+' days</font></font></td>');
            expiryBanner=new String('<td align = "center"><font color="#000000" face="verdana" size="-2"> Renew License in '+(getExpiryDays()-1)+' days </font></td>');
           //updateBanner=new String('<td><a  class="link" onclick = "handleLogout(\'' + homeURL + '\')"><font color="#ff0000" face="verdana" size="-2">Log Out</a></font></td>');
            updateBanner=new String('<td align = "center"><font color="#ff0000" face="verdana" size="-2">Remember to logout</a></font></td>');
            sUpdate = 'Status: Remember to logout.';
            sExpiry = 'Renew License in '+(getExpiryDays()-1)+' days';
       }
    }
    else { //LOCAL edition
        if(oTop.asCOOKIEITEM[accessIndex]=="0"){
            expiryBanner=new String("");
            //updateBanner=new String('<td><a href='+tomyaccountURL+' target="_top"><font color="#00aa00" face="verdana" size="-2">Get license</a></font><font color="#5555ff" face="verdana" size="-2"> to activate (requires network access)</font></td>');
            updateBanner=new String('<td align = "center"></font><font color="#000000" face="verdana" size="-2"> Download license to activate (visit myAccount)</font></td>');
            sUpdate = 'Status: Download license to activate (visit myAccount)';
            sExpiry = '';
       }
        else{
            expiryBanner=new String('<td  align = "center"> <font color="#000000" face="verdana" size="-2"> Renew License in '+(getExpiryDays()-1)+' days</font></font></td>');
             sUpdate = 'Status:';
            sExpiry = 'Renew License in '+(getExpiryDays()-1)+' days';
       }
    }
    var endBanner=new String('</tr></table>');
    var sBanner = '<span class="topBannerCell">' + sUserCell + ';</span>'
        + '<span class="topBannerCell">' + sMediaCell + ';</span>'
        + '<span class="topBannerCell">' + sLicenseCell + ';</span>'
        + '<span class="topBannerCell">' + sUpdate +' '+sExpiry + '</span>';
    //document.write("<span style='cursor:pointer;' onclick='goMyAccount()' onmouseover='goTip(\"To upgrade your license or order<br/> a TEST-CD, log on to MyAccount page\")' onmouseout=UnTip(\'\') >"+ startBanner+mediaBanner+accessBanner+idBanner+expiryBanner+updateBanner+endBanner + "</span>");
    document.write('<div class="topBanner">' + sBanner + '</div>' );
 //document.write("<span >"+ startBanner+mediaBanner+accessBanner+idBanner+expiryBanner+updateBanner+endBanner + "</span>");
 }
    //select an option from its value, used in license
    function selectOptionByValue(oSelect, sValue){
        var asOption= oSelect.options, nOptionSize= asOption.length;
        while(nOptionSize){
            if (asOption[--nOptionSize].value== sValue){
                oSelect.selectedIndex= nOptionSize;
                nOptionSize= 0;
            }
        }
    }
    // build a generic convenience function library...here or in registration?

    String.prototype.trim = function () {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    }


    //used whereever registraiton.js is loaded, it checks email...
    function bIsAnEmail(sEmail){
        //alert('testing in global');
        var rPattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
        return rPattern.test(sEmail);
    }


    //onclick handler:used from help/naviation.html
    function goMainHref(sPageURL){
        oTop.main.location = sPageURL;
        return false;
    }
    //onclick handler:used from help/naviation.html; intro files; self wrt page that loads this file
    function goSelfHref(sPageURL){
        self.location = sPageURL;
        return false;
    }
    //onclick handler:used from help/naviation.html; intro files; self wrt page that loads this file
    function goCousinFrameHref(sPageURL,nFrame){
        //alert('frame id: '+parent.frames.length);
        parent.frames[nFrame].location = sPageURL;
        return false;
    }
    //onclick handler:used from Home.js
    function goTopHref(sPageURL){
        oTop.location = sPageURL;
    }
    //tip will work only if tip js files are added in the html file, in this case home.html (through home.js).
    function goTip(sTip,iDelay){
        if(!iDelay) var iDelay = 1000;
        //Tip(sTip, OFFSETY, -4, OFFSETX, 20, DELAY, 1000);
        Tip(sTip, OFFSETY, -4, OFFSETX, 20, DELAY, iDelay);
    }
    //tip will work only if tip js files are added in the html file, in this case home.html (through home.js).
    function goUnTip(){
        UnTip('');
    }

    //clicking status bar takes you to myAccount
    function goMyAccount(){
        //handleToMyAccount();
    // 0. test if local
    if(!oTop.bWEB){

        alert('You have to be online to log on to the myAccount page. Please visit www.thermofluids.net (or a suitable mirror site) and try again. ');
        return;
    }
       if( confirm('The MyAccount page will open in a new window/tab. For account security, you have to log in (with the same id and password) even if you are currently logged into TEST. Proceed? '+oTop.MYACCOUNTURL)) window.open(oTop.MYACCOUNTURL, 'licenseWindow');
       else return;
    }




