<!--

//
//  registration.js - registration script for TEST by Bhattacharjee
//  
//  Author:  Chris Paolini and Subrata  Bhattacharjee [subrata@thermo.sdsu.edu]
// 
//  read cookie or read login string from the server and supply it to every TEST page.
//   Oct 06 (SB): comment.php called without the help of forward.php so that local version runs.
//// Sep 06: license.txt must be included with registration.js for the cookiereading to work.
//bf: Nov, 05: allow daemon use for 15 sec. without registration.
//license comes from license.txt (local) or cookies (web).
//this file is used in all daemons files as well as VT files.

//  decide web or local edition

	var absRegPath="http://energy.sdsu.edu/registrationdev/" // used in inviting people in home.html; also in serverscript/cllientlib.php
	var actualMedia=getActualMedia(); //Local or web is determined.
	var mediaCheck="true"; // check for Local vs. Web edition

//-------------------------------------Global flags: handle with care.
	var releaseFlag=getDynamicFlag("TESTdev"); // "dev" for development or "" for production verstion.

//--------------------------------------server URL. baseURL is the license Server.
	//var baseURL="http://thermo.sdsu.edu/";  //deprecate? used for counters.
    var tomyaccountURL = "http://test.sdsu.edu/registration/tomyaccount.html"; // hard coded
      
	// either registration or registrationdev. Serverscripts adds the actual server name in front.
	var relServerScriptsURL="jscripts/serverScripts/"; //relative to home.html.
	var absServerRegFolderPath="registration"+releaseFlag+"/";  //registrationdev for TESTdev.

//---------------counters. these urls should be moved to absServerRegFolderPath?
	//var studentCount="http://kahuna.sdsu.edu/test/student-list.php", eduCount="http://kahuna.sdsu.edu/test/educators-list.php", proCount="http://kahuna.sdsu.edu/test/professionals-list.php",
	//pageCount=baseURL+"stats/total.php";

//-------------------------------login and logout from serverscripts using curl. My account requires logout.	
// loginURL should transmit whether development or production. 4-13-2005
    if(getDynamicFlag("TESTdev")=="dev") append="?release=dev";
	else append="?release=pro";
	var loginURL=relServerScriptsURL+"login.php"+append, 
	logoutURL=relServerScriptsURL+"logout.php",
	myaccountURL=relServerScriptsURL+"tomyaccount.php?rel="+releaseFlag; //registration or regdev?
	
//-------all account activities in absolute server after forwarding by relServer.
// signup.php can be in energy or entropy as decided in the serverScript/clientLib.php header file.
// the php call is forwarded by forward.php which sends as argument the path, which include the dev
// or prod string to indicate where to look - registration or registrationdev. We can use the same
// trick in comment submission form used in intro/toc.html.
	var signupURL=relServerScriptsURL+"forward.php?path="+absServerRegFolderPath+"signup.php",  
	forgotURL=relServerScriptsURL+"forward.php?path="+absServerRegFolderPath+"forgot.php",
    changeURL=relServerScriptsURL+"forward.php?path="+absServerRegFolderPath+"change.php",
	adminURL=relServerScriptsURL+"forward.php?path="+absServerRegFolderPath+"admin.php",
    commentURL=relServerScriptsURL+"forwardNew.php?path="+absServerRegFolderPath+"kahuna/comment.php";
	//use for admin.

//----------------------------------global variables used in registration.js and login.js
	var saluteIndex=0,firstNameIndex=1, lastNameIndex=2,accessIndex=3,expiryIndex=4, mediaIndex=5,emailIndex=6,	 jumbleIndex=7; // what is number 8 then?
	//get the license using various options
 // There is a ThermoCookieLocalDefault in the license.txt file.
	var ThermoCookieWebDefault = " : :Guest:0:12234567890:WEB:guest@guest.com:LUbZHz0HLUGsMi5zBP8W9_Hk_ohs6Ph35Xijfxamu@7"; 
	var serverCookie=ThermoCookieWebDefault; //overwritten by jsrs call
	var cookieLocation="CLIENT";
    //It has either 9 or 8 : delimited strings, the last two are jumbled.
	ThermoCookie = GetCookie('ThermoCookie');  //cookie has been already written by login.php and read by license.txt
