// Created by John Whitney: Thu May 27 10:29:46 EDT 2004
// Addition of layers, pan, and USA region by E. Mancini and Jack Glendening  July 2009
// *** PROGRAMMING NOTES ***
// underscore after a variable indicates it is global in scope
// underscore before a variable indicates it belongs to an object

var baseUrl_ = "http://www.drjack.info";
var randUniq_ = "jw" + (new Date()).getSeconds().valueOf();

//var randUniq_ = "jw" + Math.random() * (new Date()).getSeconds().valueOf();
var imgs_ = new Array();
var myDefBMI_ = null;
var constSz_ = null; // null constSz_ means use img's orig size
var loop_ = null;
var errImgUrl_ = baseUrl_ + "/BLIP/NAM/USA/blipmap.not.available.png";

var tzEast_ = "18z";
var tzWest_ = "18z";
var tzArr_ = new Array();
tzArr_["NC"] = tzEast_;
tzArr_["NE"] = tzEast_;
tzArr_["SC"] = tzEast_;
tzArr_["SE"] = tzEast_;
tzArr_["NW"] = tzWest_;
tzArr_["CANV"] = tzWest_;
tzArr_["GP"] = tzWest_;
tzArr_["SW"] = tzWest_;
tzArr_["OKTX"] = tzWest_;
tzArr_["USA"] = tzEast_;

// new arrays for key label
var imgsize_ = new Array();
imgsize_["CANV"] = 611;
imgsize_["NW"] = 734;
imgsize_["SW"] = 729; // 729,726 for RUC,NAM
imgsize_["GP"] = 611;
imgsize_["OKTX"] = 579;
imgsize_["NC"] = 550; // 548,552 for RUC,NAM
imgsize_["SC"] = 570; // 568,572 for RUC,NAM
imgsize_["NE"] = 590; // 589,591 for RUC,NAM
imgsize_["SE"] = 728; // 729,726 for RUC,NAM
imgsize_["USA"] = 2377;

var noncompositetitleTop_ = new Array(10);
noncompositetitleTop_["CANV"] = 8;
noncompositetitleTop_["NW"] = 8;
noncompositetitleTop_["SW"] = 8;
noncompositetitleTop_["GP"] = 8;
noncompositetitleTop_["OKTX"] = 8;
noncompositetitleTop_["NC"] = 8;
noncompositetitleTop_["SC"] = 8;
noncompositetitleTop_["NE"] = 8;
noncompositetitleTop_["SE"] = 8;
noncompositetitleTop_["USA"] = 96;

var noncompositetitleBot_ = new Array(10);
noncompositetitleBot_["CANV"] = 70; //56;
noncompositetitleBot_["NW"] = 85; //56;
noncompositetitleBot_["SW"] = 83; //56;
noncompositetitleBot_["GP"] = 69; //56;
noncompositetitleBot_["OKTX"] = 67; //56;
noncompositetitleBot_["NC"] = 62; //56;
noncompositetitleBot_["SC"] = 64; //56;
noncompositetitleBot_["NE"] = 66; //58;
noncompositetitleBot_["SE"] = 82; //64;
noncompositetitleBot_["USA"] = 156; //152;
var compositetitleTop_ = new Array(10);
compositetitleTop_["CANV"] = 16;
compositetitleTop_["NW"] = 30; //28;
compositetitleTop_["SW"] = 16;
compositetitleTop_["GP"] = 16;
compositetitleTop_["OKTX"] = 16;
compositetitleTop_["NC"] = 16;
compositetitleTop_["SC"] = 16;
compositetitleTop_["NE"] = 16;
compositetitleTop_["SE"] = 16;
compositetitleTop_["USA"] = 154;

var compositetitleBot_ = new Array(10);
compositetitleBot_["CANV"] = 46;
compositetitleBot_["NW"] = 60; //62;
compositetitleBot_["SW"] = 54;
compositetitleBot_["GP"] = 46;
compositetitleBot_["OKTX"] = 44; //46;
compositetitleBot_["NC"] = 46;
compositetitleBot_["SC"] = 44;
compositetitleBot_["NE"] = 44; //46;
compositetitleBot_["SE"] = 54;
compositetitleBot_["USA"] = 184;

var compositescaleTop_ = new Array(10);
compositescaleTop_["CANV"] = 586;
compositescaleTop_["NW"] = 612;
compositescaleTop_["SW"] = 700; //696;
compositescaleTop_["GP"] = 586;
compositescaleTop_["OKTX"] = 560; //555;
compositescaleTop_["NC"] = 495; //490;
compositescaleTop_["SC"] = 545; //550;
compositescaleTop_["NE"] = 570; //565;
compositescaleTop_["SE"] = 700;
compositescaleTop_["USA"] = 1626; //1652;
var compositescaleBot_ = new Array(10);
compositescaleBot_["CANV"] = 610;
compositescaleBot_["NW"] = 641;
compositescaleBot_["SW"] = 760; //725;
compositescaleBot_["GP"] = 609;
compositescaleBot_["OKTX"] = 578;
compositescaleBot_["NC"] = 513;
compositescaleBot_["SC"] = 568;
compositescaleBot_["NE"] = 588;
compositescaleBot_["SE"] = 727;
compositescaleBot_["USA"] = 1658; //1700;
//older_method? ns = (document.layers)? true:false
//older_method? mie = (document.all)? true:false
var ie5_ = (document.all && document.getElementById);
var ns6_ = (!document.all && document.getElementById);

var opacity_ = 30;
//CANV var opacity_ = 70;
var maxOpacity_ = 100;
var minOpacity_ = 0;

//EM: globals
var ckyVal_;
var imwid_; //the width of the base image
var imhei_;
var basGeoTop_;
var basMap_ = "2";
var defCooky_ = "no";
var snap_ = "no";
var ino_ = "out";
var sBMap_ = 'yes';

var mainCookieName_ = "MyUniviewerDefaults2";
var reViewCookieName_ = "MyUniviewerReViewList2";

var cnf_ = 'no'; //no cookie indicator
var snapd_ = 'no'; //have cookies been saved this session
var maxImgSaved_ = 20; //max images saved in ReView. 4kb max cookie size, 15 urls ~ 2kb
var frameSz_ = '600x600'; //new adjust outer frame size
var framePos_ = '0x0'; //frame left & top corner
// *********************************************************************
// *********************************************************************
function snapShot() {

    var bmi = currentBMI().clone();

    // get blip img url and remove rnd suffix
    var i0 = bmi.getUrl();
    var i1 = i0.indexOf("?");
    var imgSsrc = i0.substring(0, i1);

    var docId3 = document.getElementById('DivOverlay'); //parent div of blipmap
    var docId5 = document.getElementById("DivFixedWindow"); // Outer Div frame
    var ctrlLoc = docId3.style.left + "," + docId3.style.top; //'DivOverlay'
    var imgBLMap = (sBMap_ == 'no') ? 'no' : imgBLMap = (basGeoTop_ == "Geo") ? "geographicmap.png" : "topographicmap.png";

    var sCB = saveCheckboxes(document.popUpChooser);

    snap_ = imgSsrc + "&constSz=" + constSz_ + "&ctrlLoc=" + ctrlLoc + "&opacy=" + opacity_ + "&imgBLMap=" + imgBLMap + "&frameSz=" + frameSz_ + "&framePos=" + framePos_ + "&" + sCB;
    cookey_._cname = mainCookieName_;
    // JACK TEST6 ADDITION
    alert("Current settings will be used at next Startup" + "\n" + "(assuming cookies are enabled in your browser)");
    cookey_.setCookie(snap_);

    //EM added ReView list save
    cookey_._cname = reViewCookieName_;
    if (loop_._bmiArr.length != 0) {
        var lpArr = "";
        for (var i = 0; i < loop_._bmiArr.length; i++) { //start from 1?
            // get blip img url and remove rnd suffix
            var i0 = loop_._bmiArr[i].getUrl();
            var i1 = i0.indexOf("?");
            var imgg = i0.substring(0, i1);
            //   if (i==0)imgg=imgSsrc; // save the current bmi on top
            lpArr = lpArr + imgg + '&';
            if (i == maxImgSaved_) break; // 4kb max cookie size, 15 urls ~ 2kb
        }

        lpArr = lpArr + loop_._current; //NEW
        cookey_.setCookie(lpArr);
    } else {
        cookey_.delCookie();
    }
    snapd_ = 'yes';
    cnf_ = 'no';
}
var reVuPtr_; //NEW
function getReView() {
    cookey_._cname = reViewCookieName_;
    ckyVal_ = cookey_.getCookie();
    if (!ckyVal_ || ckyVal_.indexOf('http') == -1 || ckyVal_.indexOf('NaN') > -1) {
        cnf_ = 'yes';
        return;
    }
    var lpArr = ckyVal_.split('&');
    //  var imageObj = new Image();  //image preload
    for (var i = 0; i < lpArr.length - 1; i++) { //NEW
        //    imageObj.src=lpArr[i] + '?' + randUniq_;  //image preload
        var bmi = urlToBMI(lpArr[i]);
        loop_.insert(bmi);
    }
    reVuPtr_ = parseInt(lpArr[lpArr.length - 1]) ; //NEW bitwise OR turns into integer
}

