/*******************************************************************************
**      Copyright (c) 1995-2008 Work of U.S. Government.
**      No rights may be assigned.
**
** LIST OF CONDITIONS
** Redistribution and use of this program in source and binary forms, with or
** without modification, are permitted for any purpose (including commercial
** purposes) provided that the following conditions are met:
**
** 1.  Redistributions of source code must retain the above copyright notice,
**     this list of conditions, and the following disclaimer.
**
** 2.  Redistributions in binary form must reproduce the above copyright notice,
**     this list of conditions, and the following disclaimer in the
**     documentation and/or materials provided with the distribution.
**
** 3.  In addition, redistributions of modified forms of the source or binary
**     code must carry prominent notices stating that the original code was
**     changed, the author of the revisions, and the date of the change.
**
** 4.  All publications or advertising materials mentioning features or use of
**     this software are asked, but not required, to acknowledge that it was
**     developed at the NASA Langley Research Center in Hampton, VA, or at the
**     National Climatic Data Center in Asheville, NC, and to credit the
**     contributors.
**
** 5.  THIS SOFTWARE IS PROVIDED BY THE GOVERNMENT AND THE CONTRIBUTORS "AS IS"
**     WITH NO WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED.  In no event
**     shall the Government or the Contributors be liable for any damages
**     suffered by the users arising out of the use of this software, even if
**     advised of the possibility of such damage.
**
********************************************************************************
**
** DISCLAIMER:
**     This work was prepared as an account of work by employees of an agency
**     of the United States Government.  Neither the United States Government
**     nor any of its employees, makes any warranty, express or implied, or
**     assumes any liability or responsibility for the accuracy, completeness,
**     or usefulness of any information, apparatus, product, or process
**     disclosed, or represents that its use would not infringe privately-
**     owned rights.  Reference herein to any specific commercial products,
**     process, or service by trade name, trademark, manufacturer, or
**     otherwise, does not necessarily constitute or imply its endorsement,
**     recommendation, or favoring by the United States Government.  The views
**     and opinions of authors expressed herein do not necessarily state or
**     reflect those of the United States Government, and shall not be used
**     for advertising or product endorsement purposes.
**
********************************************************************************
** Authors: B. R. Barkstrom
**          National Climatic Data Center
**          151 Patton Av.
**          Asheville, NC  28801  USA
**          Phone:  +1 828/271-4412
**          e-mail: bruce.barkstrom@noaa.gov
**
**          S. P. Forsythe-Newell
**          National Climatic Data Center
**          151 Patton Av.
**          Asheville, NC  28801  USA
**          Phone:  +1 828/271-4485
**          e-mail: shane.forsythe-newell@noaa.gov
**
**          K. P. Roberts
**          National Climatic Data Center
**          151 Patton Av.
**          Asheville, NC  28801  USA
**          Phone:  +1 828/271-4083
**          e-mail: ken.roberts@noaa.gov
**
** Organization: RSAD, National Climatic Data Center
**
** Revision History:
**  6/11/08	B. R. Barkstrom, S. P. Forsythe-Newell, K. P. Roberts
**     - SDS Web Server, version 2.1 approved. This release included
**	  some redesign for all 2.0 release pages which enhanced
**	  functionality, architecture, site navigation, 508 compliance, 
**	  general security, uniformity and appearance. Many existing features
**	  were enhanced to include a National Research Council and GCOS 
**	  database update for ECVs associated with climate change. Further, 
**	  this release had some new online interfaces added that improved 
**	  Subject Matter Experts input for ECV impact values, associated 
**	  benefits and also provided potential analysis of group (community)
**	  tendencies using algorithms developed by Dr. Barkstrom. Functional
**	  concept mapping was revised that employed state-of-the-art applied
**	  principles from game theory and architecture which was integrated
**	  into the Site Map, or Navigational Map. This significantly enhanced
**	  Website navigation, functionality as well as provided future insight
**	  as to Website capabilities. The 2.1 release conformed better to NCDCs
**	  standard Header requirements than the 2.0 release. Specific
**	  improvements were: (1)ECV's were expanded from forty (version 2.0)
**	  to eighty-three that took into account all the the GCOS mandated 
**	  Essential Climate Variables; (2)A functional Proof-Of-Concept online
**	  international mechanism for SMEs (Subject Matter Experts) and 
**	  Decision-Makers to access, review and submit climate change
**        information about ECV's (and later CDRs); (3)CCSP Assistance in
**        prioritizing measurement capabilities for climate observations; (4)A
**        venue to promote NCDCs SDS Project within National and International 
**	  Scientific Conferences; (5)Database Content reflecting NRC and GCOS
**	  instruments, platforms and networks; (6)Site Map or Navigation-Concept
**	  Map (NavMap) design and functionality that includes: functional 
**	  concept mapping, state-of-the-art game theory and architectural 
**	  application principles, Milestone and Profile inventory pop-ups; and
**	  interacting hierarchal project links. This task merged modern and 
**	  futuristic gaming architecture principles with online scientific 
**	  website programming and oracle database technologies; (7)Added ECV 
**	  Priority matrix pages, (8)Added ECV's as mandated by GCOS; (9)A SME
**	  (Subject Matter Expert) Input functionality and Analysis Tool 
** 	  (SME-Alias profiles use complex algorithms and ANOVA clustering 
**	  analysis architecture integrating community vectors). Improvements
**        include SME Impact and Priority value input that is archived and
**        averaged together for display in ECV/CDR Matrices. SMEs may change
**        multiple impact values simultaneously and view community vector
**        clustering values; (10)Vocabulary, Acronyms Index pages, all
**        corresponding new static pages (a fail-safe mechanism for loss of
**        database connectivity); and under-Construction pages where applicable;
**        (11)Redesigned and enhanced functionality of Login, Archive, ECV
**        impact Dual Matrix pages and Site Map (Navigation-Concept Map);
**        (12)Revised security features on all pages (usage of prepared
**        statements, modified database object queries, and improved input
**        validation object for all String input and standardized regular
**        expressions usage); (13)Improved Section 508 compliance, uniformity of
**        content and page design, page and dB inter-functionality for all
**        pages; (14)Created pop-ups showing input records for each set of ECV
**        impacts (tabulated format) on GECV pages; (16) Static Pages that
**        provide: (A)Reduced potential performance hits on the SDS Server,
          (B) Reduced security vulnerability, (C)Quicker access
**	  for non-SME's to SDS Server information, (D) A graceful and useful
**	  alternative (local and remote) for read-only access in the event of
**	  potential database connectivity failure, and (E) Generation of static
**	  pages On-The-Fly in a real-time environment, as required;
**        (17)scrollable page description functionality;
**	  
**  12/13/07	B. R. Barkstrom, S. P. Forsythe-Newell, K. P. Roberts
**     - SDS Web Server, version 2.0 approved. The 2nd release introduced
**        two major new additions: (1) a site navigational map (absent in
**        version 1.0) and (2) a Technology Readiness Level (TRL) Matrix that
**        related ECVs to existing technologies (both In-Situ and Satellite).
**        The NavMap, or navigational map, was the initial introduction of
**        concept mapping (absent in version 1.0) to users that allowed a more
**        intuitive mechanism for easily navigating the website and still
**        enabled one to retain one's perspective and navigational functionality
**        of the website. The second major addition, the Technology Readiness
**        Level (TRL) page (absent in version 1.0), provided a functional
**        proof-of-concept tool. The TRL page provided an initial awareness to
**        users of ECVs to current technology readiness levels (satellite and
**        In-Situ) in conjunction with a concurrent display of weighted ECV
**        totals and their impact priorities. There were other numerous
**        improvements to the initial release that included a page mode
**        indicator that depicted which mode (Active Database or Read Only) of
**        the SDS Website the user was currently engaged in online. The Read
**        Only mode was designed for non-interactive users (non Subject Matter
**        Experts) and as a default fail-safe mechanism in the event the
**        database was unavailable. Unregistered users, users not requiring
**        interaction with the SDS database, or unregistered users were enabled
**        to view the SDS website and data without eliciting a system
**        performance reduction. Registered users (logged in) were abled
**	  to interact with the SDS database more efficiently. This release also 
**	  consisted of translation and revision of origional code and creation
**        of new code.
**
**  8/30/07	B. R. Barkstrom, S. P. Forsythe-Newell, K. P. Roberts
**     - SDS Web Server, version 1.0 approved.  The 1st release for the 
**	  Scientific Data Stewardship Project that was primarily used as an 
**	  initial test bed that included: three ECV Matrices, a Satellite 
**	  Heritage Diagram, and numerous other pages related to ECV's,
**        satellites and instruments. This first release provided an initial
**        online prototype that was a functional proof-of-concept tool which
**        enabled users with an increased perception of awareness about
**        quantifiable prioritized ECVs as they related under numerous
**        IPCC/Societal impact areas. These ECV impact values (strong, medium,
**        low) were represented via an ECV Matrix Web page. This ECV Matrix
**        cross referenced forty (40) ECV's to Impact Areas (IPCC and Societal)
**        with these weighted values and also showed weighted averages under a
**        Totals column in the far right hand side of the page. A Satellite
**	  Heritage Diagram also was included in this release that provided a 
**	  scrollable temporal GANNT-like depiction of list of satellites. The 
**	  Satellite Heritage page also provided the satellite status via icons 
**	  within the time lines of the diagram. The list of satellite platforms 
**	  also enabled users to expand out a list of instruments under each 
**	  satellite within this same diagram, thus enabling a viewable list of 
**	  instruments associated with each satellite platform without losing the
**	  time perspective. This enabled users to view gaps and overlaps of 
**	  satellite platforms and instruments through time. In this first
**        release, instruments were listed under each satellite platform
**        however, were not portrayed in the GANNT time lines. This release also
**        consisted of translation and revision of origional code and creation
**        of new code.
**
**  8/6 - 7/7	B. R. Barkstrom, S. P. Forsythe-Newell	
**     - SDS Web Server, preversion 1.0 work consisted of translating/revision  
**	  of origional programming code and creation of new code.
**
**  2/2 - 6/96  B. R. Barkstrom
**     - Created first major revision to allow us to analyze the data from
**        both the data panel and the payload panel surveys.  This required
**        us to improve the overall editing capability on the front end of
**        the input.  Many of the panel members did not complete their forms,
**        and there were several confusing questions.  Thus, the initial stages
**        were improved, so that we could accept ``raw'' data from the
**        questionaire without affecting the use of the SVD approach for
**        analyzing correlated variations among questions.  Found that the
**        Numerical Recipe version of SVD did not like rows of data with all
**        zeros.  Also added clustering and index question analyses.
**  11/24/95    B. R. Barkstrom
**     - Created original version of program in manner of d2r9 to analyze
**        data from questionaire done on Data Panel.  The original responses
**        were entered into a spreadsheet, where they we examined, some of
**        the rows were made into logarithmic variable.  From the new
**        information, found the mean and standard deviation, and converted
**        into the basic data that would be needed for a covariance matrix.
**        Then, we could use the program from d2r9 to do a SVD and print
**        that back out.
**
********************************************************************************
** AnalysisOfVariance
**
** Purpose:
**    Quest_Anal is intended to provide a standard statistical clustering
**     of responses to a questionaire.  We assume that the columns entering
**     this program are the answers of a single individual to questions on the
**     survey results.  The rows correspond to particular questions.
**     A SVD of this matrix produces the number of reliably distinguishable
**     groups.  The diagonal matrix w contains the standard deviations
**     attribuable to these groups.  By taking the dot product of the transpose
**     of u and the individual columns of the original matrix, we obtain the
**     degree to which the component aligns with that individual's response.
**     By taking the component with the largest alignment, we obtain the
**     classification for that individual.  We can use much of the structure
**     set up by the test program d2r9 to do the analysis.  In the original
**     application, we had expected to work with a spreadsheet, to which
**     we want to return this analysis.  Thus, we write this material out
**     to a final file when we have finished.
*******************************************************************************/