//alert("in registration.js thermocookie = "+ThermoCookie);
    var ThermoCookieList=makeThermoCookieList(ThermoCookie);  //cookie red during construction.


//called during construction, it reads cookie, why are we having parts beyond jumbleIndex in jumble?
// jumble is made of 7th and 8th strings separated by ':'
function makeThermoCookieList(cookieString){
	var cookieList=cookieString.split (/:/);
	var i=jumbleIndex; var newJumble=cookieList[jumbleIndex];

	i=i+1;
    	while (cookieList[i]!=null) { 
		newJumble=newJumble+":"+cookieList[i];
		i=i+1;
    	}
	cookieList[jumbleIndex]=newJumble;

	return cookieList;
}

//functions to get user ID from teh cookie, yet to be implemented.
function getUID(){
	//var iUID =ThermoCookieList[uidIndex];
    var iUID = 0;
	return iUID;
}

//functions to get cookie values.
function getName(){
	var name=ThermoCookieList[saluteIndex]+" "+ThermoCookieList[lastNameIndex];
	return name;
}
//Last naem is guest for unlicensed local and not logged in users. 
function getLastName(){
	return ThermoCookieList[lastNameIndex];
}

function getEmail(){
	return ThermoCookieList[emailIndex];
}

//0: expired, no licnse, 5: guest: 10: academic: 15: professional
function getAccessLevel(){
	return ThermoCookieList[accessIndex];
}

//retursn WEB or LOCAL after detecting http in front of location. Can be read from cookie too!!
function getActualMedia() {
    windowDocumentLocation = window.document.location.toString();
    i = windowDocumentLocation.indexOf(':');
    scheme = windowDocumentLocation.substring(0,i);

    if( scheme.toLowerCase() == "http" ) {
	media="WEB";
    }
    else {
	media="LOCAL";
    }
	if (mediaCheck=="false") return "WEB";
    return media;
}

//detect if dev edition or not??
function getDynamicFlag(folderName) { // decides if the current URL contains folderName.
	var flag="";
    var windowDocumentLocation = window.document.location.toString();
	//if (windowDocumentLocation.match("TESTdev")=="TESTdev") flag="dev";
	if (windowDocumentLocation.match(folderName)==folderName) flag="dev";
	return flag;
}

//number of days left for license expiration, get from cookie.
function getExpiryDays() {
    var expiryDate = new Date(ThermoCookieList[expiryIndex] * 1000);
    var today = new Date();
	var diff=((expiryDate.getTime()-today.getTime())/(24*3600*1000)).toFixed(0);
	if(diff>3650) diff="-";
	return diff
}


function getExpiryDate() {
	var monthString="xxx";
    var expiryDate = new Date(ThermoCookieList[expiryIndex] * 1000);
    var expiryDateString = expiryDate.getDate() + " ";

    switch(expiryDate.getMonth()) {
      case 0:
	monthString = "Jan";
	break;
      case 1:
	monthString = "Feb";
	break;
      case 2:
	monthString = "Mar";
	break;
      case 3:
	monthString = "Apr";
	break;
      case 4:
	monthString = "May";
	break;
      case 5:
	monthString = "Jun";
	break;
      case 6:
	monthString = "Jul";
	break;
      case 7:
	monthString = "Aug";
	break;
      case 8:
	monthString = "Sep";
	break;
      case 9:
	monthString = "Oct";
	break;
      case 10:
	monthString = "Nov";
	break;
      case 11:
	monthString = "Dec";
	break;
    }
    
    expiryYear = expiryDate.getYear();
	if(expiryYear<2003) expiryYear=expiryYear+1900;
    expiryDateString = expiryDateString + monthString + " " + expiryYear;
//alert(expiryDate.toString());
    return expiryDateString;
}

//
function getExpiryStatus() { //true means license has expired.
    var expiryDate = new Date(ThermoCookieList[expiryIndex] * 1000);
    now = new Date;
    if( now.getTime() > expiryDate.getTime() ) {
	// License has expired
	//
	return "true";
    }
    else {
	// User is licensed to use
	//
	return "false";
    }
}