//EM : new function to retrieve data from cookie value
function getCookVal(s) {
    var t, r;
    t = s.indexOf('=') + 1;
    r = s.substring(t);
    return r;
}



function setOnExit() { //EM : new function to set cookies on onunload if nothing has been previously saved
    if (snapd_ == 'yes' || cnf_ == 'no') {
        return; // auto save last image only if no cookies made this session & no cookies initially found
    }    

try {
    var bmi = currentBMI().clone();

    // get blip img url, basemap, location, opacity & size
    var i0 = bmi.getUrl();
    var i1 = i0.indexOf("?");
    var imgSsrc = i0.substring(0, i1);

    var docId3 = document.getElementById('DivOverlay'); //parent div of blipmap
    var ctrlLoc = docId3.style.left + "," + docId3.style.top;
    var imgBLMap = (sBMap_ == 'no') ? 'no' : imgBLMap = (basGeoTop_ == "Geo") ? "geographicmap.png" : "topographicmap.png";

    //save state of checkboxes
    var sCB = saveCheckboxes(document.popUpChooser);

    snap_ = imgSsrc + "&constSz=" + constSz_ + "&ctrlLoc=" + ctrlLoc + "&opacy=" + opacity_ + "&imgBLMap=" + imgBLMap + "&frameSz=\"600x600\"" +  "&framePos=\"0x0\""  + "&" + sCB;
 
    
    cookey_ = new Cookey();
    cookey_._cname = mainCookieName_;
    cookey_.setCookie(snap_);

    //save last image
    cookey_._cname = reViewCookieName_;
    lpArr = imgSsrc + '&';
    cookey_.setCookie(lpArr);    
}
catch (err){
cookey_ = new Cookey();
cookey_._cname = mainCookieName_;    
 cookey_.delCookie();

}

}

// START OF PAN-OVERLAY ADDITION --------------------------------------------------------------
// function colorSet(newColors)  EM: changed funct name to match html A href : "javascript:colorrangeSet("
function colorrangeSet(newColors) {
    var bmi = currentBMI().clone();
    bmi._png = newColors;
    bmi.sho();
    loop_.insert(bmi);
}



function changeOpacity(byOpacity) {
    opacity_ = opacity_ + byOpacity;
    if (opacity_ >= 100) opacity_ = 100;
    if (opacity_ <= 0) opacity_ = 0;
    setOpacityDO(opacity_);
}

//em new
//http://www.drquincy.com/blog/cross-browser-javascript-image-opacity-changing-function/
function setOpacityDO(opacity) {
    var docId = document.getElementById('DivOverlay').style;
    docId.filter = "alpha(opacity=" + opacity + ")";
    docId.opacity = opacity / 100;
    docId.MozOpacity = opacity / 100;
    docId.KhtmlOpacity = opacity / 100;
    opacity_ = opacity;
}



function toggleOpacity() {
    if (opacity_ <= 50) {
        setOpacityDO(100);
        opacity_ = 100;
    } else {
        setOpacityDO(0);
        opacity_ = 0;
    }
}



function makeVis(img) {
    img.style.visibility = 'visible';
    imwid_ = parseInt(img.height);
    imhei_ = parseInt(img.width);
}

// EM modified functions to swap basemap based on current bmi
function setBaselayerTopo(regn) {
    sBMap_ = "yes";
    // if (opacity_==100)setOpacityDO(30);
    var bmi = currentBMI().clone();
    var model = bmi._model;
    var region = (regn != "k") ? regn : bmi._region;
    var bkgMap = 'http://www.drjack.info/BLIP/' + model + '/' + region + '/topographicmap.png';
    var docID = document.getElementById('ImgBaselayer');
    if (docID.src == bkgMap) {
        docID.style.visibility = 'visible';
        return;
    }
    docID.src = bkgMap;
    basMap_ = bkgMap;
    basGeoTop_ = 'Topo';
    bmi.sho();
    if (regn == 'k' && opacity_ == 100) setOpacityDO(30);
}



function setBaselayerGeo(regn) {
    sBMap_ = "yes";
    // if (opacity_==100)setOpacityDO(30);
    var bmi = currentBMI().clone();
    var model = bmi._model;
    var region = (regn != "k") ? regn : bmi._region;
    var bkgMap = 'http://www.drjack.info/BLIP/' + model + '/' + region + '/geographicmap.png';
    var docID = document.getElementById('ImgBaselayer');
    if (docID.src == bkgMap) {
        docID.style.visibility = 'visible';
        return;
    }
    docID.src = bkgMap;
    basMap_ = bkgMap;
    basGeoTop_ = 'Geo';
    bmi.sho();
    if (regn == 'k' && opacity_ == 100) setOpacityDO(30);
}


function noBaselayer() {

    var docID = document.getElementById('ImgBaselayer');
    docID.src = "";
    setOpacityDO(100);
    sBMap_ = "no";

}

// Positioning adapted from script by Andreas Berger - andreas_berger@bretteleben.de (version 20081005)
// *** start of parameters ***
//USA
//below moved up
//var imwid_ = 2377; //the width of your pic
//var imhei_ = 2377; //the height of your pic
//CANV imwid_=611; //the width of your pic
//CANV imhei_=611; //the height of your pic
//panoverlay
var panwid_ = 600; //the width of the shown area
var panhei_ = 600; //the height of the shown area
//panoverlay-      panwid_=800; //the width of the shown area
//panoverlay-      panhei_=500; //the height of the shown area
//original = speed=40 & move=20 => CANV_too_fast_for_jack - but_for_others??
var speed_ = 80; //timeout between moves; set it lower to increase speed_
var move_ = 10; // movement at one step in pixels
//USA var move_ = 20; // movement at one step in pixels
//CANV move_=5; // movement at one step in pixel
//  *** end of parameters ***
/// initialization
var tim_ = 0;
var noscroll_ = true;

// to start with window center at center of image
initLeft = (panwid_ - imwid_) / 2;
initTop = (panhei_ - imhei_) / 2;

// to start with window NW corner at NW corner image
initLeft = 0;
initTop = 0;


function sr() {
    if (!noscroll_) {
        var docId = document.getElementById('DivBaseLayer');
        var now = parseFloat(docId.style.left);
        now -= move_;
        docId.style.left = now + "px";
        document.getElementById("DivOverlay").style.left = docId.style.left;
        tim_ = setTimeout("sr()", speed_);
    }
}


function sl() {

    var docId = document.getElementById('DivBaseLayer');
    if (!noscroll_) {
        var now = parseFloat(docId.style.left);
        now += move_;
        docId.style.left = now + "px";
        document.getElementById("DivOverlay").style.left = docId.style.left;
        tim_ = setTimeout("sl()", speed_);
    }
}


function sb() {
    var docId = document.getElementById('DivBaseLayer');
    if (!noscroll_) {
        var now = parseFloat(docId.style.top);
        now -= move_;
        docId.style.top = now + "px";
        document.getElementById("DivOverlay").style.top = docId.style.top;
        tim_ = setTimeout("sb()", speed_);
    }
}


function st() {
    var docId = document.getElementById('DivBaseLayer');
    if (!noscroll_) {
        var now = parseFloat(docId.style.top);
        now += move_;
        docId.style.top = now + "px";
        document.getElementById("DivOverlay").style.top = docId.style.top;
        tim_ = setTimeout("st()", speed_);
    }
}


function stoppan() {

    clearTimeout(tim_);
    noscroll_ = true;
}