//******************************************************************************
//  Pop-up Functions
//******************************************************************************

var navWindow = 0;

// Display NAV Map.
function showNavMap(root) {
    if (navWindow != 0) {
        navWindow.focus();
    } else {
        navWindow = window.open(root + "sitemap.html",
          "sdsNavMap", "status = 1, height = 435, width = 555, resizable = 0, " +
          "dependent = 1, scrollbars = 0, screenX=" + ((screen.width / 2) - 215) +
          ", screenY=" + ((screen.height / 2) - 215));
    }
}

// Display pop-up with description and links for the selected ECV.
function showEcvDescription(ecvId, root) {
    ecvWindow = window.open(root + "ecvinfo.html?id=" + ecvId, "",
        "status = 1, height = 480, width = 535, resizable = 0, " + 
        "dependent = 1, screenX=" + ((screen.width / 2) - 215) + ", screenY=" +
        ((screen.height / 2) - 215));
}

// Display pop-up with bulleted list of impact reasons for the selected ECV and
// IPCC impact area.
function showEcvReasons(ecvId, areaId, areaType, root) {
    ecvWindow = window.open(root + "ecvreasons.html?id=" + ecvId + "&area=" + areaId + "&type=" + areaType, "",
        "status = 1, height = 455, width = 430, resizable = 0, " + 
        "dependent = 1, screenX=" + ((screen.width / 2) - 215) + ", screenY=" +
        ((screen.height / 2) - 215));
}

