//var productFormat = new Array('pwa_sn' => 'wide_conus');
// (for comparison checkboxes)
var productFormat = { "pwa_sn"      : "conus_wide1",
                      "pwa_us"      : "conus",
                      "pwa_us1"      : "conus",
                      "pwa_us2"      : "conus",
                      "pwa_us3"      : "conus",																						
                      "uspwag13"      : "conus",
                      "pwr_us"      : "conus",
                      "pwsr_us"      : "conus",
                      "lia_us"      : "conus",
                      "usliag13"      : "conus",
                      "lir_us"      : "conus",
                      "lisr_us"      : "conus",
                      "ce_us"      : "conus",
                      "ct_sfov"      : "conus_wide2",
                      "ct_us"      : "conus",
                      "usctag13"      : "conus",
                      "ca_us"      : "conus",
                      "o3_us"      : "conus_wide3",
                      "cld_g12"      : "fd1",
                      "cld_g12conus"      : "nh1",
                      "wi_dpi1"      : "wi",
                      "wi_dpi2"      : "wi",
                      "wi_dpi3"      : "wi",
                      "gsc_b03"      : "conus_wide4",
                      "gsc_b05"      : "conus_wide4",
                      "gsc_b08"      : "conus_wide4",
                      "gsc_b10"      : "conus_wide4",
                      "gsc_b11"      : "conus_wide4",
                      "gsc_b12"      : "conus_wide4",
                      "gsc_b15"      : "conus_wide4",
                      "gsc_b17"      : "conus_wide4",
                      "gsc_b19"      : "conus_wide4",											
                      "ge_all"       : "spec1",
                      "gw_all"       : "spec1",
                      "g10_s5"       : "south_america",
                      "g10_s8"       : "south_america",
                      "g10_sc8"       : "south_america2",
                      "g10_s11"       : "south_america",
                      "g10_s19"       : "south_america",
                      "g10_i1"       : "south_america",
                      "g10_i2"       : "south_america",
                      "g10_i3"       : "south_america",
                      "g10_i4"       : "south_america",
                      "g10_i5"       : "south_america",
                      "g10_ctp"       : "south_america",
                      "g10_sapw"       : "south_america",
                      "g10_sapwc"       : "south_america2",
                      "g10_sali"       : "south_america",
                      "g10_salic"       : "south_america2",
                      "g10_ctpcs"       : "south_america2"};

var webDir = '/goes/rt';
var mutils = new MiscUtils();

//===================================================================
// FUNCTIONS: BEGIN
//===================================================================
//-----------------------------------------------------
function onLoad() {
  onPageShow();
}