function adjustImgSzS() {
    if (!noscroll_) {
        speed_ = 80;
        var fctr = (ino_ == "out") ? 1.05 : 0.95;
        var docId1 = document.getElementById('DivBaseLayer'); //parent div of basemap
        var docId2 = document.getElementById("DivOverlay"); //parent div of blipmap
        var docId3 = document.getElementById('ImgBaselayer'); //base map - child of DivBaseLayer
        var docId4 = document.getElementById('ImgBliplayer'); //blipmap - child div of DivOverlay
        var docId5 = document.getElementById("DivFixedWindow"); // Outer Div frame
       
        var docId5L =  docId5.style.left;        
            docId5L =  parseFloat(docId5L.split("p")[0]);
        var docId5T = docId5.style.top;       
             docId5T =  parseFloat(docId5T.split("p")[0]);
        var nowL = docId1.style.left; // + docId5L; //docId1
            nowL = parseInt(nowL.split("p")[0]);
        
        var nowT = docId1.style.top; // + docId5T; //docId1        
           nowT = parseInt(nowT.split("p")[0]);

        var ht, wdth;

        if (constSz_ == null) {
            var bmi = currentBMI();
            var img = bmi.getImg();
            imgIncompleteMsg(img);
            if (img.complete) {
                // use img dim sizes
                ht = img.height;
                wdth = img.width;
            }
        }
        //  new else
        else {
            ht = +constSz_.split("x")[0];
            wdth = +constSz_.split("x")[1];
            //ht = +frameSz_.split("x")[0];
            //wdth = +frameSz_.split("x")[1];
        }

        ht *= fctr;
        wdth *= fctr;
       constSz_ = "" + ht + "x" + wdth;
        //alert("adjust constSz_:"+constSz_);  // debug

        docId3.style.height = ht + "px"; //// 'ImgBliplayer' =  blipmap - child of DivOverlay
        docId3.style.width = wdth + "px";

        docId4.style.height = docId3.style.height; // 'ImgBaselayer' = base map  - child of DivBaseLayer
        docId4.style.width = docId3.style.width;

var now5L = parseFloat(docId5.style.left);
var now5T = parseFloat(docId5.style.top);
 var cz5D2 = +frameSz_.split("x")[0] / 2; 
        //jack - adjust to keep centered (for 600x600 frame)#        
//nowT = parseInt( fctr * ( nowT - 300 ) ) + 300 ;

        nowL = parseInt(fctr * (nowL - cz5D2)) + cz5D2;
     nowT = parseInt(fctr * (nowT - cz5D2)) + cz5D2;        

        //nowL = parseInt(fctr * (nowL - 300)) + 300;
       // nowT = parseInt(fctr * (nowT - 300)) + 300;
        docId1.style.left = nowL + "px";
        docId1.style.top = nowT + "px";
        docId2.style.left = docId1.style.left;
        docId2.style.top = docId1.style.top;

        // bmi.sho();
        tim_ = setTimeout("adjustImgSzS()", speed_);

    }
    speed_ = 80;
}

//***************FRAME RESIZING********************///
function adjustFrameSz() {
    //min frame size
    if (+frameSz_.split("x")[0] < 200 && ino_ == "in") return; //200px smallest frame size
    if (!noscroll_) {
        speed_ = 80;
        var fctr = (ino_ == "out") ? 1.05 : 0.95;
        var docId1 = document.getElementById('DivBaseLayer'); //parent div of basemap
        var docId2 = document.getElementById("DivOverlay"); //parent div of blipmap
        var docId3 = document.getElementById('ImgBaselayer'); //base map - child of DivBaseLayer
        var docId4 = document.getElementById('ImgBliplayer'); //blipmap - child div of DivOverlay
        //new Window resize
        var docId5 = document.getElementById("DivFixedWindow"); // Outer Div frame
        var nowT = parseInt(docId5.style.top);
        var nowL = parseInt(docId5.style.left);

        var ht, wdth, fsD2;

        ht = parseInt(frameSz_.split("x")[0]);
        wdth = parseInt(frameSz_.split("x")[1]);

        ht *= fctr;
        wdth *= fctr;

        frameSz_ = "" + ht + "x" + wdth;
        constSz_ = frameSz_;
        framePos_ = "" + nowT + "x" + nowL;
        //constSz_ = "" + parseInt(ht) + "x" + parseInt(wdth);
        //alert("adjust constSz_:"+constSz_);  // debug

        docId5.style.height = "" + ht + "px"; //Outer Div frame
        docId5.style.width = "" + wdth + "px";

        docId1.style.left = "" + (nowL *= fctr) + "pt";
        docId1.style.top = "" + (nowL *= fctr) + "pt";
        docId2.style.left = docId1.style.left;
        docId2.style.top = docId1.style.top;

        docId3.style.height = docId5.style.height; //// 'ImgBliplayer' =  blipmap - child of DivOverlay
        docId3.style.width = docId5.style.width;
        docId4.style.height = docId3.style.height; // 'ImgBaselayer' = base map  - child of DivBaseLayer
        docId4.style.width = docId3.style.width;

        //docId2.style.left = docId1.style.left;
        //docId2.style.top = docId1.style.top;
        // bmi.sho();
        tim_ = setTimeout("adjustFrameSz()", speed_);

    }
    speed_ = 80;
}

// *********************************************************************
// *********************************************************************
//EM this function isn't used see embedinHTML
function panoverlayStartup() {
    //forOpacityDisplay+         var opacity_ = 30;
    var docId = document.getElementById('DivBaseLayer');
    // *** SPECIFY INITIAL CENTRAL LOCATION ***
    //UTAH docId.style.left= -200 ;   docId.style.top= -500 ;
    //KENTUCKY
    docId.style.left = -1200;
    docId.style.top = -700;
    document.getElementById("DivOverlay").style.left = docId.style.left;
    document.getElementById("DivOverlay").style.top = docId.style.top;
    // TEMPORARY KLUDGES ??
    // force map size to 600x600 ??? i dont know if this works, since need to start from wrong size to see if change occurs ???
    var ht = 600;
    var wdth = 600;

}

//  END  OF PAN-OVERLAY ADDITION --------------------------------------------------------------
function Cookey() {
    this._cname = mainCookieName_;
    //old this._cname = "MyDefaultBlipMap";
}
Cookey.prototype.setCookie = function (value) {
    //alert("setCookie() value:"+value); // debug
    var expiry = new Date();
    // Set expiration date to 10 years from now.
    expiry.setTime(expiry.getTime() + (24 * 60 * 60 * 1000 * 365 * 10));
    document.cookie = this._cname + "=" + escape(value) + "; expires=" + expiry.toGMTString();
}
Cookey.prototype.getCookie = function () {

    var cname = this._cname; // + "=";
    //http://techpatterns.com/downloads/javascript_cookies.php
    // this fixes an issue with the old method, ambiguous values
    // with this test document.cookie.indexOf( name + "=" );
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f
    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');

        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == cname) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

Cookey.prototype.delCookie = function (name) {
    document.cookie = this._cname + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}



function Loop() {
    this._bmiArr = new Array();
    this._current = -1;
    this._toglDirection = -1;
}
Loop.prototype.current = function () {
    if (this._bmiArr.length == 0) {
        //alert("current() _bmiArr empty"); // debug
        return null;
    }
    var bmi = this._bmiArr[this._current];
    if (bmi != null) {
        //alert("current() url:"+bmi.getUrl());  // debug
    } else {
        alert("current() bmi is null:" + bmi);
    }
    return bmi;
}
Loop.prototype.toggle = function () {
    if (this._toglDirection > 0) {
        this._toglDirection *= -1;
        return this.next();
    } else {
        this._toglDirection *= -1;
        return this.prev();
    }
}
Loop.prototype.next = function () {
    this._toglDirection = -1;
    this._current++;
    if (this._current == this._bmiArr.length) {
        this._current = 0;
    }
    return this.current();
}
Loop.prototype.prev = function () {
    this._toglDirection = 1;
    if (this._current == 0) {
        this._current = this._bmiArr.length;
    }
    this._current--;
    return this.current();
}
Loop.prototype.zap = function () {
    var bmi = this.current();
    if (bmi == null) return null; //new
    this._bmiArr.splice(this._current, 1);
    if (this._current == this._bmiArr.length) {
        this._current = 0;
    }
    return this.current();

}
Loop.prototype.insert = function (bmi) {
    if (this._bmiArr.length <= 0) {
        this._current = -1 + this._bmiArr.push(bmi);
    } else if (!bmi.equals(this.current())) {
        this._current++;
        this._bmiArr.splice(this._current, 0, bmi);
    } else {
        //alert("will not try to reinsert here"); // debug
    }
    //new
    if (document.getElementById('reCnt')) document.getElementById('reCnt').innerHTML = loop_._current + 1 + '/' + loop_._bmiArr.length; //innerHTML
}



function BMI(model, region, prefix, param, time, png) {

    //TESTING - FIX USA REGION ?
    // region = 'USA';
    this._model = model;
    this._region = region;
    this._prefix = prefix;
    this._param = param;
    this._time = time;
    this._shown = false;
    this._png = png;

}
BMI.prototype.toString = function () {
    return this._model + "  " + this._region + "  " + this._param + "  " + this._prefix + "  " + this._time;
}

BMI.prototype.getUrl = function () {
    with(this) {

        var imgUrl = "";
        imgUrl += baseUrl_ + "/BLIP/" + _model + "/" + _region + "/FCST/";
        if (_model == "RUC") { // RUC
            imgUrl += _prefix + _param + ".";
        } else { // NAM
            if (_prefix == "previous.") {
                imgUrl += _prefix + _param + ".curr.";
            } else {
                imgUrl += _param + "." + _prefix;
            }
        }
        imgUrl += _time + _png + "?" + randUniq_;
        return imgUrl;

    }
}

