var clickIndex = 0;
var atomColor = "cpk";
var buildAtom = "C";
var jmolDebugOn = false;
var bkgdColor = "black";
var setEcho = "set echo top left;font echo 16 sansserif;color echo yellow;"
var grps = "define ~CAH carbon or hydrogen;define ~methylC carbon and connected(4) and connected(3,hydrogen);define ~methylH hydrogen and connected(~methylC);define ~CH3 ~methylC or ~methylH;define ~methyleneC carbon and connected(4) and connected(2,hydrogen);define ~methyleneH hydrogen and connected(~methyleneC);define ~CH2 ~methyleneC or ~methyleneH;define ~methineC carbon and connected(4) and connected(1,hydrogen);define ~methineH hydrogen and connected(~methineC);define ~CH ~methineC or ~methineH;define ~CR4 carbon and connected(4,carbon);define ~sp3N nitrogen and connected(3) and not connected(2,oxygen) and not connected(3,oxygen);define ~sp2N (nitrogen and connected(2)) or (nitrogen and connected(2,oxygen)) or (nitrogen and connected(3,oxygen));define ~spN nitrogen and connected(1);define ~sp3C carbon and connected(4);define ~sp2C carbon and connected(3);define ~spC carbon and connected(2);define ~spO oxygen and connected(~spC);define ~sp2O oxygen and connected(1) and not ~spO;define ~carbonylC ~sp2C and connected(~sp2O);define ~carbonylO ~sp2O and connected(~carbonylC);define ~CO ~carbonylC or ~carbonylO;define ~RCCR carbon and connected(triple,carbon);define ~hydroxylO oxygen and connected(hydrogen) and connected(carbon and not ~carbonylC);define ~hydroxylH hydrogen and connected(~hydroxylO);define ~OH ~hydroxylO or ~hydroxylH;define ~ROH ~OH;define ~carboxylicacidC ~carbonylC and connected(~CAH) and connected(2,oxygen) and connected(1,oxygen and connected(hydrogen));define ~carboxylicacidO oxygen and connected(~carboxylicacidC);define ~carboxylicacidOH hydrogen and connected(~carboxylicacidO);define ~carboxylicacidH hydrogen and connected(~carboxylicacidO);define ~RCO2H ~carboxylicacidC or ~carboxylicacidO or ~carboxylicacidH;define ~esterC ~carbonylC and connected(~CAH) and connected(2,oxygen) and not connected(oxygen and connected(hydrogen));define ~esterO oxygen and connected(~esterC);define ~aldehydeC ~carbonylC and connected(1,carbon) and connected(1,hydrogen);define ~aldehydeH hydrogen and connected(~carbonylC);define ~aldehydeO oxygen and connected(~aldehydeC);define ~RCHO ~aldehydeC or ~aldehydeH or ~aldehydeO;define ~ketoneC ~carbonylC and connected(2,carbon);define ~ketoneO ~carbonylO and connected(~ketoneC);define ~R2CO ~ketoneC or ~ketoneO;define ~etherO oxygen and connected(2,carbon);define ~R2CCR2 carbon and connected(double,carbon);define ~amideC ~carbonylC and connected(~CAH) and connected(nitrogen);define ~amideN nitrogen and connected(~amideC);define ~amideO oxygen and connected(~amideC);define ~RCONR2 ~amideC or ~amideN or ~amideO;define ~anhydrideO oxygen and connected(2,~carbonylC);define ~anhydrideC carbon and connected(~anhydrideO);define ~anhydrideOO oxygen and connected(~anhydrideC);define ~ROCOCOR ~anhydrideO or ~anhydrideC or ~anhydrideOO;define ~ROR ~etherO and not (~ROCOCOR or ~RCO2R);define ~RCO2R (~esterC or ~esterO) and not ~ROCOCOR;define ~NR3 ~sp3N and not connected(sulfur) and not ~RCONR2;";
var rotationPicOn = false;
var inversionPicOn = false;
var colorPicOn = true;
var buildPicOn = false;
var bondOrderPicOn = false;
var deletePicOn = false;
var deleteBndPicOn = false;
var fragRotPicOn = false;
var bondOrder = "1";
var jmolVar1 = "";
var jmolVar2 = "";
var jmolVar3 = "";
var jmeString = "";
var compView = false;
var mediaIntro = "";
var animOn = false;
var appletSize = 310;
var breakAtom1 = "";
var breakAtom2 = "";
r[0] = "Welcome to the ISU CheMagic USM O=CHem Virtual Molecular Model Kit. The model kit is designed to be used as a lecture presentation tool and a medium for directed virtual model kit experiments. Clicking the green line-item help links above will present some useful hints about the menu items in each line. The stoichiometric formula of the active model is dislpayed in the calculator field at the top of the page. See the <a href=\"../calculator/\" target=\"_blank\">calculator instructions</a> for more information.<br /><br /><h4>*Jmol: an open-source Java viewer for chemical structures in 3D. <a href=\"http://www.jmol.org/\" target=\"_blank\">www.jmol.org</a></h4>";
r[1] = "To change the color of an atom in a loaded molecule, click an atom color radio button. After an atom color radio button is selected, any model atom clicked will change to that color. Setting the <a href='http://en.wikipedia.org/wiki/CPK_coloring' target='_blank'>cpk</a> button (gray) results in the standard Corey, Pauling, Kultin color for the atom types subsequently clicked. The cpk colors are the default color in newly loaded models. Any atom color that is click-changed can be returned to its default cpk color by selecting the cpk radio button and clicking the atom. The default background color, black, can be changed by clicking the Background link.";
r[2] = "By clicking the appropriate link, a model can be displayed as Wireframe or Ball&amp;Stick. Clicking the VDW link will display the van der Waals surface for the loaded molecule. The vdw surface area in Angstroms<sup>2</sup> will also be printed in the model window. Clicking the MEP link will display the Map of Electrostatic Potential for Index Page and Select menu molecules.";
r[3] = "Clicking the Measure Torsion link will initiate a dialog in the model window that prompts the user to click 4 atoms to define and display a dihedral angle. Clicking the Measure Angle link will initiate a dialog in the model window that prompts the user to click 3 atoms to define and display a bond angle. The Measure Distance link will display a model window dialog prompting the user to click 2 atoms. The distance between these atoms will be displayed on the screen.";
r[4] = "There are five clean-up links. Clicking the Erase link removes text that may have accumulated in the model window. Clicking Clean removes text and measurements. Clicking Reset loads returns the model to its default load state. Clicking the Reload link reloads the page in its default state. All work on the page will be lost! Clicking the UFF link will do a <a href='http://en.wikipedia.org/wiki/Force_field_%28chemistry%29' target='_blank'>Universal Force Field</a> energy minimization calculation on the loaded structure.";
r[5] = "Clicking the Set Rotation link will initiate a dialog in the model window that prompts the user to click 2 bonded atoms to define an axis of bond rotation. Once this axis is defined repeated clicking of the Rotate link will rotate <b>one</b> of the bonded groups relative to the other about this axis in 10 degree intervals. Clicking the Image link will capture a jpeg picture of the model window. The image will be loaded in a new window. This feature works in most browsers, but it does not work in MSIE < 8.0. Clicking the Measure link displays instructions for measureing bond lengths, bond angles, and torsional angles.";
r[6] = "For advanced users with a knowledge of Jmol Script and JavaScript, the Script Command field can be used the enter and run scripts. Clicking the Run link will execute commands typed into the field. In addition, the Script Command field can be used to load 3-D structures drawn in ChemSketch. Click the ChemSketch link for more information.";
r[7] = "The select menus of the MM and MO Libraries contain the atomic coordinate files for over 300 molecules that can be loaded into the viewer. These files can also be accessed from the Index Page. The files in the MM Library contain partial atomic charge data. The files in the MO Library contain calculated partial atomic charge and molecular orbital. User drawn models can also be loaded by clicking the Draw Structure link. The ChemSketch link can me used to load structures drawn in ChemSketch. Click the ChemSketch link for more information.";
r[8] = "Clicking either the Molecular Editor link or the More Tools link will display connected pop up menus that include all of the Jmol Virtual Model Kit's tools, including links to several useful molecular animations.<br /><br />The molecular editor allows the user to build large molecules from smaller molecules by a click atom replacement process. The molecular editor gives the virtual model kit the true feel and utility of a traditional molecular model kit.";