//-----------------------------------------------------
function onPageShow() {

  // start popup menu code
  if (!is_ie) {  // hide from IE
    startList();
  }

  // update menus for browsers that do preserve form field selections in cached pages (i.e., user
  // has used the back or forward button) - this will only work for browsers that do either support
  // the pageshow event (Firefox 1.5) or browsers that load the page from the server when using
  // the back/forward buttons - as of 4/3/2006, this will not work in Opera as it loads from cache
  // when the user uses the back or forward buttons and it doesn't execute the onload event for loading
  // pages from the cache and it doesn't support the pageshow event
  updateFormFields();

/*  if (getParam('test') == 'true') {
    test();  
  }*/

  var productMenu = document.getElementById('product');
  var selectedProductValue = getParam('product');
  if (document.getElementById('compare1')) {  // compare buttons exist
    var compareButtons = mutils.getElementsByClassName('compareButton');
    for (var i=0; i < compareButtons.length; i++) {
      addEvent(compareButtons[i], 'click', compare);
    }

    // for checkbox validation
    if (!is_ie) {
      var clearButtons = mutils.getElementsByClassName('clearButton');
      for (var i=0; i < clearButtons.length; i++) {
        addEvent(clearButtons[i], 'click', clear);
      }

      var compareCheckBoxes = mutils.getElementsByName('compare');
      for (var i=0; i < compareCheckBoxes.length; i++) {
        addEvent(compareCheckBoxes[i], 'click', compareCheck);
      }
    }
  }
  if ( document.getElementById('fullscreenEnable') ) {
    addEvent(document.getElementById('fullscreenEnable'), 'click', fullScreenEnable);
    addEvent(document.getElementById('fullscreenDisable'), 'click', fullScreenDisable);
  }

  if (!is_ie) {
    updateLeftNav();
  }

  var templateName = 'NA';
  if ( document.getElementById('templateName') ) {
    templateName = document.getElementById('templateName').value;
  } 

  if (templateName == 'multipleTimes') {
    addEvent(document.getElementById('time'), 'change', onTimeChange);
    addEvent(document.getElementById('time'), 'click', onTimeClick);

    addEvent(document.getElementById("imageType0"), 'click', onImageTypeChange);
    addEvent(document.getElementById("imageType3"), 'click', onImageTypeChange);
    if ( document.getElementById("imageType4") )  addEvent(document.getElementById("imageType4"), 'click', onImageTypeChange);

    addEvent(document.getElementById("radioButtonContainer_image"), 'click', onImageTypeClick);
    addEvent(document.getElementById("radioButtonContainer_allani"), 'click', onImageTypeClick);
    if ( document.getElementById("radioButtonContainer_animgif") )  addEvent(document.getElementById("radioButtonContainer_animgif"), 'click', onImageTypeClick);
  } else if (templateName == 'multipleFiles') {
    addEvent(document.getElementById('fileToView'), 'change', onFileToViewChange);
    addEvent(document.getElementById("previousDay"), 'click', onPreviousDayClick);
    addEvent(document.getElementById("nextDay"), 'click', onNextDayClick);
  } else if (templateName == 'compare') {
    addEvent(document.getElementById('time'), 'change', onTimeChange);
    addEvent(document.getElementById('time'), 'click', onTimeClick);

    addEvent(document.getElementById("imageType0"), 'click', onImageTypeChange);
    addEvent(document.getElementById("imageType1"), 'click', onImageTypeChange);
    addEvent(document.getElementById("imageType2"), 'click', onImageTypeChange);

    addEvent(document.getElementById("radioButtonContainer_toggle"), 'click', onImageTypeClick);
    addEvent(document.getElementById("radioButtonContainer_fader"), 'click', onImageTypeClick);
    addEvent(document.getElementById("radioButtonContainer_panel"), 'click', onImageTypeClick);
  }

  updateNavCookie();
}

//-----------------------------------------------------
/*function test() {
  addEvent(document.getElementById('clear1'), 'click', clear);
  addEvent(document.getElementById('clear2'), 'click', clear);
//  addEvent(document.getElementById('clear3'), 'click', clear);
  addEvent(document.getElementById('clear4'), 'click', clear);

  for (prod in productFormat) { 
    addEvent(document.getElementById('compare_' + prod), 'click', compareCheck);
  }
}*/

//-----------------------------------------------------
function clear() {
  var checkbox = document.form1.compare;
  for (var i=0; i < checkbox.length; i++) {
    checkbox[i].checked = false;
  }
  var compareCheckBoxes = mutils.getElementsByName('compare');
  for (var i=0; i < compareCheckBoxes.length; i++) {
    prod = compareCheckBoxes[i].getAttribute("value");
    document.getElementById('compare_' + prod).removeAttribute('disabled');
    document.getElementById('compareContainer_' + prod).style.backgroundColor = "#c9e2f0";
  }
  document.form1.firstChecked.value = '';
} 