BMI.prototype.clone = function () {
    //alert("cloning:"+this.getUrl());  // debug
    return new BMI(this._model, this._region, this._prefix, this._param, this._time, this._png);
}
BMI.prototype.set = function (bmi) {
    this._model = bmi._model;
    this._region = bmi._region;
    this._prefix = bmi._prefix;
    this._param = bmi._param;
    this._time = bmi._time;
    this._png = bmi._png;
}
BMI.prototype.defaultTime = function () {
    this._time = tzArr_[this._region];
}
BMI.prototype.equals = function (bmi) {
    if (bmi == null) {
        return false;
    } else if (bmi == this) {
        return true;
    }
    var imgUrl1 = this.getUrl();
    var imgUrl2 = bmi.getUrl();
    //alert("equals() imgUrl1:"+imgUrl1+" imgUrl2:"+imgUrl2+" ?:"+
    //      (imgUrl1==imgUrl2));   // debug
    return imgUrl1 == imgUrl2;
}


function getDimSize(dflt, dim) {

    if (constSz_ != null) {
        dflt = constSz_.split("x")[dim];
    } else {
        //alert("using dflt:"+dflt); // debug
    }
    return dflt;
}


function calcHeight(ht) {
    return getDimSize(ht, 0);
}


function calcWidth(wdth) {
    return getDimSize(wdth, 1);
}


function imgIncompleteMsg(img) {
    /*
* Activate (uncomment) this alert if you're having img size
* and/or img rendering problems
* This user interface pause is hopefully long enough for the img loading
* thread to catch up and finish.
*/
    if (!img.complete) {
        // This alert will give a convenient little pause.
        //alert("Still loading image from URL:\n"+img.src+"\n\nReady momentarily...");
    }
}

BMI.prototype.getImg = function () {
    var imgUrl = this.getUrl();
    var img = imgs_[imgUrl];

    //alert("BMI.getImg():"+imgUrl); // debug
    if (img == null) {
        //alert("new Image():"+imgUrl); // debug
        img = new Image();
        imgs_[imgUrl] = img;

        // img.onError = "shoError(img)";
        img.onAbort = "shoError(img)";
        //img.onLoad = "shoLoad()";  // doesn't work?
        img.src = imgUrl;
    } else {
        //alert("old Image():"+imgUrl); // debug
    }
    return img;
}
BMI.prototype.compatblTime = function () {
    if (this._model == "NAM" && this._time != "18z" && this._time != "21z") {
        this._time = "18z";
    }
}
BMI.prototype.compatblPrefix = function () {
    if (this._model == "NAM" && (this._prefix == "" || this._prefix == "first.")) {
        this._prefix = "curr.";
    } else if (this._model == "RUC" && this._prefix.indexOf("curr") == 0) {
        this._prefix = "";
    }
}
BMI.prototype.sho = function () {

    var img = this.getImg();
    //  imgIncompleteMsg(img);
    var wdth, ht;

    var docId = document.getElementById('ImgBaselayer'); //base map - child of DivBaseLayer
    var docId2 = document.getElementById('ImgBliplayer'); //blipmap - child div of DivOverlay
    var docId3 = document.getElementById('DivOverlay'); //parent div of blipmap
    var docId4 = document.getElementById('DivBaseLayer'); //parent div of base map
    var docId5 = document.getElementById("DivFixedWindow"); // Outer Div frame
    if (document.getElementById('reCnt')) document.getElementById('reCnt').innerHTML = loop_._current + 1 + '/' + loop_._bmiArr.length; //innerHTML

    //added for key label
    var model = this._model;
    var region = this._region;
    var param = this._param;

    var lblUT = document.getElementById("ulTop");
    var lblUB = document.getElementById("ulBot");
    var lblUSrc = document.getElementById("iSrcT");

    var lblLT = document.getElementById("llTop");
    var lblLB = document.getElementById("llBot");
    var lblLSrc = document.getElementById("iSrcB");
    var LabelWindowWidth = 600;

    lblLSrc.style.visibility = "hidden"; // shut off lower label until needed

    // end added for key label
    // if (img.complete && constSz_ != null) {
    if (constSz_ != null || constSz_ != '0x0') {
        wdth = constSz_.split("x")[0] + 'px';
        ht = constSz_.split("x")[1] + 'px';
    } else {
        constSz_ = "600x600";
        wdth = "600px";
        ht = "600px";
        //EM set loc to 0,0  on orig image size so people can find it!
        docId3.style.left = "0px";
        docId3.style.top = "0px";
        docId4.style.left = "0px";
        docId4.style.top = "0px";

    }

    // *********************************************************************
    // *********************************************************************
    //EM:  blipmap & basemap resizing
    docId2.style.height = ht; //'ImgBliplayer' =  blipmap - child of DivOverlay
    docId2.style.width = wdth;
    docId2.alt = "Image cannot be displayed: possible cookie problem ";
    docId2.style.visibility = "visible";

    //new attach event instead of onerror
    /*
if(window.addEventListener){ // Mozilla, Netscape, Firefox
docId2.addEventListener('onerror', function imgErrWork() { //new
popupWork(this.src);
zap();
return false; //don't display standard error message
}, false);


docId2.mydata=docId2.src;
} else { // IE
docId2.attachEvent('onerror', function imgErrWork() { //new
popupWork(this.src);
zap();
return false; //don't display standard error message
});
docId2.mydata=docId2.src;
}
*/

    docId2.src = img.src;

    docId.style.height = ht; // 'ImgBaselayer' = base map  - child of DivBaseLayer
    docId.style.width = wdth;
    docId.alt = "Image cannot be displayed: possible cookie problem ";

    var hxw = "" + docId2.height + "x" + docId2.width;
    window.status = this.toString() + "   " + hxw;

    this._shown = true;

    // 4TESTCONSOLE: var isrc=img.src.toString();
    // 4TESTCONSOLE: var docConsole = document.getElementById("console");
    // 4TESTCONSOLE: docConsole.innerHTML = '<p><small><small><a href=' + basMap_ + '> Basemap: ' + basMap_  + '</a><br><a href=' + isrc + '> Blipmap: ' + isrc  + '</a></small></small></p>';
    var titleTop, titleBot, titleHeight, titleLeft, titleRight;
    // determine whether key label has composite or noncomposite parameter
    if (param.match("_")) {
        titleTop = compositetitleTop_[region];
        titleBot = compositetitleBot_[region];
    } else {
        titleTop = noncompositetitleTop_[region];
        titleBot = noncompositetitleBot_[region];
    }

    // calc Title label variables
    titleHeight = titleBot - titleTop + 1;
    titleLeft = parseInt((imgsize_[region] - LabelWindowWidth) / 2);
    if (titleLeft < 0) titleLeft = 0;
    titleRight = titleLeft + LabelWindowWidth - 1;

    lblUT.style.height = titleHeight + "px";
    lblUT.style.width = LabelWindowWidth + "px";

    lblUB.style.top = "-" + titleTop + "px"; //  -titleTop + "px";
    lblUB.style.left = "-" + titleLeft + "px"; //  -titleLeft + "px";
    lblUB.style.clip = "rect(" + titleTop + "px," + titleRight + "px," + titleBot + "px," + titleLeft + "px)";
    lblUSrc.src = docId2.src; //img.src;

    // FOR COMPOSITES, ADD SCALE BELOW TITLE
    if (param.match("_")) {

        var scaleHeight = compositescaleBot_[region] - compositescaleTop_[region] + 1;
        var scaleLeft = parseInt((imgsize_[region] - LabelWindowWidth) / 2);
        if (scaleLeft < 0) scaleLeft = 0;
        var scaleRight = scaleLeft + LabelWindowWidth - 1;

        lblLT.style.height = scaleHeight + "px";
        lblLT.style.width = LabelWindowWidth + "px";

        lblLB.style.top = "-" + compositescaleTop_[region] + "px";
        lblLB.style.left = "-" + scaleLeft + "px";
        lblLB.style.clip = "rect(" + compositescaleTop_[region] + "px," + scaleRight + "px," + compositescaleBot_[region] + "px," + scaleLeft + "px)";

        lblLSrc.src = docId2.src; //img.src;
        lblLSrc.style.visibility = "visible";
    }
    lblUSrc.style.visibility = "visible";

    /*
if(window.addEventListener){ // Mozilla, Netscape, Firefox
img.removeEventListener('onerror',imgErrWork,false);

} else { // IE
img.detachEvent('onerror',imgErrWork);
}
*/
}

//new
//http://www.captain.at/howto-addeventlistener-attachevent-parameters.php
function imgErrWork(evt) {
    alert('here');
    var e_out;

    var ie_var = "srcElement";
    var moz_var = "target";

    // "target" for Mozilla, Netscape, Firefox et al. ; "srcElement" for IE
    prop_var = "mydata";
    evt[moz_var] ? e_out = evt[moz_var][prop_var] : e_out = evt[ie_var][prop_var];

    alert('error detected \n' + e_out);
    popupWork(e_out);
    zap();
    return false;

}