r[9] = "<b>Link Help:</b><br />Clicking the Copy link captures the model in its current state. Clicking the Paste link will return the model in this state to the model window. The Paste link will restore the copied model even if another molecule has been loaded into the model window during the interval between Copy and Paste.";
r[10] = "<b>Link Help:</b><br />Double clicking any atom in a model will start a measurement sequence. A second atom double click will end the sequence. There are three scenarios: 1) Two clicked atoms (i.e. two double clicks) will measure the distance between atoms; 2) Three clicked atoms will measure the resulting defined angle; 3) Four clicked atoms will measure the resulting defined torsional angle. All measurements are printed in the model window.";
r[11] = "<b>Link Help:</b><br />Click two adjacent atoms to define a bond. Click slowly! A click that moves the model even slightly will not be registered as an atom identification click. To confirm that an atom click was successful, the clicked atom will flash briefly. After the bond is defined, repeated clicking of the Rotate link will rotate one of the bonded groups relative to the other about this axis in 10 degree intervals. Alternatively, the bond order of this bond can be changed in the Molucular Editor and Other Tools menu.";
r[12] = "<b>Link Help:</b><br />Loading a model from ChemSketch is a 6 step ChemSketch 2D process:<br />1) Draw the structure in ChemSketch 2D.<br />2) Select the structure and click the 3D optimize (not 3D viewer) button.<br />3) Copy the structure to the clipboard.<br />4) Return to this viewer Web page.<br />5) Paste the structure in the Script Command field.<br />6) Click the ChemSketch link.";
r[13] = "<b>Link Help:</b><br />After a structure is drawn and loaded, Jmol will add missing hydrogen atoms and minimize the universal force field (UFF). Occasionally (e.g. terminal alkenes and primary amines), Jmol will add two coincident hydrogen atoms. Thus the model appears to be missing a hydrogen atom. If this occurs, add the two hydrogen atoms explicitly to the JME structure.<br /><br />Note: The default drawing status of the X atom is hydrogen.";
r[14] = "<b>Link Help:</b><br />Clicking the File link displays the Jmol console. The upper window of the console contains the data file for the loaded model. The actual Jmol command for this file display is <b class='red'>console on;show file</b>. The file displayed in the console may be copy/pasteted into a text file for use in other model display software.";
r[15] = "<b>Link Help:</b><br />Click three contiguous atoms to define a carbon atom configuration inversion. Click slowly! A click that moves the model even slightly will not be registered as an atom identification click. To confirm that a rotation atom click was successful, the clicked atom will flash briefly. The &quot;inversion&quot; is really accomplihed by swapping two atoms on the target carbon atom. <b>The target carbon atom must be the second atom clicked.</b> The first and third atom clicks will be the swapped atoms.";

