




















var keepSessionAliveDialog;
var noSessionMainMenu; // jQuery.html(undefined) is a no-op, whereas jQuery.html(null) clears the element.
var pageTimeout = null;
var timeoutInSeconds;
var lastAccessTimeLocal;

function activateDatePickerFields()
{
  $(function() {
    $("input.datepicker").datepicker({
      changeMonth: true,
      changeYear: true
    });
  });
}

// If no values passed in then it uses default maxDate:+0 and yearRange:1900:+0
function activateDatePickerFieldsDob(minDateIn, maxDateIn, yearRangeIn)
{
  if (maxDateIn == null)
  {
    maxDateIn = '+0';
  }
  if (yearRangeIn == null)
  {
    yearRangeIn = '1900:+0';
  }
  $(function() {
    $("input.datepickerdob").datepicker({
      changeMonth: true,
      changeYear: true,
      minDate: minDateIn,
      maxDate: maxDateIn,
      yearRange: yearRangeIn
    });
  });
}

function getDropdownsForChosen() {
  return $("select").not(".chzn-disable").not(".dataTables_wrapper select");
}

function chosenAutocompleteFactory(placeholder)
{
  // chosen is loaded - activate all "chosen" drop-downs
  getDropdownsForChosen().each(function() {
      var width = $(this).data('outerWidthAtPageLoad');
      if (width) {
        // chosen 0.9.13 or higher is required to set width using an option to the chosen() function.
        $(this).width((width + 50) + 'px');
      }
      // Transform each select into a "chosen"
      $(this).chosen({disable_search_threshold: 7, allow_single_deselect: true, search_contains: true, placeholder_text: placeholder});
  });
  // Gives automated tests an ID to grab the text input element used for searching
  // Note: This assumes that there is only one <input type="text"/> inside each Chosen container (or it will make duplicate IDs).
  $('.chzn-container').each(function (i, x) { $(x).find('[type="text"]').attr('id', x.id + '_text'); });
}

function setNoSessionMainMenu(jsonString)
{
  noSessionMainMenu = jsonString;
}

function makePageExpire(timeLeftInSecs)
{
  if (getLastAccessTime() > 0 && $('#sessionExpiredContent').size() > 0)
  {
    if (!timeLeftInSecs)
    {
      timeLeftInSecs = timeoutInSeconds;
    }
    setPageTimeout(timeLeftInSecs - 60);
    if (window.addEventListener)
    {
      window.addEventListener('storage', refreshSessionTimeoutUi, false);
    }
    initModalDialog();
  }
}

function initSessionTimeout(shouldExpire, authorized, secondsRemaining)
{
  setLastAccessTime(authorized ? Date.now() : 0);
  timeoutInSeconds = secondsRemaining;
  if (shouldExpire && authorized)
  {
    makePageExpire();
  }
}

function setLastAccessTime(value)
{
  lastAccessTimeLocal = value;
  try {
    window.localStorage.setItem("lastAccessTime", value);
  } catch (e) {
    // Ignore.
  }
}

function getLastAccessTime()
{
  try {
    return window.localStorage.getItem("lastAccessTime");
  } catch (e) {
    return lastAccessTimeLocal;
  }
}

function setPageTimeout(seconds)
{
  clearPageTimeout();
  pageTimeout = setTimeout(refreshSessionTimeoutUi, seconds * 1000);
}

function clearPageTimeout()
{
  if (null != pageTimeout)
  {
    clearTimeout(pageTimeout);
  }
}

function stopPageExpiration()
{
  // Ignored.
}

function refreshSessionTimeoutUi(event)
{
  var idleTime = Date.now() - getLastAccessTime();
  var idleTimeInSeconds = Math.floor(idleTime / 1000);
  var timeLeftInSession = timeoutInSeconds - idleTimeInSeconds;
  if(timeLeftInSession <= 0)
  {
   expireMe();
  }
  else if(timeLeftInSession <= 60)
  {
   // if the session expires in less than 60 secs, display the session expire warning
   showKeepAliveQuestion(timeLeftInSession);
  }
  else
  {
   closeKeepAliveQuestion();
   makePageExpire(timeLeftInSession);
  }
}

function initModalDialog()
{
  
}

function showKeepAliveQuestion(timeLeftInSecs)
{
  setPageTimeout(timeLeftInSecs);
  try {
    keepSessionAliveDialog.dialog('open');
  } catch (e) {
    // Ignore.
  }
}

function closeKeepAliveQuestion()
{
  try {
    keepSessionAliveDialog.dialog('close');
  } catch (e) {
    // Ignore.
  }
}

function keepSessionAlive()
{
 $.ajax({
         url: "KeepIWebSessionAlive",
         type: "POST",
         success: function(result)
         {
          if(result == "success")
          {
           setLastAccessTime(Date.now());
           refreshSessionTimeoutUi();
          }
         },
         error: refreshSessionTimeoutUi
        });
}