function shoReview() {
    //empty ReView indicator
    if (document.getElementById('reCnt')) document.getElementById('reCnt').innerHTML = "";
    var lc = (loop_._bmiArr.length == 0) ? 0 : 1;
    if (lc == 0) {
        var docId1 = document.getElementById('ImgBaselayer'); //basemap
        var docId2 = document.getElementById('ImgBliplayer'); //blipmap
        docId1.alt = "Select a new Parameter, Day, Time or Region";
        docId2.alt = "Select a new Parameter, Day, Time or Region";
    }
    if (document.getElementById('reCnt')) document.getElementById('reCnt').innerHTML = loop_._current + lc + '/' + loop_._bmiArr.length; //innerHTML
}



function openHome() {
    window.open(baseUrl_);
}


function openHelp() {
    window.open(baseUrl_ + "/BLIP/INFO/help.html");
}


function openDetails() {
    var bmi = currentBMI();
    var param = (bmi == null) ? "wfpm" : bmi._param;
    window.open(baseUrl_ + "/BLIP/INFO/parameter_details.html#" + param);
}


function openParamSummary() {
    var bmi = currentBMI();
    var param = (bmi == null) ? "wfpm_woustar" : bmi._param;
    var model = (bmi == null) ? "NAM" : bmi._model;
    window.open(baseUrl_ + "/BLIP/" + model + "/INFO/parameters.html#" + param);
}


function openArchiveViewer() {
    var bmi = currentBMI();
    var param = (bmi == null) ? "wfpm" : bmi._param;
    window.open(baseUrl_ + "/BLIP/ARCHIVE/archive_viewer.html");
}


function openUsageNotes() {
    window.open(baseUrl_ + "/BLIP/univiewer/univiewer_usage_notes.html");
}


function zap() {

    var bmi = loop_.zap();
    if (bmi != null) {
        myDefBMI_ = bmi;
        //change basemap too!
        var regn = bmi._region;
        if (sBMap_ != "no")(basGeoTop_ == 'Topo') ? setBaselayerTopo(regn) : setBaselayerGeo(regn);

        bmi.sho();
    } else {

        //new27Jul single new click for new blip image
        //  currConstImgSz();// goto 0,0 on the image divs - handle over zoom
        var docId1 = document.getElementById('ImgBaselayer'); //basemap
        var docId2 = document.getElementById('ImgBliplayer'); //blipmap
        var lblUSrc = document.getElementById("iSrcT"); //upper key label
        var lblLSrc = document.getElementById("iSrcB"); //lower key label
        docId1.alt = "Select a new Parameter, Day, Time or Region";
        docId2.alt = "Select a new Parameter, Day, Time or Region";

        // docId1.src = "";
        docId2.src = "";
        lblUSrc.src = "";
        lblLSrc.src = "";

        // basMap_=null;
    }
}


function toggle() {
    var bmi = loop_.toggle();
    if (bmi != null) {
        //change basemap too!
        var regn = bmi._region;
        if (sBMap_ != "no")(basGeoTop_ == 'Topo') ? setBaselayerTopo(regn) : setBaselayerGeo(regn);
        bmi.sho();
    }

}


function prev() {
    var bmi = loop_.prev();
    if (bmi != null) {
        //change basemap too!
        var regn = bmi._region;
        if (sBMap_ != "no")(basGeoTop_ == 'Topo') ? setBaselayerTopo(regn) : setBaselayerGeo(regn);
        bmi.sho();
    }
}


function next() {
    var bmi = loop_.next();
    if (bmi != null) {
        //change basemap too!
        var regn = bmi._region;
        if (sBMap_ != "no")(basGeoTop_ == 'Topo') ? setBaselayerTopo(regn) : setBaselayerGeo(regn);
        bmi.sho();

    }
}


function origImgSz() {
    constSz_ = null; // null constSz_ means use img's orig size
    var bmi = currentBMI();
    bmi.sho();

}


function currConstImgSz() {
    var bmi = currentBMI();
    var img = bmi.getImg();
    imgIncompleteMsg(img);
    if (img.complete) {
        constSz_ = "" + img.height + "x" + img.width;
        //constSz_ = frameSz_; //"" + img.height + "x" + img.width;
    }
    //alert("currConst:"+constSz_);  // debug
    bmi.sho();

    //new centering
    var docId1 = document.getElementById('DivBaseLayer'); //parent div of basemap
    var docId2 = document.getElementById("DivOverlay"); //parent div of blipmap
    var docId3 = document.getElementById('ImgBaselayer'); //base map - child of DivBaseLayer
    var docId4 = document.getElementById('ImgBliplayer'); //blipmap - child div of DivOverlay
    var docId5 = document.getElementById("DivFixedWindow"); // Outer Div frame    


//alert('docId5 offset width = ' + docId5.offsetWidth + '\n docId1 offset width = ' + docId1.offsetWidth);
//return;
     var docId5L =  docId5.style.left;        
         docId5L =  parseFloat(docId5L.split("p")[0]);

var docId5W =  docId5.offsetWidth;
var docId4W =  docId4.offsetWidth;
var docIdDeltaWD2 = (docId5W - docId4W)/2;

var docId5H =  docId5.offsetHeight;
var docId4H =  docId4.offsetHeight;
var docIdDeltaHD2 =  (docId5H - docId4H)/2;


    var nowT = docId5.style.top;    
        nowT =  parseFloat(nowT.split("p")[0]);        
        nowT = nowT + docIdDeltaHD2;

    var nowL = docId5.style.left;
        nowL =  parseFloat(nowL.split("p")[0]);        
        nowL = nowL + docIdDeltaWD2;        

if (docIdDeltaHD2 < 0 || docIdDeltaWD2 <0) { 
nowL = 0;
nowT = 0;
}


    docId1.style.left = "" + nowL + "px";
    docId1.style.top = "" + nowT + "px";
    docId2.style.left = docId1.style.left;
    docId2.style.top = docId1.style.top;
   
    docId3.style.height = docId2.style.height; //// 'ImgBliplayer' =  blipmap - child of DivOverlay
    docId3.style.width = docId2.style.width;
    docId4.style.height = docId3.style.height; // 'ImgBaselayer' = base map  - child of DivBaseLayer
    docId4.style.width = docId3.style.width;

}


function constImgSz() {  //frame fit
   
   //new centering
    var docId1 = document.getElementById('DivBaseLayer'); //parent div of basemap
    var docId2 = document.getElementById("DivOverlay"); //parent div of blipmap
    var docId3 = document.getElementById('ImgBaselayer'); //base map - child of DivBaseLayer
    var docId4 = document.getElementById('ImgBliplayer'); //blipmap - child div of DivOverlay
    var docId5 = document.getElementById("DivFixedWindow"); // Outer Div frame    


var docId5W =  docId5.offsetWidth;
var docId5H =  docId5.offsetHeight;



    docId1.style.left = docId5.style.left;
    docId1.style.top = docId5.style.top;  
    docId2.style.left = docId1.style.left;
    docId2.style.top = docId1.style.top;
   
    docId3.style.height = docId2.style.height; //// 'ImgBliplayer' =  blipmap - child of DivOverlay
    docId3.style.width = docId2.style.width;
    docId4.style.height = docId3.style.height; // 'ImgBaselayer' = base map  - child of DivBaseLayer
    docId4.style.width = docId3.style.width;

 constSz_ = "" + docId5H + "x" + docId5W;
    //frameSz_ = constSz_;
    var bmi = currentBMI();
    bmi.sho();

}



function adjustImgSz(fctr) {

    ///new adjust to keep centered
    var docId1 = document.getElementById('DivBaseLayer'); //parent div of basemap
    var moveTop, moveLeft;

    var nowL = parseFloat(docId1.style.left);
    var nowT = parseFloat(docId1.style.top);

    var bmi = currentBMI();
    var ht = 600;
    var wdth = 600;

    if (constSz_ == null) {
        var img = bmi.getImg();
        imgIncompleteMsg(img);
        if (img.complete) {
            // use img dim sizes
            ht = img.height;
            wdth = img.width;
        }
    }

    ht = calcHeight(ht);
    wdth = calcWidth(wdth);
    ht *= fctr;
    wdth *= fctr;
    constSz_ = "" + parseInt(ht) + "x" + parseInt(wdth);
    //alert("adjust constSz_:"+constSz_);  // debug
    bmi.sho();

    //jack - adjust to keep centered (for 600x600 frame)
    nowL = parseInt(fctr * (nowL - 300)) + 300;
    nowT = parseInt(fctr * (nowT - 300)) + 300;
    docId1.style.left = nowL + "px";
    docId1.style.top = nowT + "px";
    document.getElementById("DivOverlay").style.left = docId1.style.left;
    document.getElementById("DivOverlay").style.top = docId1.style.top;

}