//-----------------------------------------------------
function compareCheck() {
  var oEvent = arguments[0];
  var t = oEvent.target;
  var checkboxClicked = t.getAttribute('id');
  var currentProduct = checkboxClicked.substr(8);

  eval('var checkbox = document.form1.compare_' + currentProduct);

  var compareCheckBoxes = mutils.getElementsByName('compare');
  var c;
  var nChecked = document.form1.nChecked.value;
  if (checkbox.checked == true) { // disable all incompatible checkboxes 
    nChecked++;
    document.form1.nChecked.value = nChecked;
    if (document.form1.firstChecked.value == '') {
      document.form1.firstChecked.value = currentProduct;
    }
    var prod = '';
    for (var i=0; i < compareCheckBoxes.length; i++) {
      prod = compareCheckBoxes[i].getAttribute("value");
      c = document.getElementById('compare_' + prod);
      cc = document.getElementById('compareContainer_' + prod);
      eval('checkbox = document.form1.compare_' + prod);
      if (checkbox.checked != true && productFormat[prod] != productFormat[document.form1.firstChecked.value]) {
        cc.style.backgroundColor = "#cccccc";
      }
    }
  } else { // enable all incompatible checkboxes 
    nChecked--;
    document.form1.nChecked.value = nChecked;

    for (var i=0; i < compareCheckBoxes.length; i++) {
      prod = compareCheckBoxes[i].getAttribute("value");
      c = document.getElementById('compare_' + prod);
      cc = document.getElementById('compareContainer_' + prod);
      eval('checkbox = document.form1.compare_' + prod);
      if (checkbox.checked != true && productFormat[prod] == productFormat[document.form1.firstChecked.value]) {
        c.removeAttribute('disabled');
        cc.style.backgroundColor = "#c9e2f0";
      }
    }
    if (nChecked <= 0) {
      clear();
    }
  }

}

//-----------------------------------------------------
function updateNavCookie() {
  var n_nav2 = document.getElementById("form1").n_nav2.value;

  var nState = new Array();
  for (var i=0; i < n_nav2; i++) {
    if ( document.getElementById('nav3container_' + i).style.display == 'block' ) {
      nState.push(i);
    }
  }
  var navState = nState.join('|');
  setCookie("navState",navState,"","");
}

//-----------------------------------------------------
function updateLeftNav() {
  var selectedProductValue = getParam('product');

  // open up nav that corresponds to selected product and mark selected product
  if (selectedProductValue != '' && selectedProductValue != 'compare') {
    var selectedLink = document.getElementById("link_" + selectedProductValue);
    var p = selectedLink;
    while (p.parentNode) {
      p = p.parentNode;
      if (p.tagName == 'UL') {
        break;
      }
    }
    var index = p.getAttribute('id').substr(14);
    p.style.display='block';
    document.getElementById('nav2_' + index).style.fontWeight="bold";
    document.getElementById('nav2_' + index).style.color="black";
    var txt = document.createTextNode('>>');
    selectedLink.appendChild(txt);
    selectedLink.style.color="black !important";
  }

  // restore state of nav as stored in cookie
  printDebug(document.cookie);
  if (document.cookie != '') {
    var nState = getCookieValue("navState");
    printDebug(nState);    
    if (nState != '' && nState != null) {
      var navState = nState.split('|');
      for (var i=0; i < navState.length; i++) {
        document.getElementById('nav3container_' + navState[i]).style.display = 'block';
        document.getElementById('minus' + navState[i]).style.display = 'inline !important';
        document.getElementById('plus' + navState[i]).style.display = 'none';
      }
    }
  }
}

//-----------------------------------------------------
function printDebug(message) {
  var debug = getParam('debug');
  if (debug == 'true') {
    alert(message);
  }
}

//-----------------------------------------------------
function onPreviousDayClick() {
  var fileMenu = document.getElementById("fileToView");
  var productMenu = document.getElementById("product");
//  var selectedProductValue = productMenu[productMenu.selectedIndex].value;
  var selectedProductValue = document.getElementById("form1").product.value;

/*  var newIndex = fileMenu.selectedIndex - 1;
  if (newIndex < 0) {
    newIndex = fileMenu.length - 1;
  }*/

  var newIndex = fileMenu.selectedIndex + 1;
  if (newIndex >= fileMenu.length) {
    newIndex = 0;
  }

  var newFile = fileMenu[newIndex].value;

  var newURL = webDir + '/viewdata.php?product=' + selectedProductValue + '&fileToView=' + newFile;
  changeURL(newURL);
}

//-----------------------------------------------------
function onNextDayClick() {
  var fileMenu = document.getElementById("fileToView");
  var productMenu = document.getElementById("product");
//  var selectedProductValue = productMenu[productMenu.selectedIndex].value;
  var selectedProductValue = document.getElementById("form1").product.value;

/*  var newIndex = fileMenu.selectedIndex + 1;
  if (newIndex >= fileMenu.length) {
    newIndex = 0;
  }*/

  var newIndex = fileMenu.selectedIndex - 1;
  if (newIndex < 0) {
    newIndex = fileMenu.length - 1;
  }

  var newFile = fileMenu[newIndex].value;

  var newURL = webDir + '/viewdata.php?product=' + selectedProductValue + '&fileToView=' + newFile;
  changeURL(newURL);
}