function execScript(script) {
    var scpt = script;
    if (scpt.indexOf("select ~") > -1) {
        jmolScript(grps, jmSuffix);
    }
    if (scpt.substring(0, 1) == "~") {
        eval(scpt.substring(1, scpt.length));
    }
    else {
        scpt = scpt.replace("flash", "color fuchsia;delay .7;color cpk");
        jmolScript(setEcho, jmSuffix);
        jmolScript(scpt, jmSuffix);
    }
}

function processPick(appNum, messageString, indexNum) {
    pickApplet = appNum + "";
    setPicApp(parseInt(right(pickApplet, 1)));
    var scriptTxt = "";
    var atomID = messageString + "";
    atomID = atomID.substring(0, atomID.indexOf(" ", 0));
    var atNowColor = jmolEvaluate("{atomindex = _atomPicked}.color", jmSuffix);
    frankOff();
    execScript("frank on");
    //k[clickIndex] = atomID;
    k[clickIndex] = "atomIndex=" + indexNum;
    clickIndex++;
    if (clickIndex == 9) { clearClickIndex(); }
    if (colorPicOn) {
        scriptTxt = "select atomIndex = _atomPicked;color " + atomColor + ";select;";
        execScript(scriptTxt);
    }
    if (rotationPicOn) {
        if (clickIndex == 1) { execScript("select atomIndex = _atomPicked;color fuchsia;delay .3;color " + atNowColor + ";select none;"); }
        if (clickIndex == 2) {
            execScript("select;select atomIndex = _atomPicked;color fuchsia;delay .3;color " + atNowColor + ";select none;echo;");
            rot1[pickApplet] = k[0];
            rot2[pickApplet] = k[1];
        }
    }
    if (inversionPicOn) {
        if (clickIndex == 1) { execScript("select atomIndex = _atomPicked;color fuchsia;delay .1;color " + atNowColor + ";select none;"); }
        if (clickIndex == 2) { execScript("select atomIndex = _atomPicked;color fuchsia;delay .1;color " + atNowColor + ";select none;"); }
        if (clickIndex == 3) {
            execScript("select;select atomIndex = _atomPicked;color fuchsia;delay .1;color " + atNowColor + ";select;echo;");
            rot1[pickApplet] = k[0];
            rot2[pickApplet] = k[1];
            rot3[pickApplet] = k[2];
            scriptTxt = "delay 2;v1 = {" + rot1[pickApplet] + "}.xyz - {" + rot2[pickApplet] + "}.xyz;v2 = {" + rot3[pickApplet] + "}.xyz - {" + rot2[pickApplet] + "}.xyz;theAxis = cross(v1, v2);theAngle = angle(v1, {0 0 0}, v2); select within(BRANCH, {" + rot2[pickApplet] + "}, {" + rot1[pickApplet] + "});rotateSelected MOLECULAR {" + rot2[pickApplet] + "} @theAxis @theAngle;select within(BRANCH, {" + rot2[pickApplet] + "}, {" + rot3[pickApplet] + "});rotateSelected MOLECULAR {" + rot2[pickApplet] + "} @theAxis @{-theAngle};boundbox {*};select *;center selected;echo Please wait while Jmol|optimizes the structure...;minimize;select;delay 5;";
            execScript(scriptTxt);
            colorPic();
            clearRotation();
        }
    }
    if (buildPicOn) {
        jmolFileName[pickApplet] = "crystal";
        execScript("{atomIndex = _atomPicked}.element = '" + buildAtom + "';");
        execScript("select hydrogen and connected({atomIndex = _atomPicked});delete selected;");
        //execScript("set useMinimizationThread false");
        execScript("calculate hydrogens {*};");
        execScript("select *;wireframe 0.15; spacefill 23%;boundbox {*};centerat boundbox;echo Please wait while Jmol|optimizes the structure...;");
        execScript("minimize steps 100;");
        setTimeout("getFormula()", 3000);
    }
    if (bondOrderPicOn) {
        if (clickIndex == 1) { execScript("select atomIndex = _atomPicked;color fuchsia;delay .1;color cpk;select none;"); }
        if (clickIndex == 2) {
            jmolFileName[pickApplet] = "crystal";
            execScript("select;select atomIndex = _atomPicked;color fuchsia;delay .1;color cpk;select none;echo;");
            rot1[pickApplet] = k[0];
            rot2[pickApplet] = k[1];
            execScript("connect (" + rot1[pickApplet] + ") (" + rot2[pickApplet] + ") " + bondOrder);
            if (bondOrder == "DELETE") {
                execScript("minimize"); breakAtom1 = k[0]; breakAtom2 = k[1];
                //execScript("select within(branch, {" + breakAtom1 + "},{" + breakAtom2 + "});{selected}.temperature = 1;select not selected;{selected}.temperature = 2;select;");
                lnkSwitch(20);
            }
            else {
                execScript("select hydrogen and connected(" + rot1[pickApplet] + ");delete selected;");
                execScript("select hydrogen and connected(" + rot2[pickApplet] + ");delete selected;");
                execScript("calculate hydrogens {*};");
                execScript("select *;wireframe 0.15; spacefill 23%;boundbox {*};centerat boundbox;echo Please wait while Jmol|optimizes the structure...;");
                execScript("set minimizationRefresh false");
                execScript("minimize steps 100;");
                rotationPicOn = false; colorPicOn = false; inversionPicOn = false; buildPicOn = true; bondOrderPicOn = false; deletePicOn = false; deleteBndPicOn = false; fragRotPicOn = false;
                clearRotation();
                lnkSwitch(20);
                setTimeout("getFormula()", 3000);
            }
        }
    }
    if (deletePicOn) {
        execScript("delete atomIndex = _atomPicked");
    }
    if (fragRotPicOn) {
        execScript("select within(branch, {atomIndex=1000}, {atomIndex=_atomPicked});flash;");
        //execScript("var x = {atomIndex = _atomPicked}.temperature; select temperature = x;flash;")
        //fragmentXY(fg);
    }
}