function expireMe()
{
  var sessionExpiredContent = $('#sessionExpiredContent').html();
  var oldHeight = $('#userAndDateInfo').height();

  clearPageTimeout();
  if (window.removeEventListener)
  {
    window.removeEventListener('storage', refreshSessionTimeoutUi, false);
  }
  closeKeepAliveQuestion();
  setLastAccessTime(0);
  $('#content').html(sessionExpiredContent).css('padding-top', oldHeight);
  expiredSessionModal();
  $('#menu').html(noSessionMainMenu);
  document.title = 'Montana Immunization Information System';
  window.onbeforeunload = null;
}

function hdr_ref(object)
{
   if(document.getElementById)
   {
      return document.getElementById(object);
   }
   else if(document.all)
   {
      return eval('document.all.' + object);
   }
   else
   {
      return false;
   }
}

function hdr_expand(object)
{
   var object = hdr_ref(object);
   if(!object.style)
   {
      return false;
   }
   else
   {
      object.style.display = '';
   }
   if(window.event)
   {
      window.event.cancelBubble = true;
   }
}

function hdr_contract(object)
{
   var object = hdr_ref(object);
   if(!object.style)
   {
      return false;
   }
   else
   {
      object.style.display = 'none';
   }
   if(window.event)
   {
      window.event.cancelBubble = true;
   }
}

function hdr_toggle(object, open_close, open_icon, close_icon)
{
   var object = hdr_ref(object);
   var icone = hdr_ref(open_close);
   if(!object.style)
   {
      return false;
   }
   if(object.style.display == 'none')
   {
      object.style.display = '';
      icone.src = "/iweb/" + close_icon + "";
      save_menu_state();
   }
   else
   {
      object.style.display = 'none';
      icone.src = "/iweb/" + open_icon + "";;
      save_menu_state();
   }
}

function navToggle(itemId) {
  if (document.getElementById(itemId).className == "open") {
    document.getElementById(itemId).className = "";
  } else {
    document.getElementById(itemId).className = "open";
  }
}

//This function saves the state of all the opened submenus of the left navigation
//It stores all the opened menu ids in a cookie. It is called each time the user clicks
//and expands or detracts a menu.
function save_menu_state()
{
//All the menu items that are expandable are wrapped in <LI> tags
//We extract them to see if the are open or closed
  var nav_items = document.getElementById('nav').getElementsByTagName('LI');
  var menu_id;
  var menu_cookie = "siismenu=";
 for (var i = 0; i < nav_items.length; i++)
 {
   menu_id = nav_items[i].id;
   //Extract the menu item id and see if it belongs to the main menu,
   //if it does then we check to see if it is open
   if (menu_id  && menu_id.length >= 5 && menu_id.substr(0, 4) == "MMI_")
   {
      var id = menu_id.split('_');
      //If the menu item is expanded then we save its state.
      if(nav_items[i].className == 'open')
      {
 menu_cookie += "-" + id[1];
      }
   }
 }
  //Save the cookie and store it in the session.
  menu_cookie = menu_cookie + "-" + ";";
  document.cookie = menu_cookie;
}

function activateSpinner(includeChosen)
{
  if (includeChosen)
  {
    getDropdownsForChosen().each(
      function(object)
      {
        $(this).data('outerWidthAtPageLoad', $(this).outerWidth());
      }
    );
  }
  $("div#content").hide();
  $("div#waiting").show();
}

function resizePageCheck() {
  $("div#waiting").hide();
  $("div#content").show();
  var arr = ['scrollboxVertHoriz', 'scrollbox','scrollbox2','scrollbox3'];
  var resizeFlag=false;
  var topWidth=$("div#content").width();
  $("div#content table").each(function(){
    if(jQuery.inArray($(this).parent().attr('class'), arr)<0){
      var newWidth=$(this).outerWidth();
      if (newWidth > topWidth) {
        topWidth=parseInt(newWidth);
        resizeFlag=true;
      };
    }
  });
  if (resizeFlag) {
    topWidth = topWidth + 170;
    $("div#main").css('min-width',topWidth);
    $("div#main").css('max-width',topWidth);
    $("div#bottomRoundGutter").css('min-width',topWidth);
    $("div#bottomRoundGutter").css('max-width',topWidth);
  }
}

function oldIEAutofocusHack() {
  if ($.browser.msie) {
    var ieMajorVersion = parseInt($.browser.version, 10);
    if (ieMajorVersion < 10) {
      var targetElement = $("input[autofocus]");
      if (targetElement.length > 1) {
        // In IE 7 (and other versions in Compatibility Mode) this attribute selector matches
        //   all elements with or without the specified attribute!
        // This is a workaround to filter out the false positives.
        targetElement = targetElement.filter(function() {
          return this.getAttributeNode("autofocus").specified;
        });
      }
      // Only targets the first element if there happen to be more than one.
      targetElement.eq(0).focus();
    }
  }
}