// Display pop-up with bulleted list of impact reasons for the selected ECV and
// IPCC impact area.
function showFeasibilityReasons(ecvId, root) {
    ecvWindow = window.open(root + "feasibilityreasons.html?id=" + ecvId, "",
        "status = 1, height = 455, width = 430, resizable = 0, " + 
        "dependent = 1, screenX=" + ((screen.width / 2) - 215) + ", screenY=" +
        ((screen.height / 2) - 215));
}

// Display pop-up with detailed information on selected satellite.
function showSatInfo(satId, root) {
    satWindow = window.open(root + "satinfo.html?id=" + satId, "",
        "status = 0, height = 465, width = 700, resizable = 1, " +
        "scrollbars = 1, dependent = 1, screenX=" + ((screen.width / 2) - 215) +
        ", screenY=" + ((screen.height / 2) - 215));
}

// Display pop-up with detailed information on selected instrument.
function showInstrInfo(instrId, root) {
    instrWindow = window.open(root + "instrumentinfo.html?id=" + instrId, "",
        "status = 0, height = 465, width = 700, resizable = 1, " +
        "scrollbars = 1, dependent = 1, screenX=" + ((screen.width / 2) - 215) +
        ", screenY=" + ((screen.height / 2) - 215));
}

// Display pop-up with detailed information on selected data product.
function showProductInfo(productId, root) {
    productWindow = window.open(root + "dataproductinfo.html?id=" + productId, "",
        "status = 0, height = 500, width = 700, resizable = 1, " +
        "scrollbars = 1, dependent = 1, screenX=" + ((screen.width / 2) - 215) +
        ", screenY=" + ((screen.height / 2) - 215));
}