function rotate(cyc, del) {
    cyc = (!cyc) ? 10 : cyc;
    var ort = 0;
    if (cyc < 0) { ort = 1; cyc = -1 * cyc; }
    del = (!del) ? .1 : del;
    if (!compView && !animOn) { feedback("<b>Jmol Script Hint:</b><br />When a rotation axis is set by clicking the Set Rotation link, clicking the Rotate link will execute rotation around this axis in 10 degree increments.<br /><br />Typing the command <b>~rotate(+/-integer)</b> in the Script Commands field and clicking the Run link will start an animated rotation of <i> + or - integer</i> degrees. An optional function argument, e.g. <b>~rotate(number,.5)</b>, will change the speed of rotation (default 0.1). Try: <b class='red'>~rotate(360)</b> and <b class='red'>~rotate(-360)</b>."); }
    execScript("echo");
    var rJ = 10;
    var y = parseInt(.1 * cyc);
    if (cyc < 10) { rJ = 1; y = parseInt(cyc); }
    if (cyc < 1) { rJ = .1; y = parseInt(cyc * 10); }
    selectBranch();
    for (var i = 0; i < y; i++) {
        var rotBond = "rotateSelected {" + rot1[pickApplet] + "} {" + rot2[pickApplet] + "} " + rJ + ";delay " + del + "";
        if (ort > 0) { rotBond = "rotateSelected {" + rot2[pickApplet] + "} {" + rot1[pickApplet] + "} " + rJ + ";delay " + del + ""; }
        execScript(rotBond);
    }
}

function selectBranch() {
    var rotBond = "select WITHIN(BRANCH,{" + rot1[pickApplet] + "}, {" + rot2[pickApplet] + "});";
    execScript(rotBond);
}

function clearClickIndex() {
    for (var i = 0; i < 10; i++) { k[i] = 0; }
    clickIndex = 0
}

function clearRotation() {
    rot1[pickApplet] = "";
    rot2[pickApplet] = "";
    rot3[pickApplet] = "";
}

function colorPic() {
    execScript("echo;set picking off;set picking on;set pickcallback 'processPick';axes off;");
    rotationPicOn = false; colorPicOn = true; inversionPicOn = false; buildPicOn = false; bondOrderPicOn = false; deletePicOn = false; deleteBndPicOn = false; fragRotPicOn = false;
}

function surfaceOff() {
    execScript("mo delete;isosurface delete;select *;dots off;dipole off");
}

function copyMol() {
    if (!compView && !animOn) { feedback(r[9]); }
    execScript("select *");
    jmolVar1 = jmolGetPropertyAsString("stateInfo", "all", jmSuffix);
    mepsData["tempHold"] = mepsData[jmol1];
}

function pasteMol() {
    if (!compView && !animOn) { feedback(r[9]); }
    execScript("select *");
    execScript(jmolVar1);
}

function resetParam() {
    execScript("reset;echo;select all;color cpk;isosurface off;dipole off;mo off;measure delete;hover off;background " + bkgdColor + ";moveto 0 1 1 1 66;")
}

function loadMol(x) {
    var midClr = "black";
    var mid2Clr = "red";
    var ldFolder = "models";
    var ldMid = "mid2";
    mepsData[pickApplet] = "false"
    if (x == 2) { midClr = "red"; mid2Clr = "black"; ldFolder = "meps"; ldMid = "mid"; mepsData[pickApplet] = "true" }
    var loadString = "load ../" + ldFolder + "/" + document.getElementById(ldMid).options[document.getElementById(ldMid).selectedIndex].value;
    loadString += ";hover off;background " + bkgdColor + ";moveto 0 1 1 1 66;";
    document.getElementById("mid").style.color = midClr; document.getElementById("mid2").style.color = mid2Clr;
    jmolFileName[pickApplet] = document.getElementById(ldMid).options[document.getElementById(ldMid).selectedIndex].value;
    execScript(loadString); setTimeout("getFormula()", 3000);
}