function addToOnload(myFunction) {
  var oldLoad = window.onload;
  window.onload = function() {
    oldLoad();
    eval(myFunction);
  }
}





function accordionSetup() {
  var $headerRows = $('.accordionTable .accordion').not('.accordionDefault');
  var $headerRowsDefault = $('.accordionTable .accordionDefault');
  $headerRows.siblings().hide();
  $headerRows.attr('title', 'Click to expand/shrink this section.');
  $headerRowsDefault.attr('title', 'Click to expand/shrink this section.');
  $('td', $headerRows).prepend('<img style="vertical-align: middle;" alt="=>" class="toggleImg" src="/iweb/images/accordionPlus.gif">');
  $('td', $headerRowsDefault).prepend('<img style="vertical-align: middle;" alt="=>" class="toggleImg" src="/iweb/images/accordionMinus.gif">');
  $headerRows.click(function() {
    $(this).siblings().toggle();
    var $image = $('.toggleImg', this);
    var src = ($image.attr('src') === '/iweb/images/accordionPlus.gif')
                ? '/iweb/images/accordionMinus.gif' : '/iweb/images/accordionPlus.gif';
    $image.attr('src', src);
  });
  $headerRowsDefault.click(function() {
    $(this).siblings().toggle();
    var $image = $('.toggleImg', this);
    var src = ($image.attr('src') === '/iweb/images/accordionPlus.gif')
                ? '/iweb/images/accordionMinus.gif' : '/iweb/images/accordionPlus.gif';
    $image.attr('src', src);
  });
}

function accordionSetupPatientDemographics() {
  var $headerRows = $('.accordionTable .accordion').not('.accordionDefault');
  var $headerRowsDefault = $('.accordionTable .accordionDefault');
  $headerRows.siblings().hide();
  $headerRows.attr('title', 'Click to expand/shrink this section.');
  $headerRowsDefault.attr('title', 'Click to expand/shrink this section.');
  $('td', $headerRows).prepend('<img style="vertical-align: middle;" alt="=>" class="toggleImg" src="/iweb/images/accordionPlusWhite.gif">');
  $('td', $headerRowsDefault).prepend('<img style="vertical-align: middle;" alt="=>" class="toggleImg" src="/iweb/images/accordionMinusWhite.gif">');
  $headerRows.click(function() {
    $(this).siblings().toggle();
    var $image = $('.toggleImg', this);
    var src = ($image.attr('src') === '/iweb/images/accordionPlusWhite.gif')
                ? '/iweb/images/accordionMinusWhite.gif' : '/iweb/images/accordionPlusWhite.gif';
    $image.attr('src', src);
  });
  $headerRowsDefault.click(function() {
    $(this).siblings().toggle();
    var $image = $('.toggleImg', this);
    var src = ($image.attr('src') === '/iweb/images/accordionPlusWhite.gif')
                ? '/iweb/images/accordionMinusWhite.gif' : '/iweb/images/accordionPlusWhite.gif';
    $image.attr('src', src);
  });
}

function accordionExpandAll() {
  var $headerRows = $('.accordionTable .accordion');
  $headerRows.siblings().show();
  $(".toggleImg").each(function() {
    $(this).attr('src', "/iweb/images/accordionMinus.gif");
  });

}

function accordionCompressAll() {
  var $headerRows = $('.accordionTable .accordion');
  $headerRows.siblings().hide();
  $(".toggleImg").each(function() {
    $(this).attr('src', "/iweb/images/accordionPlus.gif");
  });
}

function accordionExpandAllNewUI() {
  var $headerRows = $('.accordionTable .accordion');
  $headerRows.siblings().show();
  $(".toggleImg").each(function() {
    $(this).attr('src', "/iweb/images/accordionMinusWhite.gif");
  });

}

function accordionCompressAllNewUI() {
  var $headerRows = $('.accordionTable .accordion');
  $headerRows.siblings().hide();
  $(".toggleImg").each(function() {
    $(this).attr('src', "/iweb/images/accordionPlusWhite.gif");
  });
}

function oldIEWarningMessage() {
  var IEversion = -1;
  if (navigator.appName == 'Microsoft Internet Explorer') {
    var isTrident=false;
    var tridentRegex  = new RegExp("Trident/([0-9]{1,}[\.0-9]{0,})");
    if (tridentRegex.exec(navigator.userAgent) == null){
      isTrident=true;
    }
    var regEx = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (regEx.exec(navigator.userAgent) != null) {
      IEversion = parseFloat( RegExp.$1 );
    }
    if (isTrident && IEversion < 8.0) {
      $("#browserVersionAlertImg").show().tooltip({ position: { my: "right top", at: "right bottom" } });
    }
  }
}