//-----------------------------------------------------
function compare() {

  var formFields = document.forms['form1'].elements;
  var element;
  productList = new Array();
  for (var i=0; i < formFields.length; i++) {
    element = formFields[i];
    if (element.type == 'checkbox' && element.checked == true) {
      productList.push(element.value);
    }
  }

  var newURL = webDir + '/viewdata.php?product=compare&productList=' + productList.join('|');
  changeURL(newURL);
}

//-----------------------------------------------------
function fullScreenEnable() {
  //banner and navcol
  document.getElementById("banner").style.display = 'none';
  document.getElementById("navcol").style.display = 'none';
  document.getElementById("fullscreenEnable").style.display = 'none';
  if (document.getElementById("controlNav")) {
    document.getElementById("controlNav").style.display = 'none';
  }
  document.getElementById("fullscreenDisable").style.display = 'block';
  
}

//-----------------------------------------------------
function fullScreenDisable() {
  document.getElementById("banner").style.display = 'block';
  document.getElementById("navcol").style.display = 'table-cell';
  document.getElementById("fullscreenEnable").style.display = 'block';
  document.getElementById("fullscreenDisable").style.display = 'none';
  if (document.getElementById("controlNav")) {
    document.getElementById("controlNav").style.display = 'table';
  }
  
}

//-----------------------------------------------------
function updateFormFields() {
  var formFields = document.forms['form1'].elements;
  var type;
  var tagname;
  var idName = '';
  var paramval;
  for (var i=0; i < formFields.length; i++) {
    tagname = formFields[i].tagName;
    if (tagname == 'INPUT' || tagname == 'SELECT') {
      if (tagname == 'INPUT' && formFields[i].getAttribute("type") == 'radio') {
        // determine what the imageType value is in the URL
        idName = formFields[i].getAttribute('name');
        var paramval = getParam(idName);
        eval('var radioSet = document.getElementById("form1").' + idName);

        // if there is not an imageType specified in the query string, set to image
        if (paramval == '') {
          paramval = radioSet[0].value;
        }

        if (formFields[i].value == paramval) {
          formFields[i].checked = true;
        }
      } else if (tagname == 'INPUT' && formFields[i].getAttribute("type") == 'text') {
        // determine what the imageType value is in the URL
        idName = formFields[i].getAttribute('name');
        var paramval = getParam(idName);
        if (paramval != '') {
          // change the text box
          formFields[i].value = paramval;
        }
      } else if (tagname == 'SELECT') {
        idName = formFields[i].getAttribute('id');
        var paramval = getParam(idName);
        eval('var menu = document.getElementById("form1").' + idName);

        // if there is not a time specified in the query string, set to latest   
        if (paramval == '') {
          paramval = menu[0].value;
        }
        // change the menu
//        for (var j=0; i < formFields[i].length; j++) {
        for (var j=0; j < formFields[i].length; j++) {
          if (menu[j].value == paramval) {
            menu[j].selected = true;
            break;
          }  // if formFields
        }  // for var j
      }  // if tagname == INPUT ...
    }  // if tagname == INPUT || tagname == SELECT
  }  // for var i
}

//-----------------------------------------------------
function getParam(param) {
  // get the value for the requested GET parameter from the query string

//  var rExp = /\?[^#]+/;
  var rExp = /\?.*$/;
  var queryString = window.location.href.substr(window.location.href.search(rExp) + 1);
  rExp = /#/;
  var ind = queryString.search(rExp);
  if (ind != -1) {
    queryString = queryString.substr(0, ind);
  }
  var paramStrings = queryString.split('&');
  var keyVal = new Array();
  var paramValue = '';
  for (var i=0; i < paramStrings.length; i++) {
    keyVal = paramStrings[i].split('=');
    if (keyVal[0] == param) {
      paramValue = keyVal[1];
      break;
    }
  }

  return paramValue;
}