var picDataString;
var fdbkVar = "";
function getPic() {
    var tempStr = "<img width='350' height='350' src='data:image/jpeg;base64" + "," + picDataString + "' />";
    tempStr = "<p style='text-align: center'><b>JPEG Image of Actve Applet</b><br />" + tempStr + "</p><p style='text-align: left'>The image capture only works with some browsers - e.g. Firefox and Opera. This technique does not work with MSIE &lt; 8. With an appropriate browser, the above jpeg can be saved to a local computer file.</p>"
    feedback(tempStr, fdbkVar);
}

function takePic() {
    feedback("<p style='text-align: center;'><b>The camera has a slow shutter speed. Working...</b></p>", fdbkVar);
    picDataString = eval("document.getElementById('" + pickApplet + "').getPropertyAsString('image')");
    setTimeout("getPic()", 2000);
}

function frankOff() {
    var apHolder = pickApplet;
    if (compView) { setPicApp(2); execScript("frank off;"); }
    setPicApp(1); execScript("frank off;");
    setPicApp(parseInt(right(apHolder, 1)));
}

function clearMedia() {
    slnu = 1;
    feedback(mediaIntro);
}

function doSetRotation(x) {
    x = (!x) ? 2 : x;
    surfaceOff();
    if (!compView && !animOn && x != 3) { feedback(r[11]); }
    execScript("select; wireframe 0.15; spacefill 23%; select ''; set picking on;set pickcallback 'processPick'");
    rotationPicOn = true; colorPicOn = false; inversionPicOn = false; buildPicOn = false; bondOrderPicOn = false; deletePicOn = false; deleteBndPicOn = false; fragRotPicOn = false;
    if (x == 3) { rotationPicOn = false; colorPicOn = false; inversionPicOn = true; buildPicOn = false; bondOrderPicOn = false; deletePicOn = false; deleteBndPicOn = false; fragRotPicOn = false; }
    if (x == 4) { rotationPicOn = false; colorPicOn = false; inversionPicOn = false; buildPicOn = false; bondOrderPicOn = true; deletePicOn = false; deleteBndPicOn = false; fragRotPicOn = false; }
    document.getElementById("cpk").checked = true;
    atomColor = "cpk";
    clearClickIndex();
    clearRotation();
    if (x == 2 || x == 4) { execScript("echo Click two atoms to define the|new bond or bond modification."); }
    if (x == 3) { execScript("echo Click three contiguous atoms to|define the configuration inversion.|The second atom clicked must|be the atom to be inverted."); }
}

function doWireFrame() {
    if (!compView && !animOn) { feedback("<b>Jmol Script Hint:</b><br />The script command sequence <b class='red'>select; wireframe 0.15; spacefill 23%;</b> will set the model to ball &amp; stick. Select/Click-Drag the red text to the Script Command Field and click Run. Changing the two numbers in the command sequence allows complete control over model appearance. The wireframe number is the width of the bond in Angstroms. The spacefill number is the atom size in % of van der Waals radius."); }
    execScript("select; wireframe 0.03; spacefill 1%;")
}

function doBallStick() {
    if (!compView && !animOn) { feedback("<b>Jmol Script Hint:</b><br />The script command sequence <b class='red'>select; wireframe 0.03; spacefill 1%;</b> will set the model to wireframe. Select/Click-Drag the red text to the Script Command Field and click Run. Changing the two numbers in the command sequence allows complete control over model appearance. The wireframe number is the width of the bond in Angstroms. The spacefill number is the atom size in % of van der Waals radius."); }
    execScript("select; wireframe 0.15; spacefill 23%;")
}

function mep(colorScheme) {
    var colorNum = (!colorScheme) ? "1" : "" + colorScheme;
    var colors = "";
    if (colorNum == "1") { colors = "roygb"; }
    if (colorNum == "2") { colors = "low"; }
    if (colorNum == "3") { colors = "high"; }
    if (colorNum == "4") { colors = "rwb"; }
    if (jmolFileName[pickApplet].substring(0, 7) == "crystal" || jmolFileName[pickApplet].substring(0, 9) == "animation" || jmolFileName[pickApplet] == "JmeMolecule") {
        alert("Some files [e.g. edited, crystal, animation, JME, and ChemSketch.] do not contain MM or MO data.");
    }
    else {
        doClean();
        execScript("select *;echo Calculating...;");
        if (!compView && !animOn) { feedback("<b>Jmol Script Hint:</b><br />The map of electrostatic potential (MEP) is set to load as a translucent surface. Once the default MEP is loaded, the command <b class='red'>isosurface opaque;</b> will change the transluscent surface to opaque. The script command <b>~mep(integer)</b> allows the mep to be changed to any one of four color schemes. Click the Molucular Editor and Other Tools link above for more specific information. Select/Click-Drag the red text to the Script Command Field and click Run."); }
        execScript("isosurface COLORSCHEME '" + colors + "'; isosurface resolution 6 MOLECULAR color range -0.05 +0.05 map mep;isosurface translucent;delay 2; echo;");
    }
}