// Display heritage legends.
function showLegend(page, root) {
    clusterWindow = window.open(root + page + "legend.html",
      "legends", "height=450, width=450, scrollbars=1, resizable=1");
}

// Display ECV user input clusters.
function showVectors(root) {
    clusterWindow = window.open(root + "smeinput/vectors.html",
      "clusters", "height=500, width=450, scrollbars=1, resizable=1");
}

// Display number of users per community vector.
function showUsersPerVector(root) {
    clusterWindow = window.open(root + "smeinput/userspervector.html",
      "clusters", "height=300, width=450, scrollbars=1, resizable=1");
}

// Show a term description.
function showDefinition(id, root) {
    clusterWindow = window.open(root + "definition.html?id=" + id,
      "legends", "height=455, width=430, scrollbars=1, resizable=1");
}

//******************************************************************************
//  Drop-Down Navigation Functions
//******************************************************************************

// Shows the selected drop-down navigation menu.
function showDropNav(dropNavId) {
    
    // Reset display.
    hideDropNav();
    document.getElementById('dropNavCategory' + dropNavId).style.backgroundColor = '#4455A5';
    document.getElementById('dropNavPagesMain').style.backgroundColor = '#4455A5';
    document.getElementById('dropNavCategoryLink' + dropNavId).style.color = '#FFFFFF';
    
    // Populate drop-down navigation DIV with page selections.
    document.getElementById("dropNavPagesMain").innerHTML = dropNavLinks[dropNavId - 1];
}