function validUser(){ //accesslevel=0 or expired license, redirect to home page and then to myAccount.
	//alert("access level="+ThermoCookieList[accessIndex]+" expiry stat= "+getExpiryStatus());
	if(ThermoCookieList[accessIndex] == 0||getExpiryStatus()=="true") 
		{return "false";}
	else
		{return "true";}
}

//*********applet call with generated warning based on access level (expired account)
// web/local, and jumbletext. 
function getAppletTag(code,codebaseDepth,codebaseRel,width,height,browserColor) {
    i = 0;  codeDotStr="";
    while (i < codebaseDepth) { 
	codeDotStr=codeDotStr +"../"; i=i+1;
    }
    codebase=codeDotStr+codebaseRel;
	
	var cipherText=ThermoCookieList[jumbleIndex]+":"+ThermoCookieList[8]; // what is in index 8?
	cipherText=ThermoCookieList[jumbleIndex];  
//*** necessary because of the delimeter being part of the string.
  //alert('jumbleIndex: '+ jumbleIndex+'jumble= '+ThermoCookieList[jumbleIndex]);
    tag = new String(" code=\"" + code + "\" codebase=" + codebase + " width=" + width + " height=" + height + "><param name=BrowserColor value="+browserColor+"><param name=warning value="+ThermoCookieList[accessIndex]+"><param name=actualMedia value="+actualMedia+"><param name=jumble value=\"" + cipherText + "\">");

    return(tag);
}

//*********completes the applet tag. used by most  calling pages.
function openApplet(code,codebaseDepth,codebaseRel,width,height,browserColor) {
    tag = getAppletTag(code,codebaseDepth,codebaseRel,width,height,browserColor);
    tag = "<applet"+ tag + "</applet>";
//    alert(tag);
    document.write(tag);
}
//**********fluidType was added as a parameter later.
function openAppletFluidModel(code,codebaseDepth,codebaseRel,width,height,browserColor,fluidType) {
    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) {
    tag = getAppletTag(code,codebaseDepth,codebaseRel,width,height,browserColor);
    tag = "<applet archive="+jarFile+ tag + "<param name=fluidtype value=" + fluidType + "></applet>";
    document.write(tag);
}

//**********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) {
	
    //tag = getAppletTag(code,codebaseDepth,codebaseRel,width,height,browserColor);
    /*i = 0;  codeDotStr="";
    while (i < codebaseDepth) { 
	codeDotStr=codeDotStr +"../"; i=i+1;
    }
    codebase=codeDotStr+codebaseRel;*/


	var cipherText=ThermoCookieList[jumbleIndex]+":"+ThermoCookieList[8];  
	cipherText=ThermoCookieList[jumbleIndex];  
//*** necessary because of the delimeter being part of the string.
  
    tag = new String(" code=\"" + code + "\" codebase=" + codebase + " width=" + width + " height=" + height + "><param name=BrowserColor value="+browserColor+"><param name=warning value="+ThermoCookieList[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);
}

function getCookieVal (offset) {  
    var endstr = document.cookie.indexOf (";", offset);  
    if (endstr == -1)    
      endstr = document.cookie.length;  
    return unescape(document.cookie.substring(offset, endstr));
}
//****modify so that if cookie does not exist it returns defaultstring
function GetCookie (name) {
    //alert('call came to get cookie '+' '+actualMedia+' '+ThermoCookieLocalDefault);
	if(actualMedia=="LOCAL") return  ThermoCookieLocalDefault;
	else if(actualMedia=="WEB"){   
		if (cookieLocation=="CLIENT"){
			var arg = name + "=";  
			var alen = arg.length;  
			var clen = document.cookie.length;  
			var i = 0;  
		
			while (i < clen) {    
				var j = i + alen;    
				if (document.cookie.substring(i, j) == arg) return getCookieVal (j);    
				i = document.cookie.indexOf(" ", i) + 1;    
				if (i == 0)	break;   
			}  
			return ThermoCookieWebDefault;
		}
		else if(cookieLocation=="SERVER"){
			//jsrsExecute(cookieURL, fetchServerCookie, "test", Array("Test","String")); we can leave the parameters null.
			jsrsExecute(cookieURL, fetchServerCookie);
			return serverCookie;
		
		}
	}
}

