// Centrifuge 2.4 Template

function getEnginePath(frames)
{
    if( frames == null ) return null;
    //    alert("Checking: " + getFramePath(frames));
    var enginePath = null;
    if( frames.frames )  // first, make sure it's a frame set
    {
        for( var i=0; i<frames.length; i++ )
        {
            //            if( frames[i].oEngineLocation )
            if( enginePath == null )
                enginePath = getEnginePath(frames[i].frames);
        }
    }

    //    alert("Found so far: " + enginePath);
    if( enginePath == null && frames && frames.name && frames.name == "engineFrame" )
        enginePath = frames;

    return enginePath;
}

function getFramePath(oLoc)
{
    refname = oLoc.name;
    oRef = oLoc.parent;
    while( oRef.name && oRef != top )
    {
        refname = oRef.name + "." + refname;
        oRef = oRef.parent;
    }
    if( refname == "" )
    {
        refname = "top";
    }
    else
    {
        refname = "top." + refname;
    }
    //alert(refname);
    return refname;
}


// sniff out the browser.  This is a very simple test.  For a more complete test, see sniffer.js
ns = (top.document.layers)?true:false;
ie = (top.document.all)?true:false;

bEngineLoaded = false;
//oEngineLocation = top.engineFrame; //DOM location of engine frame/window relative to oSelfLocation
//oEngineLocation = getEnginePath(top); //DOM location of engine frame/window relative to oSelfLocation
currentSearch = this;
oEngineLocation = null;
while( oEngineLocation == null && currentSearch != top )
{
    currentSearch = currentSearch.parent;
    oEngineLocation = getEnginePath(currentSearch);
}
sSelfLocation = getFramePath(this); //A string representing the DOM location of this frame/window relative to oEngineLocation
oSelfLocation = this; //DOM location of this frame/window
sFormLocation = 'document.CentrifugeForm'; //A string representing the DOM location of the form that contains all of the Centrifuge Controls relative to oSelfLocation
sSelfURL = window.location.href; //URL of this frame/window
aRefreshFrames = new Array(); //Array of DOM locations of all frames/windows to refresh relative to oSelfLocation
//sActiveLayer = ''; //String representing the ID of the layer/block to bring to the front after refresh.
sReloadCmd = sSelfURL + '_ReloadCmd';
refreshScreen = false; // to allow controls to force reload of screen

if( document.configure != null )  // check for presence of array
{
    for( var index=0; index<configure.length; index++ )
    {
        var item = configure[index];
        var objectToConfigure = item[0];
        var objectValue = item[1];
        var object = eval(objectToConfigure);
        object = objectValue;
    }
}

if( oEngineLocation )
{
    if( oEngineLocation.bEngineLoaded )
    {
        bEngineLoaded=true;
        //Clear out Previously Registered Controls before registering new ones on this page.
        oEngineLocation.ClearControls(sSelfLocation);
        oEngineLocation.RegisterPage(oSelfLocation, sSelfURL);
        //sActiveLayer = oEngineLocation.GetActiveLayer(sSelfURL);
    }
}

function showState(bXML)
{
    var w=window.open('', 'MyWin', 'width=600,height=420,resizable=no');
    w.document.writeln('Engine ' + String(oEngineLocation.GetVersion()) + ' Model ' + String(oEngineLocation.GetCurrentStateID()) + ' is ' + ( oEngineLocation.CheckValidity() ? 'valid' : 'invalid' ) + '<BR />');
    w.document.writeln('To save the CR, cut and paste the following into your favorite editor.<br />');
    w.document.writeln('<form name=tempform><textarea name=cr readonly=true rows=20 cols=70></textarea>');
    w.document.tempform.cr.value= ( arguments.length < 1 || bXML ) ? oEngineLocation.toXML() : oEngineLocation.toINI();
    //w.document.tempform.cr.select();
}

function storeHistory(frameName,str)
{
    dt = new Date();
    timestamp = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds() + ":" + dt.getMilliseconds();
    if( bEngineLoaded )
    {
        oEngineLocation.addDynamicProperty('History',
                                           String(oEngineLocation.getDynamicProperty('History')) +
                                           timestamp + '\t' + frameName + '\t' + str + '\n');
    }
}

function getHistory()
{
    sval = '';
    if( bEngineLoaded )
    {
        sval = String(oEngineLocation.getDynamicProperty('History'));
    }
    return sval;
}

