
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

//Collection of Javascript functions that all work towards
//dynamically creating a APPLET tag with necessary attributes
//and parameters.
//
// $Id: poet_applet.js,v 1.11 2010/08/19 22:53:36 ntt Exp $

// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

// Collects the query string parameters from the URL and returns
// them as an associative array.
// RETURNS: string to string array

function get_query_parameters()
{
    var qsParamArray = new Array();
    var query = window.location.search.substring(1);
    var params = query.split("&");
    for (var index = 0; index < params.length; index++)
    {
    	var position = params[index].indexOf('=');
	    if (position > 0)
	    {
	        var key = params[index].substring(0, position);
	        var val = params[index].substring(position + 1);

	        qsParamArray[key] = unescape(val);	
	    }    
    }
    
    return qsParamArray;
}

// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

//JS novice creating custom object for something that probably already exists
//function JavaPropertyObj(propName, propValue)
//{
//    this.propertyName  = propName;
//    this.propertyValue = propValue;    
//    this.getName  = function() { return this.propertyName; };
//    this.getValue = function() { return this.propertyValue; };
//}

// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

//Returns an array of default parameters.  These parameters are
//retrieved from the server-side file 'poet_applet.props'.  If
//unsuccessful, then get_default_parameters_hardcoded() will be used.
// RETURNS: string to string array

function get_default_parameters()
{
    var propsFilename = "poet_applet.props";
    var defaultParams = getPropertiesFromFile(propsFilename);
    if (!defaultParams)
	    defaultParams = get_default_parameters_hardcoded();

    //Due to a bug in Apple's version of JVM that does not 
    //correctly handle cross-platform look and feel for
    //combo boxes, check if we should rquire native lnf
    if (shouldEnforceNativeLookAndFeel())
    {
	defaultParams["poet.use.native.lnf"] = "true";
        defaultParams["poet.table.scrolling.hidden"] = "true";
    }   

 
    return defaultParams;	
}

// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

// Returns an array of applet parameters, combining default
// with overriding values from the URL query string
// RETURNS: string to string array

function get_applet_parameters()
{
    var dParams = get_default_parameters();
    var qParams = get_query_parameters();
    
    var aParams = new Array();
    for (dKey in dParams)
    {
	var dVal = dParams[dKey];
	aParams[dKey] = dVal;
    }
    
    for (qKey in qParams)
    {
	var qVal = qParams[qKey];
	aParams[qKey] = qVal;
    }
    
    return aParams;
}

// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

// Returns the size of the applet based on properties.
// !!PARAM: width      - width of the applet
// !!PARAM: height     - height of the applet
// !!PARAM: parameters - parameter array

function get_applet_dimensions()
{
    var listWidth    = "780";
    var listHeight   = "1500";
    var tabbedWidth  = "780";
    var tabbedHeight = "850";
    
    var dimensions = new Array();
    dimensions["width"]  = listWidth;
    dimensions["height"] = listHeight;
    
    var parameters = get_applet_parameters();
    if (parameters)
    {
        var layoutType = parameters["poet.panel.layout"];
	    if (layoutType)
	    {
	        if (layoutType == "tabbed")
	        {		    
	            dimensions["width"]  = tabbedWidth;
		        dimensions["height"] = tabbedHeight;     
	        }
	    }	    
    }
    
    return dimensions;
}

// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

// Returns the name of the JAR/archive file based on properties

function get_applet_archive()
{
    var defaultJar = "poet.jar";
    var signedJar  = "signed_poet.jar";
    
    var returnVal  = defaultJar;
    
    if (isSecure())
    {
        returnVal = signedJar;	        
    }
    
    
    //Add browser launcher
    if (false)
    {
        returnVal = "" + returnVal + ", " + "BrowserLauncher2-all-1_3.jar";
    }
    
    return returnVal;
}

// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

// Returns hardcoded default parameter.  This is in place in case
// the properties file cannot be loaded.
// RETURNS: string to string array

function get_default_parameters_hardcoded()
{
    
    var params = new Array();

    var myHost     = window.location.protocol + "//" + window.location.host;    
    var myBase     = myHost + "/" + window.location.pathname;
    var myConfig   = myBase + "/config";
    
    params["poet.datasource.configuration"] = myConfig + "/dataconfig.xml";     //"http://mako.jpl.nasa.gov/poet/config/dataconfig.xml";
    params["poet.dataview.configuration"]   = myConfig + "/dataviews.xml";      //"http://mako.jpl.nasa.gov/poet/config/dataview.xml";
    params["poet.region.configuration"]     = myConfig + "/regions.xml";        //"http://mako.jpl.nasa.gov/poet/config/regions.xml";
    params["poet.map.location"]             = myConfig + "/map720.jpg";         //"http://mako.jpl.nasa.gov/poet/config/map720.jpg";
    params["poet.daterange.configuration"]  = myConfig + "/daterange";          //"http://mako.jpl.nasa.gov/poet/daterange";
    params["poet.help.location"]            = myBase   + "/gui_help.html";      //"http://mako.jpl.nasa.gov/poet/gui_help.html";
    params["poet.frame.width"]              = "760";
    params["poet.use.scrolling"]            = "false";
    params["poet.panel.layout"]             = "list";
    params["poet.log.title"]                = "POET";
    params["poet.datasource.title"]         = "Variable";    
    params["poet.log.debug"]                = "false";
    params["poet.userregion.service"]       = myHost + "/cgi-bin/esip/user_mask.pl";    

    return params;	
}

// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

function isSecure()
{
    var isSecure = (window.location.protocol == "https:");
    
    if (!isSecure)
    {
        var parameters = get_applet_parameters();
        if (parameters)
        {
            var isSecure = parameters["secure"];
            if (!isSecure)
            {
                isSecure = parameters["signed"];
            }
	    }	    
    }
       
    //alert("Is secure => "+isSecure);
        
    return isSecure;
}

function shouldEnforceNativeLookAndFeel()
{
    var enforceNativeLnf = false;

    if (true)
    {
        //Required for macs due to bug in cross-platform lookandfeel

        enforceNativeLnf = navigator.userAgent.indexOf('Mac') != -1; 
       
        //enforceNativeLnf = !enforceNativeLnf; 
    }


    return enforceNativeLnf;
} 


function get_applet_codebase()
{

    var myBase = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
    
    var myPath = myBase + "/lib/";
    
    //alert("Path = "+myPath);
    
    return myPath;
    
}

// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

// Generates an APPLET element with underlying PARAM elements
// for the Poet applet. This includes size, query params,
// and default parameters.  Inserts under div with id
// equal to the appletId parameter
// PARAM: appletId - name associated with div where applet will be inserted
// PARAM: width    - width of the applet
// PARAM: height   - height of the applet

function generate_applet_tags(appletId, width, height)
{
    
    var archiveFile = get_applet_archive();
    if (!(archiveFile))
        archiveFile = "poet.jar";
    
    var codeBase = get_applet_codebase();
    if (!(codeBase))
        codeBase = "lib/";
    
    //attributes of the APPLET tag
    var attributes = {
    	code:     "gov.nasa.jpl.podaac.poet.ui.PoetApplet",
        name:     "PoetApplet",
        codebase:  codeBase,
        archive:   archiveFile,
        hspace:   "0",
        vspace:   "0",
        align:    "top",
        id:       "poetApplet",
        alt:      "POET applet should run here"
    };
    //var attributes = {
    //	code: "gov/nasa/jpl/podaac/poet/ui/PoetApplet.class",
    //    name: "PoetApplet",
    //    codebase: "lib/",
    //    archive: "poet.jar",
    //    hspace: "0",
    //    vspace: "0",
    //    align: "top",
    //    id: "poetApplet"
    //};
    
    //create a new applet element
    var appletTag = document.createElement("APPLET");

   
    //set the width and height params, then iterate over attributes from above
    appletTag.setAttribute("width",  width);
    appletTag.setAttribute("height", height);
    for (var attribute in attributes) 
    {
    	appletTag.setAttribute(attribute, attributes[attribute]);
    }
    
    
    //create the PARAM children under APPLET    
    var appletParams = get_applet_parameters();
    for (var paramKey in appletParams) 
    {	
	    var paramVal = appletParams[paramKey];
	    if (paramVal != null)
	    {
            var paramTag = document.createElement("PARAM");
	        paramTag.setAttribute("name",  paramKey);	
	        paramTag.setAttribute("value", paramVal);
	        appletTag.appendChild(paramTag);	
	    }			
    }   
    
    
    //create a message to be displayed if Java not available
    
    //Internet Explorer seems to complain about this, so leave it commented for now........
    //var pNode = document.createElement("P");    
    //var textNode = document.createTextNode("Java must be installed for the browser to run this Applet. Please visit http://www.java.com to download.");    
    //pNode.appendChild(textNode);      
    //appletTag.appendChild(pNode);
    
    
    //-----------------------
    
    //get reference to the body    
    var bodyRef = document.getElementById(appletId);

    //insert the applet tag
    bodyRef.appendChild(appletTag);

    
    if (appletParams["debugjs"])
        showAppletAsAlert(bodyRef);
    
    if (appletParams["debugjsall"])
        showAppletAsAlert(document.getElementById("appletTable"));
	
}

// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

function showAppletAsAlert(domNode)
{
    var barstring = "\n==============================================================\n";	
    var message = barstring + "[DEBUG] Applet as HTML" + barstring;
    message = message + domNode.innerHTML;
    message = message + barstring;
    alert(message);
}


// ------------------------------------------------------------------------
// ------------------------------------------------------------------------


function generate_applet_tags_default()
{
    var dimensions = get_applet_dimensions();
    var width  = dimensions["width"];
    var height = dimensions["height"];
    generate_applet_tags("appletDiv", width, height);
}


// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

function get_version_title()
{
    var poetTitle = "The PO.DAAC Ocean ESIP Tool (POET)"; 

    var propsFilename = "poet_applet.vers";
    var versionParams = getPropertiesFromFile(propsFilename);
    if (versionParams)
    {
         poetVer = versionParams["poet.version"];
         if (poetVer)
             poetTitle = poetTitle + " v" + poetVer;
    }
     
    return poetTitle;
}

// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

function writePoetTitle()
{   
    var titleStr = get_version_title();
    if (titleStr)
        document.write( "" + titleStr + "");
    else
        document.write("The PO.DAAC Ocean ESIP Tool (POET)");
}




// ------------------------------------------------------------------------
// ------------------------------------------------------------------------

