// Created by John Whitney: Thu May 27 10:29:46 EDT 2004

var baseUrl_ = "http://www.drjack.info";
var randUniq_ = "jw"+(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/RUC/NE/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_;


function Cookey()
{
  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 dcookie = document.cookie;
  var cname = this._cname + "=";
  var clen = dcookie.length;
  // alert("Cookie size = " + clen); // debug
  var cbegin = 0;
  while (cbegin < clen)
  {
    var vbegin = cbegin + cname.length;
    if (dcookie.substring(cbegin, vbegin) == cname) {
      var vend = dcookie.indexOf (";", vbegin);
      if (vend == -1) vend = clen;
      return unescape(dcookie.substring(vbegin, vend));
    }
    cbegin = dcookie.indexOf(" ", cbegin) + 1;
    if (cbegin == 0) break;
  }
  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;
  }
  //alert("current() current:"+this._current+" _bmiArr.length:"+
  //      this._bmiArr.length);  // debug
  var bmi = this._bmiArr[this._current];
  //alert("current() bmi:"+bmi);  // debug
  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) {
    myDefBMI_ = bmi;
  }
  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
  }
}


function BMI(model, region, prefix, param, time, png)
{
  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);
  if (img.complete) {
    //alert("img complete:"+img.src);  // debug
    var newH = calcHeight(img.height);
    var newW = calcWidth(img.width);
    //alert("newH:"+newH+" newW:"+newW);
    document.blipmap.height = newH;
    document.blipmap.width = newW;
    //alert("sho w:"+document.blipmap.width+" h:"+document.blipmap.height); // debug
  }
  document.blipmap.src = img.src;
  var hxw = ""+document.blipmap.height+"x"+document.blipmap.width;
  window.status = document.blipmap.alt = this.toString()+"    "+hxw;

  this._shown = true;
  cookey_.setCookie(img.src+"&constSz="+constSz_);
}


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" : bmi._param;
  var model = (bmi == null) ? "RUC" : 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) {
    bmi.sho();
  }
}
function toggle()
{
  var bmi = loop_.toggle();
  if (bmi != null) {
    bmi.sho();
  }
}
function prev()
{
  var bmi = loop_.prev();
  if (bmi != null) {
    bmi.sho();
  }
}
function next()
{
  var bmi = loop_.next();
  if (bmi != null) {
    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;
  }
  //alert("currConst:"+constSz_);  // debug
  bmi.sho();
}
function constImgSz(hxw)
{
  constSz_ = (hxw == null) ? "589x589" : hxw;
  var bmi = currentBMI();
  bmi.sho();
}
function adjustImgSz(fctr)
{
  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();
}
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;
    }
  }
  //alert("constSz_:"+constSz_+" csz:"+csz); // debug
}
function urlToBMI(imgUrl)
{
  if (imgUrl == null) {
    return null;
  }
  var tokArr = imgUrl.split("/");
  if (tokArr.length < 6) {
    return null;
  }
  //alert("imgUrl:"+imgUrl+" tokArr.len:"+tokArr.length); // debug
  var model = tokArr[4];
  var region = tokArr[5];
  var prefix;
  var param;
  var time;
  var ifname = tokArr[7];
  var png = ".PNG";
  var sfxPos = ifname.indexOf(png);
  if (sfxPos == -1) {
    png = ".png";
    sfxPos = ifname.indexOf(png);
  }
  ifname = ifname.substring(0, sfxPos);
  tokArr = ifname.split(".");
  var iii = 0;
  if (model == "RUC") {
    if (tokArr.length == 3)	{
      prefix = tokArr[iii++]+".";
    }
    else {
      prefix = "";
    }
    param = tokArr[iii++];
    time = tokArr[iii++];
  }
  else {   // NAM
    if (tokArr.length == 4) {
      prefix = tokArr[iii++]+".";
    }        
    param = tokArr[iii++];
    if (tokArr.length == 3) {
      prefix = tokArr[iii]+".";
    }
    iii++;
    time = tokArr[iii++];
  }
  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_");  // debug
    bmi = myDefBMI_;
  }
  return bmi;
}
function shoRegion(region)
{
  var bmi = currentBMI().clone();
  bmi._region = region;
  bmi.sho();
  loop_.insert(bmi);
}
function shoPrefix(prefix, model)
{
  var bmi = currentBMI().clone();
  bmi._prefix = prefix;
  bmi._model = model;
  bmi.compatblTime();
  bmi.sho();
  loop_.insert(bmi);
}
function shoTime(time, model)
{
  var bmi = currentBMI().clone();
  bmi._time = time;
  bmi._model = model;
  bmi.compatblPrefix();
  bmi.sho();
  loop_.insert(bmi);
}
function shoParam(param)
{
  var bmi = currentBMI().clone();
  bmi._param = param;
  bmi.sho();
  loop_.insert(bmi);
}
function colorToggle()
{
  var bmi = currentBMI().clone();
  bmi._png = (bmi._png == ".png") ? ".PNG" : ".png";
  bmi.sho();
  loop_.insert(bmi);
}
function initSho()
{
  loop_ = new Loop();

  var bmi = currentBMI().clone();
  bmi.sho();
  loop_.insert(bmi);
}
function initViaCookey()
{
  cookey_ = new Cookey();
  //cookey_.delCookie();  // try to vaporize problem cookie
  var ckyVal = cookey_.getCookie();
  //alert("ckyVal:"+ckyVal); // debug
  if (ckyVal != null && ckyVal.length < 6) {
    cookey_.delCookie();
    ckyVal = null;
  }
  myDefBMI_ = urlToBMI(ckyVal);
  setConstSz(ckyVal);
  if (myDefBMI_ == null) {
    var defRegion_ = "NE";
    myDefBMI_ = new BMI("NAM", defRegion_, "curr.", "wfpm",
			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();
  }
}
function embedInitImgHtml()
{
  initViaCookey();
  var ht = 600;
  var wdth = 600;
  if (constSz_ == null) {
    // no const size specified so try to derive it from default img dim sizes
    var img = myDefBMI_.getImg();
    imgIncompleteMsg(img);
    if (img.complete) {
      // use img dim sizes
      ht = img.height;
      wdth = img.width;
    }
  }
  ht = calcHeight(ht);
  wdth = calcWidth(wdth);
  //alert("embedding init img h:"+ht+" w:"+wdth);  // debug
  document.write("<IMG height="+ht+" width="+wdth+" src=\"\" name=blipmap onClick=\"popupDisplay(event)\" >");
}

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) ? "RUC" : bmi._model;
  var region = (bmi == null) ? "NE" : 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);
}