function clearHistory()
{
    if( bEngineLoaded )
    {
        oEngineLocation.addDynamicProperty('History', '');
    }
}

function makeFocusCmd(ControlName)
{
    if( !bEngineLoaded ) return;
    cmd = '';
    if( typeof(ControlName) == 'undefined' || ControlName == null )
    {
        return cmd;
    }
    if( ControlName.length == 0 )
    {
        return cmd;
    }
    ControlName = "document.CentrifugeForm." + String(ControlName);
    if( eval(ControlName + ".focus") != null )
    {
        cmd = ControlName + ".focus()";
    }
    else
    {
        //} else if (eval(ControlName + "[0].focus") != null) {
        var controlarray = eval(ControlName);
        if( controlarray != null )
        {
            var lastidx = controlarray.length - 1;
            var cmdpre = ControlName + "[" + lastidx + "].focus";
            if( eval(cmdpre) != null )
            {
                cmd = cmdpre + "()";
            }
        }
        //cmd = ControlName + "[0].focus()";
    }
    return cmd;
}

function HandlePageSubmit(sScrControlID)
{
    oEngineLocation.addDynamicProperty(sReloadCmd, makeFocusCmd(sScrControlID));
    oEngineLocation.HandleSubmit(oSelfLocation, sScrControlID);
}

function MM_reloadPage(init)
{  //reloads the window if Nav4 resized
    if( init==true ) with( navigator )
        {
            if( (appName=="Netscape")&&(parseInt(appVersion)==4) )
            {
                document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage;
            }
        }
    else if( innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH ) location.reload();
}

function restoreFocus()
{
    if( !bEngineLoaded ) return;
    recmd = oEngineLocation.getDynamicProperty(sReloadCmd);
    if( recmd == null )
    {
        return;
    }
    recmd = String(recmd);
    if( recmd == '' )
    {
        return;
    }
    if( ie )
    {
        eval('try {eval(recmd)} catch( e ) { }');
    }
    else
    {
        window.onError = "window.onError=\"\";return true;";
        eval(recmd);
        window.onError = "";
    }
}

// cross-browser function to show the active layer
function showdiv(divname)
{
    if( ns )
    {
        document.layers[divname].visibility="show";
    }
    if( ie )
    {
        document.all[divname].style.visibility="visible";
    }
}

function unslash(thing)
{
    thing = thing.replace(/.*\\/g,""); //remove backslashes, if any
    thing = thing.replace(/.*[\/]/g,""); //remove forward slashes, if any
    return thing;
}

// Save a working copy of the current state.
// The user is redirected back to nextPage after the save.
function saveWorking(projectTitle)
{
    oEngineLocation.ProcessDirtyStates();
    oCCR = new ActiveXObject("RebsCCR.FileIO");
    ccr = oEngineLocation.toCR();
    var filename = "";
    if( projectTitle == null || projectTitle == "" )
        projectTitle = "Please Select a file to save into";
    stat = oCCR.save_file(ccr, filename, projectTitle);
    if( stat.substring(0, 5) == "ERROR" )
    {
        alert(stat);
        stat = "";   // simulate cancel button
    }
    return stat;
}

function loadWorking()
{
    var oCCR = new ActiveXObject("RebsCCR.FileIO");
    var ccr = oCCR.load_file("", "Please select your Centrifuge Project");
    if( ccr == "" ) return;
    var error = ccr.substring(0, 5);
    if( error == "ERROR" )
    {
        alert(ccr);
    }
    else if( ccr != "" )
    {
        var activeModel = oEngineLocation.GetCurrentStateID();
        oEngineLocation.loadAllStatesFromCRString(ccr);
        oEngineLocation.SetActiveModel(activeModel, false);
        location.reload();
    }
}

// Netscape-specific. This function is harmless if browser is IE.
MM_reloadPage(true);

// check to see if user wants to unslash sSelfURL
if( document.unslashSelfURL != null && document.unslashSelfURL )
    sSelfURL = unslash(sSelfURL);


function keyDown(events)
{
    k = (ns) ? events.which : window.event.keyCode;
    if (k == 13)
    {
        return false;  // don't submit
    }
}

//BUG 2729 This also disables enter for textarea, which is not desired.  changed form onsubmit to return false...
//document.onkeydown = keyDown; // work together to analyze keystrokes
//if (ns) document.captureEvents(Event.KEYDOWN|Event.KEYUP);