function dipole() {
    if (jmolFileName[pickApplet].substring(0, 7) == "crystal" || jmolFileName[pickApplet].substring(0, 9) == "animation" || jmolFileName[pickApplet] == "JmeMolecule") {
        alert("Some files [e.g. edited, crystal, animation, JME, and ChemSketch.] do not contain MM or MO data.");
    }
    else {
        var setDipole = "dipole on;select;wireframe 0.03;spacefill 1%;isosurface off;dipole calculate bonds;dipole calculate molecular offset 1.0;dipole bonds width 0.05;dipole bonds noCross;dipole bonds offsetSide 0.4";
        if (!compView && !animOn) { feedback("<b>Jmol Script Hint:</b><br />Jmol uses a very crude calcuation to compute bond dipoles:<br />(distance 1,2) * (charge 1 - charge 2) / 2<br />The <b>~dipole()</b> command displays the dipoles as atom colored arrows offset 0.4 Angstroms from the bond. The resulting net dipole is displayed as an orange arrow offset 1 Angstrom from it's molecular position. The Script Command Field command <b class='red'>zoom 150</b> may make the dipoles easier to read."); }
        doClean();
        execScript(setDipole);
    }
}

function doClean() {
    execScript("measure delete;mo off;isosurface off;echo;dipole off;label \"\";");
}

function doVdw() {
    var vdw = "select;isosurface resolution 6 SOLVENT area;isosurface translucent;delay 2;isosurfaceArea = \"vdw surface area = \" + isosurfaceArea % 0 + \" \u212B<sup>2</sup>\";echo @isosurfaceArea";
    if (!compView && !animOn) { feedback("<b>Jmol Script Hint:</b><br />The script command that generated the VDW surface is <b class='red'>isosurface resolution 6 SOLVENT;isosurface translucent;</b>. Here's a variation that adds some color, makes the surface opaque, and increases the resolution: <b class='red'>isosurface resolution 8 SOLVENT;isosurface opaque;color isosurface green;</b>. Select/Click-Drag the red text to the Script Command Field and click Run. The higher resolution surface takes a bit more time to generate."); }
    doClean();
    execScript(vdw);
}

function wyfc() {
    if (!compView && !animOn) { feedback("<b>Jmol Script Hint:</b><br />The dialog box will change the page default background color.<br /><br />The Script Command Field command <b class='red'>background pink</b> will color the existing background pink. Select/Click-Drag the red text to the Script Command Field and click Run. Changing the color in the command allows complete control of an existing model background color."); }
    var clr = prompt("With apologies to Monte Python, what's your favorite color? With your entry below of a common color name, the model background default can be set to any color you want. But be careful. You might be wrong! If the color you enter is too exotic, the background will not change.", "Blue");
    if (clr == "" || clr == null) { clr = bkgdColor; }
    bkgdColor = clr;
    execScript("background " + bkgdColor);
}

function doUFF() {
    if (!compView && !animOn && jmeString == "") { feedback("<b>Jmol Script Hint:</b><br />Clicking the UFF link will do a <a href='http://en.wikipedia.org/wiki/Force_field_%28chemistry%29' target='_blank'>Universal Force Field</a> energy minimization calculation on the loaded structure. For fun, try this: From the MM drop-down select menu, load the 'methane square planar model'. After the model is loaded, click the UFF link.<br /><br />The UFF minimize calculation is used to convert the 2d structures from the Draw Structure link into 3d structures."); }
    doClean();
    if (!animOn) { execScript("echo Please wait while Jmol|optimizes the structure..."); }
    execScript("minimize steps 100;");
    setTimeout("doClean()", 3000);
    jmeString = "";
}

function loadFromString(num) {
    if (!compView && num == 2) { feedback(r[12]); }
    jmolFileName[pickApplet] = "JmeMolecule";
    if (num == 2) { jmeString = document.getElementById("script").value; }
    if (jmeString.length > 100 || jmeString.indexOf("JME 2005") > -1) {
        document.getElementById(pickApplet).loadInlineString(jmeString, "hover off;echo;", false);
        if (num == 1) { execScript("echo Please wait while Jmol|optimizes the structure...;calculate hydrogens;minimize;"); }
        if (num == 2) { execScript("echo Please wait while Jmol|optimizes the structure...;minimize;"); }
        setTimeout("getFormula()", 5000);
    }
}

function playVideo(nm) {
    var x = "500";
    var y = "440";
    var jmolVid = "<p style='text-align: center'><object width='" + x + "' height='" + y + "' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95' id='mediaplayer1'><param name='Filename' value='" + jmolVideoPath + nm + "' /><param name='AutoStart' value='True' /><param name='ShowControls' value='True' /> <param name='ShowStatusBar' value='False' /><param name='ShowDisplay' value='False' /><param name='AutoRewind' value='True' /><embed type='application/x-mplayer2' pluginspage='http://www.microsoft.com/Windows/Downloads/Contents/MediaPlayer/' width='" + x + "' height='" + y + "' src='" + jmolVideoPath + nm + "' filename='" + jmolVideoPath + nm + "' autostart='True' showcontrols='True' showstatusbar='False' showdisplay='False' autorewind='True'></embed></object></p>";
    feedback(jmolVid);
}