//-----------------------------------------------------
function changeURL(url) {
  /* if Opera, then change so that the page can not be accessed via the 
     history, i.e., the Back/Forward buttons.  This is because Opera currently
     does not execute the onload (or any JavaScript) when loading from the cache
     (which it does if using the Back/Forward buttons) and therefore the query string
     in the URL and what is being displayed gets out of sync with what is selected
     in the form fields, which are preserved when loaded from cache
  */ 
  if (is_opera) {
    window.location.replace(url);
  } else {
    window.location.href = url;
  }
}

//-----------------------------------------------------
function show() {
  var elem;
  for (var i=0; i < arguments.length; i++) {
    eval('elem = document.getElementById("' + arguments[i] + '")');
    elem.style.display = 'block';
  }
}

//-----------------------------------------------------
function hide() {
  var elem;
  for (var i=0; i < arguments.length; i++) {
    eval('elem = document.getElementById("' + arguments[i] + '")');
    elem.style.display = 'none';
  }
}


//-----------------------------------------------------
function viewDescription() {
  show('moreText'); 
  hide('moreLink');

  var rExp = /#.*$/;
  var end = window.location.href.search(rExp);
  if (end == 0) {
    var url = window.location.href;
  } else {
    var url = window.location.href.substr(0, end);
  }

  changeURL(url + '#description');
}

//-----------------------------------------------------
function hideDescription() {
  hide('moreText'); 
  show('moreLink');
}

//-----------------------------------------------------
function onImageTypeClick() {
  var oEvent = arguments[0];
  var t = oEvent.target;
  var tName = t.tagName;
  var c = t.getAttribute('class');

  // go up through the parents of target element until you
  // get the appropriate element to see it's ID to determine
  // which radio button table cell was clicked
  while (tName != 'td' && c != 'radioButtonContainer') {
    t = t.parentNode;
    tName = t.tagName;
    c = t.getAttribute('class');
    if (t.getAttribute("id") == 'contentContainer') {
      c = '';
      break;
    }
  }

  if (c == 'radioButtonContainer') {
    var imageTypeClicked = t.getAttribute("id");
    var rExp = /radioButtonContainer_/;
    imageTypeClicked = imageTypeClicked.replace(rExp,'');

    var imageType = document.getElementById("form1").imageType;
    var imageTypeIndex = 0;
    for (i=0; i < imageType.length; i++) {
      if (imageType[i].value == imageTypeClicked) {
        imageTypeIndex = i;
        break;
      }
    }

    imageType[imageTypeIndex].checked = true;
    onImageTypeChange();
  }
}

//-----------------------------------------------------
function onImageTypeChange() {

  var timeMenu = document.getElementById('time');
  var productMenu = document.getElementById('product');
  var imageType = document.getElementById("form1").imageType;

  var selectedTimeValue = timeMenu[timeMenu.selectedIndex].value;

  // get product value from query string instead of Jump Menu because referring to Jump Menu won't work
  // for product=compare
//  var selectedProductValue = productMenu[productMenu.selectedIndex].value;
  var selectedProductValue = getParam('product');
  if (selectedProductValue == 'compare') {
    var productList = getParam('productList');
  }

  var imageTypeIndex = 0;
  for (i=0; i < imageType.length; i++) {
    if (imageType[i].checked == true) {
      imageTypeIndex = i;
      break;
    }
  }

  var previouslySelectedImageType = document.getElementById('form1').previouslySelectedImageType.value;
  if (previouslySelectedImageType != imageType[imageTypeIndex].value) {
    var newURL = webDir + '/viewdata.php?product=' + selectedProductValue + '&time=' + selectedTimeValue + '&imageType=' + imageType[imageTypeIndex].value;
    if (selectedProductValue == 'compare') {
      changeURL(newURL + '&productList=' + productList);
    } else {
      changeURL(newURL);
    }
  }
}

//-----------------------------------------------------
function onProductChange() {

  // determine what is selected and the value of selections
  var productMenu = document.getElementById('product');
//  var selectedProductValue = productMenu[productMenu.selectedIndex].value;
  var selectedProductValue = document.getElementById("form1").product.value;

  // load new URL 
  if (selectedProductValue != '') {  
    var newURL = webDir + '/viewdata.php?product=' + selectedProductValue;
    changeURL(newURL);
  } else {
    var previouslySelectedProduct = document.getElementById('form1').previouslySelectedProduct.value;
    var previouslySelectedProductIndex = 0;
    for (i=0; i < productMenu.length; i++) {
      if (productMenu[i].value == previouslySelectedProduct) {
        previouslySelectedProductIndex = i;
        break;
      }
    }
    productMenu[previouslySelectedProductIndex].selected = true;

  }
}

