// creates the home page with js and doc.write
// this is at home.html level, so parent means index.html even when loaded
// in frames by thermofluids.net. note tht reg.js is at diff. levels.
// v 1.14: temp for Tech de Monterry. A lot of changes in writecookie..
// v 1.13: link to newmyaccount v 1.12: message of day
// cosmetic v 1.11 features images instead of video; 1.10 eliminate reg.js
// v 1.9: tab header bug..
// v 1.11: timeout login as visitor
//
Home = Class.create();

//variables in the scope of this class

Object.extend(Home.prototype, {

    initialize: function(){
        this.sMsgOfDay = 'To reliably access TEST, bookmark two independent locations: ';
        this.sMsgOfDay +='<ul><font color="#0088bb"><li/>www.thermofluids.net<font color="#555555">: Multiple servers make this most reliable.</font><p/>';
        this.sMsgOfDay +='<li/>www.iddl.vt.edu/TEST/<font color="#555555">: Mirror in the east coast of USA.</font><p/>';
        this.sMsgOfDay +='<li/>www.sfsb.hr/test/<font color="#555555">: Mirror in Europe.</font><p/>';
        this.sMsgOfDay +='<li/>www.fing.edu.uy/if/mirror/TEST/<font color="#555555">: Mirror in South America.</font><p/>';
        this.sMsgOfDay +='</font></ul><p/><font color="#000000">If your institution is interested in mirroring (for faster access speed), please let us know at support@thermofluids.net.</font>';
        this.oMODExpirs = new Date(2010,8,30);
    },

    // inset popup in home page, sElement popup identifier.
    alertFloat: function (sElement, sMessage){
        var oPopup = new PopupT(sElement);
        oPopup.alertFloat(sMessage);
    },
    // inset popup in home page
    alertInElement: function (sElement, sMessage){
        var oPopup = new PopupT(sElement);
        oPopup.alert(sMessage);
    },
    // inset popup in home page
    alertLocal: function (sMessage){
        var oPopup = new PopupT('popupBox');
        oPopup.alert(sMessage);
    },
    //loginafter enter..
    handleEnter: function(){
        var args = $A(arguments);
        var e = args.shift();     // Event object
        var oThis = args.shift();
        var sBlock = args.shift();
        var keyPressed = e.which || e.keyCode;
        if (keyPressed == 13 ) {
            if (sBlock == 'login') this.handleLogInClick();
            if (sBlock == 'sendpw') this.handleSendPWClick();
            if (sBlock == 'changepw') this.handleChangePWClick();
        }

    },


    //site checkbox has been clicked or unchecked.
    handleSiteLogInClick: function(){
        if($('sitebox').checked){
            $('userid').value = '';
            this.handleLogInClick();
        }
    },

    //php based ajax call for login.
    handleLogInClick: function(){
        //0. check site checkbox, read email and password
        var bSite = $('sitebox').checked;
        var sID = $('userid').value;
        if (sID == '')bSite = true;
        //if(sID.trim() == '') bSite = true;
        var sPW = $('password').value;
        var sPattern = '^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$';
        var orPattern  =  new RegExp(sPattern,"gi");
        var bEmail = sID.search(orPattern) != -1;
        if(!bSite && !bEmail){
            this.alertLocal("The login id is the email you used during creation of the TEST account. If you do not have an account, create one in seconds by clicking the 'create an account' link above.  ");
            return;
        }
        if(bSite){
            document.getElementById('userid').value = '';
            document.getElementById('password').value = '';
        }
        $('log').disable();
        
        //php based ajax call
        //PHPSERVLETPATH is the target URL set by iDEBUG in GlbalHome
        var oBlogSynch = new SynchronizerPHP("ajaxcodes/phpcurl/", parent.PHPSERVLETPATH);
        var sInJSON = '{"sID": "' + sID + '", "sPW": "' + sPW +'"}';
        oBlogSynch.standardUpdate(sInJSON, 'authenticator.php', this.logInCallback, this);
    },


    // callback after all the cookie arrive
    logInCallback: function() {
        // 0. get data from json
        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

        // 5. enable login button even before the try block
        $('log').enable();

        try{
            // 5. extract inJson
            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

            // 10. handle error and warning
            if(oInData.iError >0) {
                oThis.alertBadLogin(oThis,oInData.iError);
                return;
            }

            // 15. set globals
            parent.iWARNING = oInData.iWarning; //warning message cannot be displayed as render will be called again..
            parent.bottomPanel.showLogout();
            parent.bLOGIN = true;
            parent.GLOBALCOOKIE = oInData.sCookie;//index must be a parent
         //alert('Temporary alert #1: '+parent.GLOBALCOOKIE.substr(0,20));
            parent.sSERVEREXP = oInData.sServerExp;//index must be a parent
            var oD = new Date(oInData.iRegistrationTime*1000);
            parent.sREGYEAR = oD.getFullYear();
            parent.tEXPIRATION = oThis.tGetExpTime(parent.COOKIELIFE); // maybe bring cookielife from server?

          //alert('alert #2: setting global vars');
            parent.setGlobalVars(); //update the web cookie and other vars ...

            // 20. write cookies if permitted for easy tabbing by individual user.
            if (parent.GLOBALCOOKIE.indexOf('user@site.edu') == -1)  oThis.writeCookies(oThis,oInData);

            // 25. reload page, login block will be wiped out by the render method...
            self.location = "home.html"; // this will call render again...
        }
        catch(err){
            oSynchronizer = null;
            // allow limited entry...
            alert("Unexpected Error: If you could email this message to support@thermofluids.net, it will be appreciated. Thank you in advance. Error Message: "+err.description);
            parent.iWARNING = 25; //warning message cannot be displayed as render will be called again..
            parent.bottomPanel.showLogout();
            parent.bLOGIN = true;
            parent.GLOBALCOOKIE = "Dr.:Distinguished:Visitor:10:1449907200:WEB:guest@thermofluids.net:ab_ZEn_IA.1R8NkPPUX.tnaDJUHiVh7AGT2W35Hk_ohs6Ph35Xv'fw8Dx:aF3NaYQd"
            parent.sSERVEREXP = "2010-06-28 12:10:12";
            //var oD = new Date(oInData.iRegistrationTime*1000);
            parent.sREGYEAR = '2000';
            parent.tEXPIRATION = oThis.tGetExpTime(parent.COOKIELIFE); // maybe bring cookielife from server?
            parent.setGlobalVars(); //update the web cookie and other vars ...
            self.location = "home.html";
            //alert("The operation could not be completed; please check your network connection and try again.");
            return;
        }
        oSynchronizer = null;
        return;
    },

    //padd now with iLife s and return t in msec
    tGetExpTime: function (iCOOKIELIFE){
        var oToday = new Date();
        var tLife = iCOOKIELIFE*1000; //in msec
        oToday.setTime(oToday.getTime()+tLife);
        var tEXPIRATION = oToday.getTime();
        return tEXPIRATION;
    },

    // display alert messages, failed login attempt..
    alertBadLogin: function(oThis, iError){
        var sMsg = "";
        switch (iError){
            case 5:
                sMsg = "Your login id is valid, but the password did not match. In case you do not remember the password, you can have it mailed to you by following the Forgot Password link above. Also, you can reset your password to something simple to remember by following the Change Password link above.";
                break;
            case 10:
                sMsg = "The email address that you entered does not match with any user account. If you do not have a TEST account, you can create one in seconds by following the Sign Up link above.";
                break;
            case 15:
                sMsg = "You are already logged in from several different IP addresses. Either you forgot to logout or someone else is using your account (if you suspect so, please change your password by following the link above). We have initiated a server-side logout, which will take 15 minutes. Please try to login again after 15 minutes. We regret this inconvenience. ";
                break;
            case 20:
                sMsg = "The server is trying to log you out from your unfinished sessions. The default time interval is 15 minutes. Please try after some time.  ";
                break;
            case 50:
                sMsg = "It appears that your campus does not have a site license yet. For a free academic site license, have an educator from your institution contact Prof. Bhattacharjee, prof.bhattacharjee@gmail.com.";
                break;
            case 100:
                sMsg = "Error: There was a problem connecting to the TEST user database. If the problem persists, please report this error (Error code 100) to support@thermofluids.net.";
                break;
            default : sMsg = "Please check your network connection and try again. If the problem persists, please report this error message (id:" + iError + ") to support@thermofluids.net. Thank you!";
        }
        oThis.alertLocal(sMsg);
    },


    // display alert messages, failed login attempt..
    alertBadWarning: function(oThis, iWarning){
        var sMsg = "";
        switch (iWarning){
            case 5:
                sMsg = "You are currently logged in from another IP address. Perhaps, you forgot to logout from your previous session. When you are done with the current session, please remember to logout. ";
                break;
            case 25:
                sMsg = "You are seeing this message because: (i) your internet access is experiencing problem, (ii) the registration server of TEST is down, or (iii) there is a problem with your account. <p/>We are temporarily logging you in as a visitor (with full access to the daemons). Some of the TEST modules such as the Forum will not work until the problem is resolved. If you see this message everytime you try to log in, causes (i) and (ii) can be ruled out. Please contact us so that we can correct the problem (support@thermofluids.net). We regret this inconvenience.";
                break;
            default : sMsg = "Please check your network connection and try again. If the problem persists, please report this error message (id:" + iError + ") to support@thermofluids.net. Thank you!";
        }
        oThis.alertLocal(sMsg);
    },


    // set more globals and set a cookie if permitted (only for ind. user, not site)
    writeCookies: function(oThis, oInData){
        //0. set ThermoCookie  2 hours expiration time in parent for cookielife sec -  2 hours?

        var oToday = new Date();
        var iLife = parent.COOKIELIFE*1000; //in msec
        oToday.setTime(oToday.getTime()+iLife);
 
        //5. name the cookie and set it? Need to delete in bottom.logout
        var sCookieName = 'ThermoCookie';
        document.cookie = sCookieName+"="+oInData.sCookie + "; expires="+oToday.toGMTString()+"; path=/";

        //10. Is cookie allowed? Read it to test.
        var sRead = '';
        sRead = document.cookie;

        // 15. if cookies are prohibited return;
        if (sRead.indexOf('ThermoCookie') == -1) return;


        // 20. get current user id in a different way (mexico debuggin can't access $('userid') in IE.
        var currentname = '';
        currentname = oInData.sCookie.split(':')[oTop.emailIndex];

        // 25. read autosuggest cookie called username cookies for autosuggest..6 months?
        var username = oThis.getCookie('username');

        // 30. if the cookie does not exist create it fresh
        if(username == "") {
            this.setCookie('username',currentname,180);
        }
        // 35. cookie exisdts, enhance it if the userid is unique
        else {
            if(username.indexOf(currentname) == -1){
                currentname = currentname +':'+username;
                this.setCookie('username',currentname,180);
            }
        }


    },


    //no ajax call yet. from render. first try to read cookie for easy tabbing. also to expire old logins as users come back home
    loadCookie: function() {
        //0. web edition?


        if(parent.sMEDIA=="LOCAL"){
         return;
        }

        //5. test ram cookie life if already set
        var oToday = new Date();
        var tNow =  oToday.getTime(); //in msec
        var tEXPIRATION = parent.tEXPIRATION

        //10. If RAM cookie expired, logout..
        if(tEXPIRATION>0 && tNow>tEXPIRATION) {
            parent.bottomPanel.handleLogout();
            return;
        }

        //15. now try reading cookie, if privacy is too high return...
        var sRead = document.cookie;
        if(!sRead) {
            //alert('cookie could not be found');
            return;
        }
        //20.  read ThermoCookie
        var sCookie = this.getCookie('ThermoCookie');
        if(sCookie == "" ||  sCookie == null) return;
        //if(sCookie == null ) return;

        // 25. cookie still exists, bypass ajax login; set RAM cookie and render takes care of the rest..
        parent.bLOGIN = true;
        parent.GLOBALCOOKIE = sCookie;//index must be a parent
        parent.tEXPIRATION = this.tGetExpTime(parent.COOKIELIFE);
        //alert('set timer for : life='+parent.COOKIELIFE +' exp = '+parent.tEXPIRATION);
        parent.setGlobalVars(); //update the web cookie and other vars ...
        parent.bottomPanel.showLogout();
    },

    //multiple passes...
    render: function(){
        //0. first see if the cookie exists (for tabbing etc.), note that the header has been written already..
        this.loadCookie(); // in case cookie exists bypass login (on a tab)...

        // 5. set default or from cookie
        var lastName = parent.asCOOKIEITEM[parent.lastNameIndex];
        var modeColor=" #d07500 "; var width=" width=80% ";    //
        var modeColorWidth, secondString="My Account", firstString="";

        var bAlert = false;
        var sAlertMsg = '';
        var sMsg = 'To take advantage of all resources offered by TEST, please log in. You can create a free account to check out TEST in minutes by visiting the \'create an account\' link above.';

        //10. on the web, not logged in, and no past account (Mr, Guest)
        if(parent.asCOOKIEITEM[parent.accessIndex] == 0 && parent.asCOOKIEITEM[parent.mediaIndex]=="WEB" && lastName == "Guest") {
            //10.0 draw login block, form needed?
            //document.write('<form class="loginForm" name="loginForm" id="loginForm" method="post"  >');
            document.write('<div id = "loginblock">');
            //document.write(this.sGetLoginBlock());
            document.write('</div>')
            this.renderLoginBlock();
            //10.10 default message for the permanent msg block, replace it with message from author?
     
            //10.15. connect events for the login box.. enter does not work for chrome..
//            $('password').onkeypress = this.handleEnter.bindAsEventListener(this, this);
//            $('userid').onkeypress = this.handleEnter.bindAsEventListener(this, this);
//            $('log').onclick = this.handleLogInClick.bindAsEventListener(this, this);
//            $('sitebox').onclick = this.handleSiteLogInClick.bindAsEventListener(this, this);

            //10.20. auto suggest userid only..
            sMsg = 'To take advantage of all resources offered by TEST, please log in. You can create a free account to check out TEST in minutes.'
            var sUserIDs = this.getCookie('username');
            if(sUserIDs!=""){
                var asUserID = sUserIDs.split(':');
                var oSuggestionProvider = new SuggestionProvider(asUserID);
                var oTextbox = new AutoSuggestControl($('userid'), oSuggestionProvider);
            }            
        }

        // 20. local accounts or web logged in success (first time or in tab through cookie cookie found), or web expired.
        else {        
            var sFirst, sSecond, sModeColor, sModeColorL;

            // 20.0 handle site license greetings and login messages first
            if (parent.asCOOKIEITEM[parent.saluteIndex]=="Site") { //site license
                sFirst = ' Greetings, Site-Licensed User!';
                sSecond = parent.asCOOKIEITEM[parent.lastNameIndex];
                sMsg = 'Each session lasts for 2 hours or until you log out. To extend/upgrade your license beyond '+getExpiryDate()+', please have your instructor contact prof.bhattacharjee@gmail.com.';
            }
            // 20.5 personal a/c (local or web), successful login, valid or expired
            else { 
                sFirst =  ' Greetings, ' + parent.asCOOKIEITEM[parent.saluteIndex] + ' '  +parent.asCOOKIEITEM[parent.lastNameIndex] + '!';
                sSecond = 'Registered User Since ' + parent.sREGYEAR + '. ';
                if (parent.sREGYEAR == '1000' && !parent.bWEB) sSecond = 'You are running TEST locally.';
                if (parent.sREGYEAR == '1000' && parent.bWEB) sSecond = 'Remember to Logout from Each Tab';
                sMsg ='Visit \'myAccount\' page to extend/upgrade your license, which will expire on  '+getExpiryDate()+'.';
            }

            // 20.10 Web and Local: Customize messages for different access levels, expired license etc.

            //20.10.0 Guest access, bLOGIN=true, bWEB=true - license must have expired
            if(parent.asCOOKIEITEM[parent.accessIndex] == 0 && parent.asCOOKIEITEM[parent.mediaIndex]=="WEB") { //expired license
                sModeColor="#d07500 "; sModeColorL = "#e08510" ;
                sSecond="**License Alert**";
                bAlert = true;
                sMsg ='Visit myAccount page to extend/upgrade your license, which expired on  '+getExpiryDate()+'.';
                sAlertMsg = 'Your license to use TEST has expired. Although some of the modules of TEST will still work, most will not without a valid license.'
                    +'<p/>If you are new to TEST, you can start with an academic license for a full year that costs less than two cups of coffee from a certain store. Funds generated from subscription is solely used to support further development of TEST.'
                    +'<p/>As a subscriber when you post a comment in the Forum, your postings will be highlighted and your questions will be answered with priority. You will also receive significant discount when you extend or upgrade your license. Of course, it is easy to create another account and try TEST for another 30 days. But if you find TEST useful, I hope you will do the right thing and support TEST. '
                    +'<p/>Extending or upgrading your license will take seconds. Visit myAccount page and you will find simple instructions there.<p/>Thank you!<p/>Prof. S. Bhattacharjee';
                if(parent.asCOOKIEITEM[parent.saluteIndex]=="Site") sAlertMsg = 'The site license for your campus has expired. Please inform your instructor, who can get the license renewed by contacting prof.bhattacharjee@gmail.com. ';
            }

            //20.10.5 Guest access, Local  -- no cd license
            else if(parent.asCOOKIEITEM[parent.accessIndex] == 0 && parent.asCOOKIEITEM[parent.mediaIndex]=="LOCAL") { //local, no license.txt or expired license.txt
                sModeColor=" #d07500 ";
                sFirst="Install license.txt file to activate TEST.";
                sSecond="Visit myAccount to download license.txt.";
                bAlert = true;
                sAlertMsg = 'You are seeing this message because either you have not installed the license file or it has expired.'
                    +'<p/>For TEST to run locally, a valid license file must be downloaded and installed. '
                    +'<p/>Visit www.thermofluids.net, access the myAccount page, and click the "Get CDROM License" button. The license should arrive in your inbox in less than a minute as an attachment named "license.txt". Make sure you check your SPAM folder of your mailbox.'
                    +'<p/>In your locally installed copy of TEST (say, in a folder called myTEST) you will find an existing "license.txt" file in the myTEST folder. Simply replace the old "license.txt" with the new file arriving with the email. You can also copy and paste the old content with the new content as these are text files. This will activate the locally installed copy of TEST.'
                    +'<p/>If you have questions, visit the Forum or write to us at support@thermofluids.net.';
            }

            // 20.10.10 evaluation - set header for evaluation from guest
            else if(parent.asCOOKIEITEM[parent.accessIndex] ==5) { //evaluation?
                if(parent.bWEB){
                    $('headerPart1').src = "testcentericons/headerPart1Evaluation.jpg";
                    $('headerPart2').src = "testcentericons/headerPart2Evaluation.jpg";
                }
                sModeColor="#4aa02c";
            }
            // 20.10.15 academic
            else if(parent.asCOOKIEITEM[parent.accessIndex] ==10) { //academic
                if(parent.bWEB){
                    $('headerPart1').src = "testcentericons/headerPart1Academic.jpg";
                    $('headerPart2').src = "testcentericons/headerPart2Academic.jpg";
                }
                sModeColor="#5555aa"; 
            }
            // 20.10.20 prof.
            else if(parent.asCOOKIEITEM[parent.accessIndex] ==15) { // professional
                if(parent.bWEB){
                    $('headerPart1').src = "testcentericons/headerPart1Professional.jpg";
                    $('headerPart2').src = "testcentericons/headerPart2Professional.jpg";
                }
                sModeColor="#5555aa";
            }
            // 20.15 write greetings part1 and 2. draw logout (in case cookie caused the login..
            document.write('<table align=center width=100% bgcolor=dddddd  height=20 ><tr><td BGCOLOR='+sModeColor+' width = "50%" align="center"><font color=#ffffff face=verdana size=-1>' + sFirst +  ' <font></td><td  bgcolor='+sModeColor+' width = "50%" align="center"><font color=#ffffff face=verdana size=-1>' + sSecond +  '</font></td></tr></table>');
            //alert('calling bottom.showlogout');
            if(parent.bWEB) parent.bottomPanel.showLogout();
        }



        // 25. boxes used for alert during login and permanent message after login.
        document.write('<div id = "alertBox" class="alertBox"></div>');
        document.write('<div id = "messageBox" class="messagebox"></div>');

        // 30. bAlert may be set in the else block above..
        if(bAlert) this.alertLocal(sAlertMsg);
        else if (parent.bWEB && !parent.bLOGIN){
            var oDate = new Date();
            if (oDate < this.oMODExpirs) this.alertLocal(this.sMsgOfDay);
        }
        this.sSetLoginMsg(sMsg);

        // 35. table starts with feature video clips, quote by Arnold
        document.write('<table bgcolor=ffffff border=0 width=100% cellpadding=5 cellspacing=0 >');
        this.writeVideoClip();
        document.write('<tr><td>');
        document.write('<p>');
        document.write('<img src="testcentericons/quote.gif" nosave valign=top border=0 alt="Click here for a Feature Tour">');

        document.write('</td></tr><tr valign=bottom><td valign="Bottom"> <p><font face="verdana" size="-1">');

        // 30. welcome message
        document.write('Welcome  to TEST - a visual platform to analyze  thermofluids problems,  verify hand calculations, pursue what-if '+
            'scenarios,  visualize thermal systems, and engage in a life-long journey to master thermodynamics.</p>'+
            '<p><font face="verdana" size="-1">Created for students, educators, and practicionars of thermodynamics, TEST offers smart thermodynamic tables for property evaluation and analysis  tools for  mass, energy, entropy, and exergy analysis of open and closed systems, IC engines, gas and vapor power cycles, refrigeration, HVAC, combustion, chemical equilibrium, and gas dynamics. </p>' +
            '<p><font size="-1" face="verdana">Beside the <em>daemons - </em> dedicated web-based  calculators with a friendly graphical interface - you will find other useful modules such as an animation library, rich internet applications (RIA\'s), traditional charts and tables, manual and TEST solutions of hundreds of engineering problems, and fifteen chapters of examples and problems to supplement any thermodynamics textbook.</p>'+
            '<p><font face="verdana" size="-1">Go through the <em>Tutorial</em>, specifically the Getting Started and My First TEST Solution sections, before you create an account (takes less than a minute) and start exploring TEST. Once you conclude that TEST can be a useful tool for you, visit the <em>myAccount</em> page to upgrade your account, order a CD for local installation, or request a site license for your institution. TEST is freely distributed to educators and students of any academic institution. If you are an educator, please write directly to prof.bhattacharjee@gmail.com to obtain a permanent license.  </p>  '+
            '<p><font face="verdana" size="-1">If you have any question or comment, visit the Forum. There, you can search and browse discussions organized into various thermodynamic topics. Any well-posed thermodynamic question will be addressed by the moderators expeditously. You will be notified as soon as an answer is posted.'+
            '</td></tr>'+
            '</table>');

        // 40. warning has been set after login..
        if(parent.iWARNING >0) {
            this.alertBadWarning(this, parent.iWARNING);
        }
    },


    // called by home.html it writes graphic header  writeHomeHeader
    renderHeader: function(){
        var headerPart1, headerPart2;
        if(getExpiryStatus()) parent.asCOOKIEITEM[parent.accessIndex]="0";
        var lastName = parent.asCOOKIEITEM[parent.lastNameIndex];
        switch(parent.asCOOKIEITEM[parent.accessIndex]) {
            case "0": // either not registered or expired license, distinguish the two through last name. "Guest" cannot be anyone's lastname

                headerPart1="headerPart1Guest"; headerPart2="headerPart2Guest";
                footnote=new String("Guest Mode/WEB: This is the default mode with very limited access. You may browse the Tutorial or the Slide Show pages to learn about TEST, but you must log in in order to use TEST effectively. ");
                message=new String('<br><table width=100%  boder=2 cellpadding=2 cellspacing=0><tr><td><font face="verdana" size="-1" color=blue><hr>Activation Procedure: You must activate this locally installed distribution of TEST. Activation means downloading a license file and save it in a particular folder. The following instructions assume that you have already copied the entire content of the CD into a local folder named \"myTEST\" (in your C drive or desktop) and bookmarked this local page in your favorite browser (Firefox/IE/Safari). More detailed instructions can be found in the README.txt file in the CD.<ol><li>If you are not connected to the Internet, go to step-2. Click on the \"My Account\" link on the Task Bar (or next to the greetings  above). It will take you to the TEST registration site, where you must log in to access your account. If you do not have an account, you can create one in minutes following the \"create an account\" link. In case you forgot your password it will be emailed to you as long as you remember your login id (the email address you use during registration). <p>After you log in, you can see your account status in the "My Account" page. There you will see a button  "Send CDROM License" prominantly displayed (among other options). Click on it to receive the license file "license.txt" as an email attachment (should take less than a minute; make sure you check your spam folder just in case the machine generated mail is treated as spam by your email application). The license file contains the expiration date of your subscription and the type of subscription (educational vs. professional). Log out of "My Account" and check your email. After the "license.txt" file arrives as an attachment, save it in the "testcenter" folder, located inside the "myTEST" folder (where you copied the content of the CD). The new file replaces an old  file by the same name ("license.txt") copied from the CD. <p>Launch TEST again (using your local bookmark or clicking the index.html file in the "myTEST" folder).  A personalized greetings on the home page will indicate that TEST has been successfully activated. Also, this instruction block will disappear and appear again only after your license will have expired.<p><li>If your computer does not have a network connection, you have to go to a different networked computer and visit www.thermofluids.net, click on myAccount link, and get the "license.txt" file as described in Step-1. After the file arrives, copy it into a floppy disk or some other moveable media, and transfer it to the "myTEST/testcenter" folder in your non-networked computer.  <p><li>Once activated, the local edition of TEST does not require any network connection (except for accessing the solution manual). After your license period expires, these instructions will reappear on this page. To extend your license, go to "My Account" page, renew your license,  obtain a fresh "license.txt" file to update/upgrade your existing license. Users who renew license before the expiration date receive a substantial discount. <p><li>If you received the cd from a colleague, follow the same procedure starting at Step-1. Of course, you have to create an account first by registering (click on "Register Now" in the "My Account" page). </ol><hr></font></td></tr></table>');

                if(parent.sMEDIA=="WEB"&& lastName=="Guest") message='<div class="messagebox"><div class = "news" >ACCESS SPEED OF THE FORUM PROGRESSIVELY INCREASES AS YOU ACCESS IT MORE OFTEN. THE FORUM NOW WORKS IN CHROME ALSO. </div>To test if your institution has a site license, simply click the Log In button above. Academic site license is free and can be activated in minutes for your campus. If you are an educator, create a personal account (in seconds) and then send an email to Prof. Bhattacharjee (prof.bhattacharjee@gmail.com) to upgrade your account. Also, to set up the free site license, include the first two nodes of the IP address of your campus.   </div>';
                if(parent.sMEDIA=="WEB" && getExpiryStatus()){ //account expired, web user
                    message=new String('Dear '+parent.asCOOKIEITEM[parent.saluteIndex] + ' ' + lastName +',\n\nYour license to use TEST needs to be renewed, which apparently expired on '+getExpiryDate()+'. Close this \nwindow and go to \"My Account\" page, where you can renew/upgrade your license in minutes. If you are an educator, please write directly to prof.bhattacharjee@gmail.com for a permanent academic license.\n\nThank you for your support! \n\nS. Bhattacharjee, Author of TEST\n');
                    message= '<div class="messageboxred">Your license to use TEST needs to be renewed, which apparently expired on '+getExpiryDate()+'. Go to My Account page, where you can renew/upgrade your license in minutes. <p>If you are an educator, please write directly to prof.bhattacharjee@gmail.com to extend/upgrade your academic license.</div>';
                }

                if(parent.sMEDIA=="LOCAL"){
                    headerPart1="headerPart1GuestLocal";
                    footnote=new String("Guest Mode/Local Edition: This is the default mode with very limited access. You must activate this local edition in order to use TEST effectively.");

                }


                break;
            case "5":
                headerPart1="headerPart1Evaluation"; headerPart2="headerPart2Evaluation";
                footnote=new String("Evaluation Mode: This mode gives you almost as much access as the Academic Mode for a limited period of time. In the Evaluation Mode run a few daemons to make sure that everything works before upgrading your license to Academic or Professional Mode.");

                if(parent.sMEDIA=="LOCAL"){
                    headerPart1="headerPart1EvaluationLocal";
                }
                break;
            case "10":
                headerPart1="headerPart1Academic"; headerPart2="headerPart2Academic";
                footnote=new String("Academic Mode/Web Edition: This mode gives you access to an adequate set of working substances used in thermodynamics education.  Web Edition means you are accessing the latest version of TEST. The access speed is, however, limited by the speed of your connection. If you would like to run TEST locally to enjoy its native performance, order a TEST-CD. The Professional Edition of TEST contains a much larger data base and comes with a CD for local installation. ");

                if(parent.sMEDIA=="LOCAL"){
                    headerPart1="headerPart1AcademicLocal";
                    footnote=new String("Academic Mode/Local Edition: This mode gives you access to an adequate set of working substances used in thermodynamics education. Local installation means access speed is at its fastest and no Internet connection is necessary. The Professional Edition of TEST contains a much larger data base. ");

                }
                break;
            case "15":
                headerPart1="headerPart1Professional"; headerPart2="headerPart2Professional";
                footnote=new String("Professional Mode/Web Edition: This mode gives you complete access to the growing list of working substances available in the TEST database. Web Edition means you are accessing the latest version of TEST. The access speed is, however, limited by the speed of your connection. For best access, obtain a license with a CD so that you can run TEST locally for speed and access the Web Edition to use the latest version from anywhere. ");

                if(parent.sMEDIA=="LOCAL"){
                    headerPart1="headerPart1ProfessionalLocal";
                    footnote=new String("Professional Mode/Local Edition: This mode gives you complete access to the growing list of working substances available in the TEST database. Local installation means access speed is at its fastest. Occasionally access TEST on line to see if the on line version has improved sufficiently to justify an upgrade.");

                //alert('got it');

                }
                break;
            default:
                break;
        }
        document.write('<tr><td bgcolor=#ffffff valign=top align=center width=20%><img src="testcentericons/testLogoEd.jpg" Alt="TEST Logo" nosave border=0 width=100 height=90 usemap="#m_testLogoEd"><map name="m_testLogoEd"><area shape="rect" coords="17,0,24,6" href='+oTop.ADMINURL+'><area shape="rect" coords="25,0,31,6" href="http://energy.sdsu.edu/awstats/awstats.pl?config=energy.sdsu.edu"><area shape="rect" coords="17,0,24,6" href='+oTop.ADMINURL+'><area shape="rect" coords="25,0,31,6" href="http://energy.sdsu.edu/awstats/awstats.pl?config=energy.sdsu.edu"><area shape="rect" coords="80,12,90,20" href='+oTop.MYACCOUNTURLTEMP+'></map></td><td width=75% valign=top align=middle ><a target="_top" href="http://www.thermofluids.net"><img id = "headerPart1" src="testcentericons/'+headerPart1+'.jpg" nosave border=0 width=590 height=90></a></td><td bgcolor=#ffffff valign=top align=middle width=5%><img id = "headerPart2" src="testcentericons/'+headerPart2+'.jpg" width=40 height=90  alt="About TEST-Pro" border=0></td></tr>');

    },


    //invitation for a friend to join...
    writeInvite: function () {
        var s = '<table border=0 cellpadding=0 cellspacing=0 height=50 >';
        s += '<tr><td  align=left class="linkStyle" colspan=2 >Email:</td></tr>';
        document.write(s);
	document.write('<FORM  METHOD="POST" ACTION='+oTop.INVITEURL+' >');
        document.write('<tr><TD colspan=2><input type="hidden" name="from" value='+parent.getEmail()+'><input type="hidden" name="fromName" value='+parent.getLastName()+'><INPUT TYPE="text" name="to" SIZE="12" MAXLENGTH="100" ></TD></tr><tr></tr><small><TD align=center height=10 colspan=2><INPUT name="submit" TYPE="submit" VALUE="Invite"></small></td></tr></form>');
        document.write('</table>');
    },

    //number of days left for license expiration, get from cookie.
    getExpiryDays: function () {

        //var expiryDate = new Date(ThermoCookieList[expiryIndex] * 1000);
        var expiryDate = new Date(parent.asCOOKIEITEM[parent.expiryIndex] * 1000); //time in msec
        var today = new Date();
        var diff=((expiryDate.getTime()-today.getTime())/(24*3600*1000)).toFixed(0);
        //if(diff>3650) diff="-";  ??
        return diff;
    },

    // constructor calls this to make message
    sSetLoginMsg: function(sMsg){
//        var sDaysLeft = this.getExpiryDays();
//        if(parent.bWEB){
//            sMsg = 'Each session lasts for 2 hours or until you log out. You can extend/upgrade your license beyond '+getExpiryDate()+'  by visiting the My Account page or by writing directly to prof.bhattacharjee@gmail.com if you are an educator or a site license holder. </div>';
//        }
//        var sMsg ='Visit "My Account" link to extend/upgrade your license, which will expire on  '+getExpiryDate()+'.';
        if ($('messageBox'))$('messageBox').innerHTML = sMsg;

    },

    // right under login message, do camtasia video
    writeVideoClip: function (){
        var iRandom = Math.floor(Math.random()*3);
        var asFeature = [];
        asFeature[0] = 'features/featureA.html';
        asFeature[1] = 'features/featureB.html';
        asFeature[2] = 'features/featureC.html';
        //if(getExpiryStatus()=="true") ThermoCookieList[accessIndex]="0";
        if(getExpiryStatus()) parent.asCOOKIEITEM[parent.accessIndex]="0";
        if(parent.sMEDIA=="WEB"  && parent.asCOOKIEITEM[parent.accessIndex] != 0) {
        }
        else{

            var s = "<tr ><td valign='top' align=left><iframe  id='videoClip' frameborder='0' scrolling='no' valign = 'top' align = 'left' width='582' height = '335' marginheight='0px' marginwidth='0px' src='"+asFeature[iRandom]+"'></iframe></td></tr>";
            document.write(s);
        }
    },


    //image for Web Edition vs. Web Mirror etc.
    writeMirror: function(){
        var mirrorFile="webEdition.jpg";
        if(parent.sMEDIA=="WEB") mirrorFile="webMirror.jpg";
        document.write('<img src=testcentericons/'+mirrorFile+'>');
    },

/*
    getCookie: function( name ) {
        var start = document.cookie.indexOf( name + "=" );
        var len = start + name.length + 1;
        if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
            return null;
        }
        if ( start == -1 ) return null;
        var end = document.cookie.indexOf( ';', len );
        if ( end == -1 ) end = document.cookie.length;
        return unescape( document.cookie.substring( len, end ) );
    },
*/


    // from w3school.com
    setCookie: function (sCookieName,value,iLifeInDays) {
        var oToday = new Date();
        oToday .setDate(oToday .getDate()+iLifeInDays);
        var usernames = escape(value);
        document.cookie=sCookieName+ "=" +usernames+((iLifeInDays==null) ? "" : ";expires="+oToday .toGMTString());
    },

    // return a string like email1: email2: email3
    getCookie: function (sCookieName){
        if (document.cookie.length>0){
            iStartIndex=document.cookie.indexOf(sCookieName + "=");
            if (iStartIndex!=-1){
                iStartIndex=iStartIndex + sCookieName.length+1;
                iEndIndex=document.cookie.indexOf(";",iStartIndex);
                if (iEndIndex==-1) iEndIndex=document.cookie.length;
                return unescape(document.cookie.substring(iStartIndex,iEndIndex));
            }
        }
        return "";
    },

    sGetLoginBlock: function(){
            var s = '';
            //s += "<input type=hidden name=operation value=\"login\">";
            s += "<table width='100%' bgcolor='dddddd' border='0' cellpadding='0' cellspacing='0'>";

            s += "<tr>";
            s += "  <td width='5'>&nbsp;</td>";
            s += '  <td height=20 colspan=1><font face=verdana size=-1> Log in or <a href='+oTop.SIGNUPURL+' >create an account</a></font></td>';

            s += "  <td width='2'>&nbsp;</td>";
            s += '  <td height=20  colspan=3>[ <a href="#" id = "sendpwlabel"  ><font face=arial size=-1>Forgot password?</font></A>&nbsp;&nbsp;&nbsp;<A href='+oTop.CHANGEURL+' ><font face=arial size=-1>Change password</font></A>&nbsp; ]</td>';
            s += "</tr>";

            s += "<tr>";
            s += "  <td width='5'>&nbsp;</td>";
            s += "  <td width='190' height='5' valign='middle'><font face='verdana' size='-2'>Login id (e-mail address):</font></td>";
            s += "  <td width='5'>&nbsp;</td>";
            s += "  <td  height='5' colspan='3' valign='middle'><font face='verdana' size='-2'>Password: (No id or password is necessary with site license.)</font></td>";
            s += "</tr><tr>";

            //10.5 userid and password
            s += "  <td width='5'>&nbsp;</td>";
            s += "  <td width='190' height='5' valign='top'><font face='verdana' size='-1'><INPUT name=userid   type = text id='userid' size='30' maxLength='40' tabindex='1'></font></td>";
            s += "  <td width='2'>&nbsp;</td>";
            s += "  <td  width = 100 height='5' valign='top'><font face='verdana' size='-1'><INPUT  name=password type=password id='password' size='15' maxLength='15' tabindex='2'></font></td>";
            s += "  <td  colspan=2  >";
            s += "  <INPUT  type=button  value='Log In' name='log' id='log' /> <INPUT type=checkbox  value=NO name='sitebox' id='sitebox' tabindex='4' /><font face='verdana' size='-1'>Site License</font></td>";
            s += "</tr>";

            s += "<tr>";
            s += "  <td width='5'>&nbsp;</td>";
            s += "  <td colspan='5'>";
            s += "  <font face='verdana' size='-1'>To test if your campus/corporation has a site license, click the Site License box.&nbsp;&nbsp;&nbsp;</font></td>";
            s += "</tr>";

            s += "</table>";
            return s;
    },


    sGetForgotBlock: function(){
            var s = '';
            //s += "<input type=hidden name=operation value=\"login\">";
            s += "<table width='100%' bgcolor='dddddd' border='0' cellpadding='0' cellspacing='0'>";

            s += "<tr>";
            s += "  <td width='5'>&nbsp;</td>";
            s += '  <td height=20 colspan=4><font face=verdana size=-1> Retrieve password or go back to the <a href="#" id="loginlabel" >log in block</a></font></td>';
            s += "</tr>";

            s += "<tr>";
            s += "  <td >&nbsp;</td>";
            s += "  <td width='190' height='5' valign='middle' colspan='5'><font face='verdana' size='-2'>Login id (e-mail address: your password will be emailed right away)</font></td>";
            s += "</tr><tr>";

            //10.5 userid and password
            s += "  <td >&nbsp;</td>";
            s += "  <td width='190' height='5' valign='top'><font face='verdana' size='-1'><INPUT name='userid'   type = text id='userid' size='30' maxLength='40' tabindex='1'></font></td>";
            s += "  <td width='2'>&nbsp;</td>";
            s += "  <td  colspan='3'  >";
            s += "  <INPUT  type=button  value='Send Password' name='pwbutton' id='pwbutton' /> </td>";
            s += "</tr>";

            s += "<tr>";
            s += "  <td >&nbsp;</td>";
            s += "  <td colspan='5'>";
            s += "  <font face='verdana' size='-1'>The password should arrive in your inbox within a minute. Check your spam folder.</font></td>";
            s += "</tr>";

            s += "</table>";
            return s;
    },
    
    
    //site checkbox has been clicked or unchecked.
    renderSendPWBlock: function(){
        self.location = oTop.FORGOTURL;
//        $('loginblock').innerHTML = this.sGetForgotBlock();
//        $('loginlabel').onclick = this.renderLoginBlock.bindAsEventListener(this, this);
//        $('pwbutton').onclick = this.handleSendPWClick.bindAsEventListener(this, this);
//        $('userid').onkeypress = this.handleEnter.bindAsEventListener(this, this, 'sendpw');
    },

    //site checkbox has been clicked or unchecked.
    renderLoginBlock: function(){
        $('loginblock').innerHTML = this.sGetLoginBlock();
        $('password').onkeypress = this.handleEnter.bindAsEventListener(this, this, 'login');
        $('userid').onkeypress = this.handleEnter.bindAsEventListener(this, this, 'login');
        $('log').onclick = this.handleLogInClick.bindAsEventListener(this, this);
        $('sitebox').onclick = this.handleSiteLogInClick.bindAsEventListener(this, this);
        $('sendpwlabel').onclick = this.renderSendPWBlock.bindAsEventListener(this, this);
    },

    //php based ajax call for sending pw.
    handleSendPWClick: function(){
        alert('send password handler');
        //0. check site checkbox, read email and password
        var sID = $('userid').value;
        var sPattern = '^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$';
        var orPattern  =  new RegExp(sPattern,"gi");
        var bEmail = sID.search(orPattern) != -1;
        if(!bEmail){
            this.alertLocal("Please check your input. The login id is the email address you used during account creation.   ");
            return;
        }
        $('sendpwbutton').disable();

        //php based ajax call
        //PHPSERVLETPATH is the target URL set by iDEBUG in GlbalHome
        var oBlogSynch = new SynchronizerPHP("ajaxcodes/phpcurl/", parent.PHPSERVLETPATH);
        var sInJSON = '{"sID": "' + sID + '"}';
        oBlogSynch.standardUpdate(sInJSON, 'sendPassword.php', this.logInCallback, this);
    },


    //php based ajax call for sending pw.
    handleChangePWClick: function(){
        alert('change password handler');
    }



});