function showPicture(tl, nm) {
    var x = "500";
    var y = "400";
    var jmolPid = "<h3 style='text-align: center;'>" + tl + "<br /><img width='" + x + "' height='" + y + "' src='../images/" + nm + "' /></h3>";
    feedback(jmolPid);
}

var slnu = 1
function slideShow(tl, fldr, beg, end) {
    var x = "500";
    var y = "400";
    var prevnu = slnu - 1;
    var prev = "<a href='javascript:nullFunction();' onclick='slnu=" + prevnu + ";slideShow(" + "\"" + tl + "\", " + "\"" + fldr + "\", " + beg + ", " + end + ")'>previous</a>"
    if (prevnu < beg) { prev = "" }
    var prttl = prev + " " + tl + " <a href='javascript:nullFunction();' onclick='slnum=slnu;slideShow(" + "\"" + tl + "\", " + "\"" + fldr + "\", " + beg + ", " + end + ")'>next</a>";
    var jmolPid = "<h3 style='text-align: center;'>" + prttl + "<br /><img width='" + x + "' height='" + y + "' src='../slide_shows/" + fldr + "/s" + slnu + ".jpg' /></h3>";
    if (slnu == end + 1) {
        clearMedia();
    }
    else {
        feedback(jmolPid);
        slnu++;
    }
}

function view(num) {
    num = (!num) ? Math.floor(Math.random() * 6) + 1 : num;
    var front = "if not(showBoundBox);if not(showUnitcell);boundbox on;moveto 2.0 front;delay 1;boundbox off;else;moveto 2.0 front;delay 1;endif;endif;";
    var back = "if not(showBoundBox);if not(showUnitcell);boundbox on;moveto 1.0 front;moveto 2.0 back;delay 1;boundbox off;else;moveto 1.0 front;moveto 2.0 back;delay 1;endif;endif;";
    var left = "if not(showBoundBox);if not(showUnitcell);boundbox on;moveto 1.0 front;moveto 2.0 left;delay 1;boundbox off;else;moveto 1.0 front;moveto 2.0 left;delay 1;endif;endif;";
    var right = "if not(showBoundBox);if not(showUnitcell);boundbox on;moveto 1.0 front;moveto 2.0 right;delay 1;boundbox off;else;moveto 1.0 front;moveto 2.0 right;delay 1;endif;endif;";
    var top = "if not(showBoundBox);if not(showUnitcell);boundbox on;moveto 1.0 front;moveto 2.0 top;delay 1;boundbox off;else;moveto 1.0 front;moveto 2.0 top;delay 1;endif;endif;";
    var bottom = "if not(showBoundBox);if not(showUnitcell);boundbox on;moveto 1.0 front;moveto 2.0 bottom;delay 1;boundbox off;else;moveto 1.0 front;moveto 2.0 bottom;delay 1;endif;endif;";
    if (num == 1) { execScript(left); }
    if (num == 2) { execScript(right); }
    if (num == 3) { execScript(front); }
    if (num == 4) { execScript(back); }
    if (num == 5) { execScript(top); }
    if (num == 6) { execScript(bottom); }
}

function getFormula() {
    try {
        execScript("echo;boundbox {*};centerat boundbox;");
        var info = jmolGetPropertyAsString("moleculeInfo[1].mf", "all", jmSuffix);
        if (info == null || info == "") { info = ""; }
        info = info.substring(info.indexOf("\"") + 1, info.length - 1).split(" ")
        var f = new Array();
        for (var i = 0; i < info.length; i++) {
            f[i] = info[i];
        }
        if (f[0] == "H" && f[2] == "C") { info[0] = f[2]; info[1] = f[3]; info[2] = f[0]; info[3] = f[1]; }
        info = info.join(" ") + " "
        if (info.indexOf(" ") > -1) { document.getElementById("calcDisplay").value = info.replace(/ 1 /g, "").split(" ").join(""); }
    }
    catch (e) {
        execScript("echo;boundbox {*};centerat boundbox;");
    }
}

function getJme() {
    var jme = document.getElementById(jme1).molFile() + "";
    return jme;
}

function openHelpWindow() {
    window.open("../code/jme/helpfs.html", "", "toolbar=no,menubar=no,scroolbars=no,resizable=yes,width=500,height=600")
}

function doAnim(x) {
    animOn = true;
    if (jmolGetPropertyAsString("modelInfo.models[1].title", "all", jmSuffix).indexOf(x) < 0) { execScript("load '../models/animation!" + x + "_an.mol';"); }
    eval(x + "()");
}

function cyclohexane_chair() {
    view(1);
    execScript("select atomno=12;color lemonchiffon;select atomno=16;color lemonchiffon;select atomno=7;color lemonchiffon;");
    execScript("select atomno=9;color lemonchiffon;select atomno=18;color lemonchiffon;select atomno=13;color lemonchiffon;delay 2;");
    var scpt = "draw plane1 200 PLANE (atomno=2) (atomno=3) (atomno=5)(atomno=6);color $plane1 green translucent; delay 2;select atomno=1;";
    scpt += "color red; delay 3; select atomno=1, atomno=7, atomno=8; invertSelected PLANE $plane1; select atomno=7, atomno=8; invertSelected;";
    scpt += "echo Boat; delay 3; select atomno=4; color red; delay 3; select atomno=4, atomno=13, atomno=14; invertSelected PLANE $plane1;";
    scpt += "select atomno=14, atomno=13; invertSelected;echo New Chair; delay 3; select carbon; color cpk; echo Calculating UFF Minimum.|Note axial/equitorial H flip.; delay 3";
    execScript(scpt);
    doUFF();
    animOn = false;
}