function constSz_FromUrl(imgUrl) {
    if (imgUrl == null) {
        return null;
    }
    var szPos = imgUrl.indexOf("constSz_=");
    var sss = imgUrl.substring(szPos + 8, imgUrl.length);
    //alert("sss:"+sss); // debug
    var tokArr = sss.split("&");
    if (tokArr.length >= 1) {
        //alert("tokArr.len:"+tokArr.length+" [0]:"+tokArr[0]);  // debug
        return tokArr[0];
    } else {
        return null;
    }
}


function setConstSz(imgUrl) {
    var csz = constSz_FromUrl(imgUrl);
    if (csz != null) {
        var xDelim = csz.indexOf("x");
        if (xDelim != -1) {
            constSz_ = csz;
        }
    }

}

// *********************************************************************
// *********************************************************************
//EM added function to extract constSz, location, opacity and basemap from cookie (imgUrl)
function urlToLOB(imgUrl) {

    if (imgUrl == null) {
        return null;
    }
    // make L-O-B array from cookie
    var plH = imgUrl.indexOf("&");
    var shrtUrl = imgUrl.substring(plH);
    var tokArr = shrtUrl.split("&");

    var cz, l, o, b, fs, fp, cb;

    if (tokArr.length == 8) {
        cz = getCookVal(tokArr[1]); // size
        l = getCookVal(tokArr[2]); // location
        o = getCookVal(tokArr[3]); // opacity
        b = getCookVal(tokArr[4]); // basemap
        fs = getCookVal(tokArr[5]); //framesize                  
        fp = getCookVal(tokArr[6]); //framepos
        cb = getCookVal(tokArr[7]); // checkbox
        return {
            cz: cz,
            l: l,
            o: o,
            b: b,
            fs: fs,
            fp: fp,
            cb: cb
        }

    } else {
        //   alert('can\'t parse cookie for loc/opac/baseMap - using default values');
        return {
            cz: '600x600',
            l: '0px,0px',
            o: 30,
            b: "geographicmap.png",
            fs: '600x600',
            fp: '0x0',
            cb: "nope"
        }
    }

}

// *********************************************************************
// *********************************************************************
//EM new url parser added to this function - imgUrl is the whole cookie
// returns (model, region, prefix, param, time, png) as new BMI
function urlToBMI(imgUrl) {
    if (imgUrl == null) {
        return null;
    }
    var model, region, prefix, param, time, png;

    //remove http// stuff from url ~ 10 chars out
    var plHolder = imgUrl.substring(10);
    var tokArr = plHolder.split("/");

    model = tokArr[2];
    region = tokArr[3];

    var pptp = tokArr[5]; // param/prefix/time/png
    // alert(tokArr[5]);
    var px = pptp.indexOf('&'); // make array of URL suffix eg: wfpm_woustar.21z.png
    // var py = pptp.substring(0, px);
    var py = (px != -1) ? pptp.substring(0, px) : pptp; // new to handle reView Array
    var u = py.indexOf('?'); // NEW strip off rnd if found, ie wfpm_woustar.curr.18z.png?jw9.391045025320002
    if (u != -1) py = py.substring(0, u);

    var pz = py.split(".");
    switch (pz.length) {
    case 3:
        //eg: wfpm_woustar.21z.png
        param = pz[0];
        prefix = "";
        time = pz[1];
        png = "." + pz[2];
        break;
    case 4:

        if (model == "RUC") { //(pz[0] == "previous" || pz[0] == "first"){
            //"previous.wfpm.15z.png" - RUC
            param = pz[1];
            prefix = pz[0] + "."; //""; //prefix = first or previous
            time = pz[2];
            png = "." + pz[3];
            break; //previous.wfpm.21z.png?jw22.873417721096047
        } else if (model == "NAM") {
            // eg: woustar.curr.18z.png - NAM
            param = pz[0];
            prefix = pz[1] + "."; //prefix = curr, curr+1 or curr+2
            time = pz[2];
            png = "." + pz[3];
        }
        break;
    case 5:
        // eg: previous.wfpm_woustar.curr.21z.png,  previous or first and curr shouldn't happen at the same time, disregard 'previous or first'
        param = pz[1];
        prefix = pz[2] + "."; //curr
        time = pz[3];
        png = "." + pz[4];
        break;
    default:
        // alert(can\'t decode url prefix \n' + pz.len + '  ' + pz);
    }
    //test
    if (time.indexOf('z') == -1) alert('cookie image parse error \n\n' + pz);
    // good time to change img alt saying there was a different problem other than a cookie
    return new BMI(model, region, prefix, param, time, png);

}


function shoError(img) {
    alert("Image failed to load from URL:\n" + img.src + "\n\nPlease reclick to try again.");
    document.blipmap.src = errImgUrl_;
}


function currentBMI() {
    var bmi = loop_.current();
    if (bmi == null) {
        // alert("currentBMI : bmi null so use myDefBMI_ =\n" +myDefBMI_);  // debug
        bmi = myDefBMI_;
    }
    return bmi;
}


function shoRegion(region) {
    var bmi = currentBMI().clone();
    bmi._region = region;
    myDefBMI_ = bmi;
    //change basemap image dep on region
    if (sBMap_ != "no") {
        (basGeoTop_ == 'Topo') ? setBaselayerTopo(region) : setBaselayerGeo(region);
    } else {
        noBaselayer();
    }
    loop_.insert(bmi);
    constImgSz(); //size image to frame on change of region
}



function shoPrefix(prefix, model) {
    var bmi = currentBMI().clone();
    //    alert(bmi.toString());
    bmi._prefix = prefix;
    bmi._model = model;
    bmi.compatblTime();
    myDefBMI_ = bmi;
    bmi.sho();
    loop_.insert(bmi);
}


function shoTime(time, model) {
    var bmi = currentBMI().clone();
    bmi._time = time;
    bmi._model = model;
    bmi.compatblPrefix();
    myDefBMI_ = bmi;
    bmi.sho();
    loop_.insert(bmi);
}


function shoParam(param) {
    var bmi = currentBMI().clone();
    bmi._param = param;
    myDefBMI_ = bmi;
    bmi.sho();
    loop_.insert(bmi);

}


function colorToggle() {
    var bmi = currentBMI().clone();
    bmi._png = (bmi._png == ".png") ? ".PNG" : ".png";
    myDefBMI_ = bmi;
    bmi.sho();
    loop_.insert(bmi);
}


function initSho() {

    //  loop_ = new Loop();
    // var bmi = currentBMI().clone();
    var bmi = myDefBMI_.clone(); //new
    bmi.sho();
    //    loop_.insert(bmi);
}


function initViaCookey() {
    // *********************************************************************
    // *********************************************************************
    // this routine generates a myDefBMI_ based on the cookie
    //EM moved get cookie to embedInitHtml()
    if (ckyVal_ != null && ckyVal_.length < 6) {
        cookey_.delCookie();
        ckyVal_ = null;
    }
    //  myDefBMI_ = urlToBMI(ckyVal_);
    if (loop_._bmiArr[reVuPtr_]) {
        myDefBMI_ = loop_._bmiArr[reVuPtr_];
    }

    else { //(myDefBMI_ == null)
        //pre-pan-overlay var defRegion_ = "NE";
        //pre-pan-overlay myDefBMI_ = new BMI("NAM", defRegion_, "curr.", "wfpm",
        var defRegion_ = "CANV";
        myDefBMI_ = new BMI("NAM", defRegion_, "previous.", "wfpm_woustar", tzArr_[defRegion_], ".png");
        //jack-altered			tzArr_[defRegion_], false);
    }

    /*
else {
myDefBMI_.defaultTime();  // easier to simply start from here
myDefBMI_._param = "wfpm";  // easier to simply start from here

myDefBMI_._prefix = "curr.";  // easier to simply start from here
myDefBMI_.compatblPrefix();
}  */

}

//NEW 7Oct09 for imagezoom addon - zoom lower layer
function zoomBase() {
    alert('hi \n zooming ImgBaselayer');
    var imgBase = document.getElementById("ImgBaselayer");
    var divi = document.getElementById("DivFixedWindow");
    imgBase.style.width = evt.style.width;
    imgBase.style.height = evt.style.height;

    divi.style.width = evt.style.width;
    divi.style.width = evt.style.width;

}



function zoomBases() {
    alert('hi \n zooming ImgBliplayer');
    var imgBase = document.getElementById("ImgBliplayer");

    imgBase.style.width = evt.style.width;
    imgBase.style.height = evt.style.height;

}