// Hide drop-down navigation menu.
function hideDropNav() {
    
    // Clear current page selections.
    document.getElementById("dropNavPagesMain").innerHTML = "";
    
    // Reset colors for all selections.
    document.getElementById('dropNavPagesMain').style.backgroundColor = '#C4CBE7';
    for (i = 0; i < dropNavLinks.length; ++i) {
        document.getElementById('dropNavCategory' + (i + 1)).style.backgroundColor = 'transparent';
        document.getElementById('dropNavCategoryLink' + (i + 1)).style.color = '#4455A5';
    }
}

//******************************************************************************
//  Page Display Functions
//******************************************************************************

// Toggles CDR matrix color displays from color to grayscale.
function convertColors() {
    
    // Reset display.
    if (getStyle(".cdrCompleted").style.backgroundColor == getStyle(".cdrCompletedColor").style.backgroundColor) {
        getStyle(".cdrCompleted").style.backgroundColor = getStyle(".cdrCompletedGrayscale").style.backgroundColor;
        getStyle(".cdrInProcess").style.backgroundColor = getStyle(".cdrInProcessGrayscale").style.backgroundColor;
    } else {
        getStyle(".cdrCompleted").style.backgroundColor = getStyle(".cdrCompletedColor").style.backgroundColor;
        getStyle(".cdrInProcess").style.backgroundColor = getStyle(".cdrInProcessColor").style.backgroundColor;
    }
}

//******************************************************************************
//  Other Functions
//******************************************************************************

// Locates the style rule with the given name.
function getStyle(ruleName) {
    
    // Iterate through all stylesheets.
    for (i = document.styleSheets.length - 1; i >= 0; --i) {
        
        // Get collection of rules for current sheet.
        var rules;
        try {
            if (navigator.appName == "Netscape") {
                rules = document.styleSheets[i].cssRules;
            } else {
                rules = document.styleSheets[i].rules;
            }
        } catch (err) {
            
            // Current style sheet is not directly accessible.
            rules = [];
        }
        
        // Iterate through all style definitions.
        for (j = 0; j < rules.length; ++j) {
            
            // Check if current style rule name matches.
            if (rules[j].selectorText.toUpperCase() == ruleName.toUpperCase()) {
                return rules[j];
            }
        }
    }
}

// Locates the style rule with the given name in given stylesheet.
function getStylesheetStyle(sheetName, ruleName) {
    
    // Iterate through all stylesheets.
    for (i = document.styleSheets.length - 1; i >= 0; --i) {
        
        // Check if the desired stylesheet has been located.
        if (document.styleSheets[i].href != null && document.styleSheets[i].href != "") {
            var url = document.styleSheets[i].href.split("/");
            if (url[url.length - 1] == sheetName) {
                
                // Get collection of rules for current sheet.
                var rules;
                try {
                    if (navigator.appName == "Netscape") {
                        rules = document.styleSheets[i].cssRules;
                    } else {
                        rules = document.styleSheets[i].rules;
                    }
                } catch (err) {
                    
                    // Current style sheet is not directly accessible.
                    rules = [];
                }
                
                // Iterate through all style definitions.
                for (j = 0; j < rules.length; ++j) {
                    
                    // Check if target rule has been found.
                    if (navigator.appName != "Netscape" && ruleName.indexOf(",") != -1) {
                        if (rules[j].selectorText.toUpperCase() == ruleName.split(",")[0].toUpperCase()) {
                            return rules[j];
                        }
                    } else {
                        if (rules[j].selectorText.toUpperCase() == ruleName.toUpperCase()) {
                            return rules[j];
                        }
                    }
                }
            }
        }
    }
}