function GetTestCookie (name) {  
    var arg = name + "=";  
    var alen = arg.length;  
    var clen = document.cookie.length;  
    var i = 0;  
		
    while (i < clen) {    
	var j = i + alen;    
	if (document.cookie.substring(i, j) == arg) 
	    return getCookieVal (j);    
	i = document.cookie.indexOf(" ", i) + 1;    
	if (i == 0)	break;   
    }  
    return(0);
}

function fetchServerCookie( returnstring ){
	//alert(returnstring);
	serverCookie=returnstring;
} 


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()=="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("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 find instructions for activating your local installation. \n\nTo check out what TEST is about without registering, go through the Tutorial. Creating an account takes only a minute or two, is free, and will give you complete access to TEST."); 
	window.parent.location=homeURL;
	}
}


function writeStatusBanner(depth) { //status line on top of each page
	//relative or absolute address
	var logoutURLExpanded=logoutURL, myaccountURLExpanded=myaccountURL;
	var i = 0;   var dotStr="";
        while (i < depth) { dotStr=dotStr +"../"; i=i+1;}
	var loginURLExpanded=dotStr+"index.html"; //takes you to home page.
        logoutURLExpanded=dotStr+logoutURL;
        myaccountURLExpanded=dotStr+myaccountURL;

        var userName=ThermoCookieList[saluteIndex]+" "+ThermoCookieList[lastNameIndex];

        if(getExpiryStatus()=="true") ThermoCookieList[accessIndex]=0;
	switch(ThermoCookieList[accessIndex]) {
	  case "0":
	    classification = new String("Unactivated");
	    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("Unactivated");
	    break;
	}

	
	var startBanner=new String('<table style = "margin-top: 0px;" width=100% border="1" cellpadding="0" cellspacing="0" bgcolor=dddddd><tr>');
	var idBanner =new String('<td width=240><font color="#5555ff" face="verdana" size="-2">Analyst: '+userName+' </font></td>');
	var accessBanner=new String('<td width=140><font color="#5555ff" face="verdana" size="-2">License: '+classification+' </font></td>');
	var expiryBanner;	

	if(actualMedia=="LOCAL") mediaString=new String("LOCAL EDITION");
	else mediaString=new String("thermofluids.net");
	var mediaBanner=new String('<td width=110><font color="#5555ff" face="verdana" size="-2">'+mediaString+' </font></td>');
	
	var updateBanner=new String("");
	if(ThermoCookieList[mediaIndex]=="WEB"){
		if(ThermoCookieList[accessIndex]=="0"){ //not logged in, no need for expiry banner.
			expiryBanner=new String("");
			updateBanner=new String('<td><font color="#5555ff" face="verdana" size="-2">Please </font><a href='+loginURLExpanded+' target="_top"><font color="#00aa00" face="verdana" size="-2">log in</a></font> <font color="#5555ff" face="verdana" size="-2"> to use TEST effectively.</font></td>');
		}
		else{ //logged in
			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>');
			updateBanner=new String('<td><a href='+logoutURLExpanded+'><font color="#ff0000" face="verdana" size="-2">Log Out</a></font></td>');

		}
	}
	else { //LOCAL edition
		if(ThermoCookieList[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>');
		}
		else{
			expiryBanner=new String('<td align=right> <a href='+tomyaccountURL+' target="_top"><font color="#00aa00" face="verdana" size="-2">Renew License</a><font color="#5555ff" face="verdana" size="-2"> in '+(getExpiryDays()-1)+' days</font></font></td>');			}
	}
	var endBanner=new String('</tr></table>');
    document.write(startBanner+mediaBanner+accessBanner+idBanner+expiryBanner+updateBanner+endBanner);
    //document.write(startBanner+mediaBanner+accessBanner+idBanner+expiryBanner+updateBanner+endBanner)
}

//-->