function embedInitImgHtml() // em: Note: combined with panoverlay startup
{
    // *********************************************************************
    // *********************************************************************    docId.style.opacity = newOpacity/10;
    //	docId.style.filter = 'alpha(opacity=' + newOpacity*10 + ')';
    if (!document.getElementById("DivFixedWindow")) {

        //EM: write divs - then fill in
        // START OF PAN-OVERLAY ADDITION --------------------------------------------------------------
        // ?? ADD "px" TO HEIGHT,WIDTH SPECS WHERE ADDED wdth,ht ??
        document.write("    <!-- *** SET OUTER FIXED WINDOW *** --> ");
        document.write("    <div id=\"DivFixedWindow\" style=\"position:relative; width:600; height:600; overflow:hidden; border-style:solid; border-width:2px;\"> ");
        //document.write("    <div id=\"DivFixedWindow\" style=\"position:relative; width:600; height:600; clip:rect(0,600,600,0); overflow:hidden; border-style:solid; border-width:2px;\"> ");
        //FULLWINDOW= document.write("    <div id=\"DivFixedWindow\" style=\"position:relative; width:"+wdth+"; height:"+ht+"; clip:rect(0,"+wdth+","+ht+",0); overflow:hidden; border-style:solid; border-width:2px;\"> ");
        document.write("      <!-- *** SET BASEMAP *** --> ");
        document.write("      <div  id=\"DivBaseLayer\" style=\"position:absolute;  z-index:2; \" >  "); // left:0px; top:0px; width:2377px; height:2377px; clip:rect(0px,2377px,2377px,0px); overflow:hidden; visibility:visible; filter:alpha(opacity=100); opacity:1.0;
        document.write("        <IMG id=\"ImgBaselayer\" onzoom=\"zoomBases()\" name=\"basemap\" SRC=\"\"  style=\"visibility: visible\">  ");
        document.write("      </div> ");
        document.write("      <!-- *** SET OVERLAY *** --> ");
        document.write("      <div  id=\"DivOverlay\" onzoom=\"zoomBase()\"  style=\"position:absolute;  z-index:3; \"> "); // left:0px; top:0px; width:2377px; height:2377px; clip:rect(0px,2377px,2377px,0px); overflow:hidden; visibility:visible; filter:alpha(opacity=30); opacity:0.30;
        //prePanOverlay= document.write("<IMG height="+ht+" width="+wdth+" src=\"\" name=blipmap onClick=\"popupDisplay(event)\" >");
        document.write("        <IMG class=\"centeredImage\" onzoom=\"zoomBase()\" id=\"ImgBliplayer\"   src=\"\"   style=\"visibility: visible\" name=\"blipmap\" onClick=\"popupDisplay(event)\" >");
        //OK document.write("<IMG src=\"\" name=blipmap onClick=\"popupDisplay(event)\" >");
        //TEST document.write("<IMG SRC=\"http://www.drjack.info/BLIP/RUC/USA/wfpm.18z.png\">   <!-- height,width not needed here --> ");
        document.write("      </div> ");
        document.write("    </div> ");

        //EM: new divs for key label
        document.write(" <div id=\"lblMain\" style=\"position:relative;width:600; height:auto;left:0px; top:0px;\"> "); // border-style:solid; border-width:2px;
        // Upper label
        document.write(" <div id=\"ulTop\" style=\"position:relative;width:600; left:0px; top:0px; overflow:hidden;\"> ");
        document.write("  <div id=\"ulBot\" style=\"position:absolute; overflow:hidden;\"> ");
        document.write("    <IMG id=\"iSrcT\" src=\"\" style=\"visibility:hidden;\" > ");
        document.write("      </div> ");
        document.write("     </div> ");

        //lower label
        document.write(" <div id=\"llTop\" style=\"position:relative;width:600; left:0px; top:0px; overflow:hidden;\"> ");
        document.write("  <div id=\"llBot\" style=\"position:absolute; overflow:hidden;\"> ");
        document.write("    <IMG id=\"iSrcB\" src=\"\" style=\"visibility:hidden;\"  > ");
        document.write("      </div> ");
        document.write("     </div> ");
        document.write(" </div> ");

    }

    //  END  OF PAN-OVERLAY ADDITION --------------------------------------------------------------
    // *********************************************************************
    // *********************************************************************
    // load ReView Array from different cookie
    var sLoc, sOpa;
    var sChkBox = "o";

    cookey_ = new Cookey();
    //cookey_.delCookie();  // try to vaporize problem cookie
    //cookey_._cname = reViewCookieName_; funct already has cookie name
    loop_ = new Loop();
    getReView();

    cookey_._cname = mainCookieName_;

    ckyVal_ = cookey_.getCookie();
    //  debugger;
    // for swapping between ff & ie or no cookie
    if (!ckyVal_ || ckyVal_.indexOf('http') == -1 || ckyVal_.indexOf('NaN') > -1) cnf_ = 'yes';

    // debug - feed a proper cookie
    //  ckyVal_ = 'http://www.drjack.info/BLIP/NAM/NE/FCST/wfpm_woustar.curr.18z.png?jw77777&constSz_=600x600&ctrlLoc=24px,12px&opacy=30&imgBLMap=geographicmap.png';
    var lob = urlToLOB(ckyVal_); //new function returns location-opacity-basemap-Checkbox array
    if (lob) // L-O-B ok
    {

        constSz_ = (lob.cz == null) ? "600x600" : lob.cz;
        sLoc = (lob.l == null) ? "0,0" : lob.l;
        sOpa = parseInt(lob.o);
        sBMap_ = lob.b;
        frameSz_ = (lob.fs == null) ? "600x600" : lob.fs;
        framePos_ = (lob.fp == null) ? "0x0" : lob.fp;
        sChkBox = (lob.cb == null) ? "o" : lob.cb;

    }
    else { //didn't get any values so use some default constSz_ & L-O-B
        //alert('embedInitImgHtml() : using default Location-Opacity-Basemap');
        // these values from function panoverlayStartup()
        // EM:  better to make a new myDefBMI
        sLoc = "0,0";
        sOpa = 50;
        sBMap_ = "geographicmap.png";
        constSz_ = "600x600";
        frameSz_ = "600x600";
        framePos_ = "0x0";
        sChkBox = "";
    }

    // *** Set LOCATION ***
    var xLoc = sLoc.split(",")
    var lLeft = xLoc[0];
    var lTop = xLoc[1];

    var docId5 = document.getElementById("DivFixedWindow"); // Outer Div frame

    var fht = +frameSz_.split("x")[0];
    var fwdth = +frameSz_.split("x")[1];
    var frT = +framePos_.split("x")[0];
    var frL = +framePos_.split("x")[1];

    docId5.style.height = "" + fht + "px"; //Outer Div frame
    docId5.style.width = "" + fwdth + "px";

    docId5.style.top = "" + frT + "px";
    docId5.style.left = "" + frL + "px";

    // now that we have constSz_ continue
    initViaCookey(); // gets myDefBMI_ from cookie myDefBMI_ = urlToBMI(ckyVal_);
    var ht = constSz_.split('x')[0] + "px";
    var wdth = constSz_.split('x')[1] + "px";

    basGeoTop_ = (sBMap_ == "topographicmap.png") ? "Topo" : "Geo"; //default geographic map
    basMap_ = (sBMap_ == 'no') ? 'no' : baseUrl_ + "/BLIP/" + myDefBMI_._model + "/" + myDefBMI_._region + "/" + sBMap_;

    // 4TESTCONSOLE: var isrc=img.src.toString();
    // 4TESTCONSOLE: var docConsole = document.getElementById("console");
    // 4TESTCONSOLE: docConsole.innerHTML = '<p><small><small><a href=' + basMap_ + '> Basemap: ' + basMap_  + '</a><br><a href=' + isrc + '> Blipmap: ' + isrc  + '</a></small></small></p>';
    //var clpRect = "rect(0px " + wdth + "px " + ht + "px " + "0px)" ; needed
    // *** Set Base Map Div Location***
    var docId2 = document.getElementById("DivBaseLayer");
    docId2.style.left = lLeft;
    docId2.style.top = lTop;

    // *** Set Blip Map div location to Base Map Div loc ***
    var docId0 = document.getElementById("DivOverlay");
    docId0.style.left = docId2.style.left;
    docId0.style.top = docId2.style.top;

    // *** Size Base Map image***
    var docId3 = document.getElementById('ImgBaselayer');
    docId3.style.height = ht;
    docId3.style.width = wdth;
    //docId3.style.clip=clpRect;  //needed?
    if (sBMap_ != 'no') docId3.src = basMap_;

    // *** Set Blip Map ***
    var docId1 = document.getElementById("ImgBliplayer");
    docId1.style.width = wdth;
    docId1.style.height = ht;
    //docId1.style.clip=clpRect;

    docId1.src = (cnf_ == "no") ? myDefBMI_.getUrl() : "";
    // docId1.src = myDefBMI_.getUrl(); // img.src;
    docId1.alt = "Image cannot be displayed: possible cookie problem";

    // *** Set Opacity ***
    setOpacityDO(sOpa);
    if (cnf_ == 'no') initSho(); // no cookie no blipmap & need this to get image label
    //fill in checkboxes
    if (sChkBox.indexOf('|') > -1) loadCheckboxes(document.popUpChooser, sChkBox);
    //   loop_._current=0;  // set loop pointer to 1 so that ReView arrow click shows #2
    loop_._current = (reVuPtr_ >= 1) ? reVuPtr_ : 0; // set ReView pointer NEW
}