function sn2() {
    execScript("load '../models/animation!sn2_an.mol'");
    execScript("select atomno=4;color red;select atomno=5;color yellow;");
    view(6);
    execScript("moveto 1 1 1 0 45;delay 2;");
    var scpt = "for(var k=0;k < 2;k++){for(var i=0;i < 8;i++){connect;select fluorine,chlorine,hydrogen;translateSelected {.1 0 0};delay .3};";
    scpt += "for(var j=0; j < 8 ; j++){connect;select fluorine,chlorine,hydrogen;translateSelected {-.1 0 0};delay .3}};";
    scpt += "for(var l=0;l < 8;l++){connect;select fluorine,chlorine,hydrogen;translateSelected {.1 0 0};delay .3};";
    execScript(scpt);
    animOn = false;
}

function ethane_conformers() {
    rot1[pickApplet] = "atomno=1"
    rot2[pickApplet] = "atomno=2"
    execScript("load '../models/animation!ethane_conformers_an.mol'");
    execScript("select atomno=3;color lemonchiffon;select atomno=7;color lemonchiffon;set defaultTorsionLabel '%0.0VALUE \u00B0';");
    view(6);
    execScript("moveto 1 1 1 0 45;delay 2;measure (atomno=3) (atomno=1) (atomno=2) (atomno=7);echo We rotate about the C-C axis by 410 degrees...;delay 4");
    rotate(410, .3);
    execScript("echo We stop at this partial eclipse position,|and minimize the UFF.|Note the angle of least energy after minimization.;delay 3;minimize;");
    animOn = false;
}

function appletLoadedA() {
    getFormula();
    jmolScript("frank on;", "01");
}

function appletLoadedB() {
    jmolScript("frank off;", "02");
}

function setBuildChain(atm) {
    execScript("axes off;echo;set picking off;set picking on;set pickcallback 'processPick'");
    rotationPicOn = false; colorPicOn = false; inversionPicOn = false; buildPicOn = true; deletePicOn = false; deleteBndPicOn = false; fragRotPicOn = false;
    buildAtom = atm;
    var scpt = "echo Clicked atoms will be replaced|by " + atm + " atoms.;select; wireframe 0.15; spacefill 23%;";
    execScript(scpt);
}

function loadBaseMol(bsmol) {
    execScript("axes off");
    bsmol = "Load '../models/" + bsmol + ".mol';hover off;";
    execScript(bsmol);
    setTimeout("getFormula()", 1000);
}

function setDelete(x) {
    if (x == 1) { execScript("axes off;"); rotationPicOn = false; colorPicOn = false; inversionPicOn = false; buildPicOn = false; deletePicOn = true; deleteBndPicOn = false; fragRotPicOn = false; }
    if (x == 0) { colorPic(); }
}

function setFragXY(x) {
    if (x == 1) { execScript("axes off"); rotationPicOn = false; colorPicOn = false; inversionPicOn = false; buildPicOn = false; deletePicOn = false; deleteBndPicOn = false; fragRotPicOn = true; view(3); execScript("axes on"); }
    if (x == 0) { colorPic();execScript("axes off;");}
}

function setPicApp(x) {
    if (x == 1) { pickApplet = jmol1; jmSuffix = "01"; }
    if (x == 2) { pickApplet = jmol2; jmSuffix = "02"; }
}

function toggleSize() {
    if (compView) {
        jmolResizeApplet(appletSize, "01");
        jmolResizeApplet(appletSize, "02");
        if (appletSize == 310) {
            appletSize = 250;
        }
        else {
            appletSize = 310;
        }
    }
}

function doProp(pId) {
    if (pId == "partialcharge" && (jmolFileName[pickApplet].substring(0, 7) == "crystal" || jmolFileName[pickApplet].substring(0, 9) == "animation" || jmolFileName[pickApplet] == "JmeMolecule")) {
        alert("Some files [e.g. edited, crystal, animation, JME, and ChemSketch.] do not contain MM or MO data.");
    }
    else {
        var chrg = "select; wireframe 0.03; spacefill 1%; spacefill 1%;label \"%-8.3[" + pId + "]\";";
        doClean();
        execScript(chrg);
    }
}

function lnkSwitch(num) {
    var w = ""
    var c = "e" + num.toString()
    for (var i = 0; i < 17; i++) {
        w = "e" + i.toString();
        objColor(w, "#ffffcc");
    }
    if (num == 0) { objColor("e0", "pink"); objColor("e1", "pink"); }
    if (num > 0 && num < 11) { objColor("e0", "pink"); objColor(c, "pink"); }
    if (num > 10 && num < 20) { objColor(c, "pink"); }
    setFragXY(0);
    colorPic();
    setDelete(0);
 }