//-----------------------------------------------------
function onTimeClick() {
  var oEvent = arguments[0];
  stopProp(oEvent);
}

//-----------------------------------------------------
function onTimeChange() {
  var oEvent = arguments[0];
  stopProp(oEvent);

  // determine what is selected and the value of selections
  var timeMenu = document.getElementById('time');
  var productMenu = document.getElementById('product');
  var imageType = document.getElementById("form1").imageType;

  var selectedTimeValue = timeMenu[timeMenu.selectedIndex].value;

  // get product value from query string instead of Jump Menu because referring to Jump Menu won't work
  // for product=compare
  var selectedProductValue = getParam('product');
  if (selectedProductValue == 'compare') {
    var productList = getParam('productList');
  }

  // load new URL based on form selections, unless you select a label in which case do nothing and
  // reset back to previous selection
  if (selectedTimeValue != '') {
    var imageTypeIndex = 0;
    if (selectedProductValue == 'compare') {
      for (i=0; i < imageType.length; i++) {
        if (imageType[i].checked == true) {
          imageTypeIndex = i;
          break;
        }
      }
      imageType[imageTypeIndex].checked = true;
    }

    var newURL = webDir + '/viewdata.php?product=' + selectedProductValue + '&time=' + selectedTimeValue + '&imageType=' + imageType[imageTypeIndex].value;
    if (selectedProductValue == 'compare') {
      changeURL(newURL + '&productList=' + productList);
    } else {
      changeURL(newURL);
    }
  } else {
    var previouslySelectedTime = document.getElementById('form1').previouslySelectedTime.value;
    var previouslySelectedTimeIndex = 0;
    for (i=0; i < timeMenu.length; i++) {
      if (timeMenu[i].value == previouslySelectedTime) {
        previouslySelectedTimeIndex = i;
        break;
      }
    }
    timeMenu[previouslySelectedTimeIndex].selected = true;
  }
}

//-----------------------------------------------------
function onFileToViewChange() {
  // determine what is selected and the value of selections
  var menu = document.getElementById('fileToView');
  var productMenu = document.getElementById('product');

  var selectedValue = menu[menu.selectedIndex].value;
//  var selectedProductValue = productMenu[productMenu.selectedIndex].value;
  var selectedProductValue = document.getElementById("form1").product.value;

  // load new URL based on form selections, unless you select a label in which case do nothing and
  // reset back to previous selection
  if (selectedValue != '') {  
    var newURL = webDir + '/viewdata.php?product=' + selectedProductValue + '&fileToView=' + selectedValue;
    changeURL(newURL);
  } else {
    var previouslySelectedValue = document.getElementById('form1').previouslySelectedFileToView.value;
    if (previouslySelectedValue == 'latest') {
      previouslySelectedIndex = 0;
    } else {
      var previouslySelectedIndex = 0;
      for (i=0; i < menu.length; i++) {
        if (menu[i].value == previouslySelectedValue) {
          previouslySelectedIndex = i;
          break;
        }
      }
    }
    menu[previouslySelectedIndex].selected = true;
  }
}

//-----------------------------------------------------
function addEvent( obj, type, fn ) {
  if (obj.addEventListener) {
    obj.addEventListener( type, fn, false );
  } else if (obj.attachEvent) {
    obj["e"+type+fn] = fn;
    obj[type+fn] = function() {
      obj["e"+type+fn]( window.event );
    };
    obj.attachEvent( "on"+type, obj[type+fn] );
  }
}

//-----------------------------------------------------
function stopProp(oEvent) {
  if (oEvent.stopPropagation) {
    oEvent.stopPropagation();
  } else {
    oEvent.cancelBubble = true;
  }
}

//===================================================================
// FUNCTIONS: END
//===================================================================

addEvent(window,'load', onLoad);
addEvent(window,'pageshow', function() {
                                          oEvent = arguments[0];
                                          if (oEvent.persisted) onPageShow();
                                       } );