function getLayer(id) {
    var nn4 = (document.layers) ? true : false;
    var ie = (document.all) ? true : false;
    var dom = (document.getElementById && !document.all) ? true : false;
    var path;
    if (nn4) {
        path = document.layers[id];
    } else if (ie) {
        path = document.all[id];
    } else {
        path = document.getElementById(id);
    }
    return path;
}



function dumpProps(obj, parent) {
    for (var iii in obj) {
        var msg = iii + "\n" + obj[iii];
        if (parent) {
            msg = parent + "." + msg;
        }
        if (!confirm(msg)) {
            return;
        }
        if (typeof obj[iii] == "object") {
            if (parent) {
                dumpProps(obj[iii], parent + "." + iii);
            } else {
                dumpProps(obj[iii], iii);
            }
        }
    }
}



function debugProps() {
    var layer = getLayer("bob");
    dumpProps(layer, "layer");
    var layer2 = getLayer("blipmap");
    dumpProps(layer2, "layer2");
    alert(" window.event.x:" + window.event.x + "\n" + " window.event.y:" + window.event.y + "\n" + " event.layerX:" + event.layerX + "\n" + " event.pageX:" + event.pageX + "\n" + " event.x:" + event.x + "\n" + " event.y:" + event.y + "\n" + " layer:" + layer + "\n" + " layer:" + layer.style.left + "\n" + " layer:" + layer.left + "\n" + " layer2:" + layer2 + "\n" + " layer2:" + layer2.x + "\n" + " layer2:" + layer2.y + "\n" + " event.offsetX:" + event.offsetX + "\n" + " event.offsetY:" + event.offsetY + "\n");
}



function getPageCoords(element) {
    var coords = {
        x: 0,
        y: 0
    };
    while (element) {
        coords.x += element.offsetLeft;
        coords.y += element.offsetTop;
        element = element.offsetParent;
    }
    return coords;
}



function getOffsets(evt) {
    var target = evt.target;
    if (typeof target.offsetLeft == 'undefined') {
        target = target.parentNode;
    }
    var pageCoords = getPageCoords(target);
    var eventCoords = {
        x: window.pageXOffset + evt.clientX,
        y: window.pageYOffset + evt.clientY
    };
    var offsets = {
        offsetX: eventCoords.x - pageCoords.x,
        offsetY: eventCoords.y - pageCoords.y
    }
    return offsets;
}



function popupWork(url) {
    //alert("url:\n"+url); // debug
    window.open(url);
}



function urlDayStr(model, prefix, dflt) {
    //alert("urlDayStr top model:"+model+" prefix:"+prefix+" dflt:"+dflt);
    var prevOrDay = dflt;
    if (model == "NAM") {

        prevOrDay = "&day=-1"; // "previous."
        if (prefix == "curr.") {
            prevOrDay = "&day=0";
        } else if (prefix == "curr+1.") {
            prevOrDay = "&day=1";
        } else if (prefix == "curr+2.") {
            prevOrDay = "&day=2";
        }
    }
    //alert("urlDayStr btm prevOrDay:"+prevOrDay);
    return prevOrDay;
}



function popupDisplay(evt) {
    var bmi = currentBMI();
    var model = (bmi == null) ? "NAM" : bmi._model;
    var region = (bmi == null) ? "USA" : bmi._region;
    var time = "18";

    if (bmi != null) {
        // take the "z" off of "HHz" or use the default "18" for "18z"
        var iii = bmi._time.indexOf("z");
        if (iii < 0) {
            alert("bmi._time:" + bmi._time + " is missing a trailing 'z'");
            return;
        }
        time = bmi._time.substring(0, iii);
    }
    var prefix = (bmi == null) ? "" : bmi._prefix;
    var previous = (prefix == "previous.") ? 1 : 0;
    var prevvv = "&prev=" + previous;

    // JACK - 16jan2006 : DISABLE FUNCTION FOR COMPOSITE IMAGES
    if (bmi._param.match(/wstar/i) || bmi._param.match(/blwind/i) || bmi._param.match(/mask/i)) {
        alert("Sorry  - this feature not enabled for composite parameter images");
        return null;
    }

    var ht = 0;
    var wdth = 0;
    var wX = 0;
    var wY = 0;
    if (window.event) {
        // IE specialization
        wX = event.offsetX;
        wY = event.offsetY;
        ht = window.blipmap.height;
        wdth = window.blipmap.width;
    } else {
        // works for Mozilla
        var offsets = getOffsets(evt);
        ht = evt.target.height;
        wdth = evt.target.width;
        wX = offsets.offsetX;
        wY = offsets.offsetY;
    }
    // alert("wXY:"+wX+","+wY); // debug
    if ((document.popUpChooser.popUpNonjavaSounding.checked || document.popUpChooser.popUpJavaSounding.checked) && model == "NAM") {
        alert("\nClickable NAM soundings currently unavailable here.\n");
    }
    if (document.popUpChooser.popUpNonjavaSounding.checked && model != "NAM") {
        var soundingUrl = baseUrl_ + "/cgi-bin/get_image_fslsounding.cgi" + "?region=" + region + "&time=" + time + "&i=" + wX + "&k=" + wY + "&width=" + wdth + "&height=" + ht + prevvv + "&type=nonjava";
        popupWork(soundingUrl);
    }
    if (document.popUpChooser.popUpJavaSounding.checked && model != "NAM") {
        var soundingUrl = baseUrl_ + "/cgi-bin/get_image_fslsounding.cgi" + "?region=" + region + "&time=" + time + "&i=" + wX + "&k=" + wY + "&width=" + wdth + "&height=" + ht + prevvv + "&type=java";
        popupWork(soundingUrl);
    }
    var prevOrDay = urlDayStr(model, prefix, prevvv);
    if (document.popUpChooser.popUpMiniSpot.checked) {
        var miniSpotUrl = baseUrl_ + "/cgi-bin/get_image_minispot.cgi" + "?region=" + region + "&model=" + model + "&i=" + wX + "&k=" + wY + "&width=" + wdth + "&height=" + ht + prevOrDay;
        popupWork(miniSpotUrl);
    }
    if (document.popUpChooser.popUpBmSkewT.checked) {
        var skewtUrl = baseUrl_ + "/cgi-bin/get_image_skewt.cgi" + "?region=" + region + "&model=" + model + "&time=" + time + "&i=" + wX + "&k=" + wY + "&width=" + wdth + "&height=" + ht + prevOrDay;
        popupWork(skewtUrl);
        //window.open(SkewtUrl,'','width=512,height=512,menubar=no,location=no,toolbar=no,directory=no,status=no,resizable=yes');
    }
}



function pasteUp() {
    //window.open(location.href);
    var windowAttr = 'menubar=no,location=no,toolbar=no,directory=no,status=no' + ',scrollbars=yes,resizable=yes' + ',width=' + (document.blipmap.width + 50) + ',height=' + (document.blipmap.height + 50);
    var windowName = 'pasteUp';
    //JACK window.open('univiewer/retrieving.jpg',windowName,windowAttr);
    window.open(document.blipmap.src, windowName, windowAttr);
}


function popUpAvail() {
    var bmi = currentBMI();
    var availUrl = baseUrl_ + "/cgi-bin/forecast_availability.cgi?" + bmi._region;
    var windowAttr = 'menubar=no,location=no,toolbar=no,directory=no,status=no' + ',scrollbars=yes,resizable=yes';
    window.open(availUrl, 'avail', windowAttr);
}

///////////////////////// Checkbox cookies////////////////////////
function saveCheckboxes(frm) {
    var setvalue, fieldType, index;
    var stringg = "|";
    var n = frm.length;
    for (var i = 0; i < n; i++) {
        fieldType = frm[i].type;
        if (fieldType == "checkbox") {
            if (frm.elements[i].checked == true) {
                stringg = stringg + 1 + "\|";
            } else if (frm.elements[i].checked == false) {
                stringg = stringg + 0 + "\|";
            }
        }
    }
    return stringg;
}



function loadCheckboxes(frm, fieldValues) {
    var fieldValue, fieldType, n;
    var fieldArray = new Array();
    n = frm.length;

    fieldArray = fieldValues.split("\|");
    fieldArray = (fieldArray.slice(1, 5)); // ["",  "0",    "1",    "0",    "1",   ""]
    for (var i = 0; i < n; i++) {
        fieldType = frm[i].type;
        if (fieldType == "checkbox") {
            fieldValue = fieldArray[i]
            if (fieldValue == "1") {
                frm.elements[i].checked = true;
            } else {
                frm.elements[i].checked = false;
            }

        }
    }
}
////////////////////////////////////////////////////////////////////////////////////////////////