// include localization testing in mockup
// document.write('<script type="text/javascript" src="javascript/localization.js"></script>');

var iframeHistory = 0;
var ieVersion;
var detectedBrowser = navigator.appName;
var columns;
var nested_columns;
var content_containers;
var margins;
var padding;
var columnWidthDifference;
var ieColumnWidth;
var ieNestedColumnWidth;
var columnImages;
var columnImagesWidth;
var windowWidth;
var sendCurrentTab;

document.observe('dom:loaded', function() {
  browserDetection();
  storeElements();
  renderColumns();
  rotateDisplay();
  contentDecorations();
  eventHandlers();
  initializeWebApp();
  renderColumns();
});

window.onload = function() {
  pngFix();
}

function pngFix() {
  if (ieVersion == null) {
    browserDetection();
  }
  if (ieVersion == 6) {
    $$('img').each( function(img) {
      currentImage = img;
      imgName = currentImage.src.toUpperCase();
      if (imgName.endsWith("PNG")) {
         imgID = (currentImage.id) ? "id='" + currentImage.id + "' " : "";
         imgClass = (currentImage.className) ? "class='" + currentImage.className + "' " : "";
         imgTitle = (currentImage.title) ? "title='" + currentImage.title + "' " : "title='" + currentImage.alt + "' ";
         imgStyle = "display:inline-block;" + currentImage.style.cssText; 
         if (currentImage.align == "left") {
           imgStyle = "float:left;" + imgStyle;
         }
         if (currentImage.align == "right") {
           imgStyle = "float:right;" + imgStyle;
         }
         if (currentImage.parentElement.href) {
           imgStyle = "cursor:hand;" + imgStyle;
         }
         if (ieVersion == 6) {
           strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "margin:2px; width:" + currentImage.width + "px; height:" + currentImage.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + currentImage.src + "\', sizingMethod='scale');\"></span>";
           
         }
         else {
           strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "width:" + currentImage.width + "px; height:" + currentImage.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + currentImage.src + "\', sizingMethod='scale');\"></span>";
         }
         currentImage.outerHTML = strNewHTML;
      }
    });
  }
}


function storeElements() {
  // store the columns
  columns = $$('.column');
  nested_columns = $$('.nested_column');

  content_containers = $$('.content_container');

  //Enterprise may not have any content containers on the start page
  if(content_containers.length < 1)
  {
      return;
  }
  
  // read margins and padding from css, and remove px. margin / padding not supported in all browsers, so we have to have margin-left, padding-left
  margins = parseInt(($$('.content_container')[0]).getStyle('margin-left').substring(0, ($$('.content_container')[0]).getStyle('margin-left').length-2));
  padding = parseInt(($$('.content')[0]).getStyle('padding-left').substring(0, ($$('.content')[0]).getStyle('padding-left').length-2));
  columnWidthDifference = (margins+padding)+15*2;
  
  // store initial column width for ie. ie returns style, ff returns offsetWidth?
  ieColumnWidth = parseInt(columns[columns.length-1].getStyle('width'));
  ieNestedColumnWidth = parseInt(columns[columns.length-1].getStyle('width'));
  
  // slideshow image resizing. we want to resize images to be the width of the column they are displayed in
  // check to see if slideshow images exist on page, then store
  if ( $$('.slideShowImage') || $$('.scaleImage') ) {
    // array of slideshow image objects
    columnImages = ($$('.slideShowImage, .scaleImage'));
    // original image size
    columnImagesWidth = ($$('.slideShowImage, .scaleImage'));
    
    for (i = 0; i < columnImages.length; i++) {
      if (columnImages[i].width == 0) {
        columnImages[i].style.display = "block";
        columnImagesWidth[i] = columnImages[i].width;
        columnImages[i].style.display = "none";
      }
      else {
        columnImagesWidth[i] = columnImages[i].width;
      }
    }
  }
  if ($$('.slideshow_titles')[0]) {
    titles =  $$('.slideshow_titles .slideshow_title');
    slides =  $$('.slideshow_images img');
    description =  $$('.slideshow_description .slideshow_text');
    
    slideshow_images_container = slides[0].getOffsetParent();
    slideshow_images_container.style.height = slides[0].offsetHeight+"px"; 
    slideshow_description_container = description[0].getOffsetParent();
    slideshow_description_container.style.top =  slideshow_images_container.offsetHeight+90+"px";
    slideshow_parent = ($$('.slideshow_footers')[0]).getOffsetParent();
    ($$('.slideshow_footers')[0]).style.top = slideshow_images_container.offsetHeight+slideshow_description_container.offsetHeight+95+"px";
    slideshow_parent.style.height = slideshow_images_container.offsetHeight+slideshow_description_container.offsetHeight+($$('.slideshow_footers')[0]).offsetHeight+95+"px";
  }
}

function eventHandlers() {
  // event handlers to check if window has been resized. IE is slow
  // to do this, so we do a manual check, and then set a timeout to
  // do the update. actual behavior with resizing close to other
  // browsers now.

  updateScreen = self.setInterval("renderColumns()", 1000);

  if ( $$('.tabs_container li') ){
    tabs = $$('.tabs_container li');
    tabClasses = $$('.tabs_container li');
    for (i=0; i < tabs.length; i++) {
      tabClasses[i] = tabClasses[i].classNames().toString();
    }
    if (tabs[0]) {
      tabs[0].addClassName('selected_tab');
    }
    if ((sendCurrentTab != undefined) && ($('currentTab') != undefined)) {
      // for elibrary to load last tab clicked from hidden input
      if ($('currentTab').value == "") {
        tabs[0].addClassName('selected_tab');
      }
      else {
        tabs[0].removeClassName('selected_tab');
        displayTabPanels($('currentTab').value, tabs, tabClasses);
      }
    }
    tabs.each( function(tab) {
        tab.observe('click', function() {
            panel = tab.classNames().toString();
            displayTabPanels(panel, tabs, tabClasses);
        });
    });
  }
}

function displayTabPanels(panel, tabs, tabClasses) {
  // only passing in the name of the panel to display; ie from a link in the panel itself; not a tab
  if (tabs == undefined) {
     tabs = $$('.tabs_container li');
     tabClasses = $$('.tabs_container li');
    for (i=0; i < tabs.length; i++) {
      tabClasses[i] = tabClasses[i].classNames().toString();
    }
    for (i = 0; i < tabClasses.length; i++) {
      $(panel).style.display = "block";
      if (tabClasses[i].match(/selected_tab/)) {
        // we don't know the current panel. remove the classname from the selected tab, then extract classname from that to find panel to hide
        tabs[i].removeClassName('selected_tab');
        $(tabs[i].classNames().toString()).style.display = "none";
      }
      if (tabClasses[i] == panel) {
        tabs[i].addClassName('selected_tab');
        if ((sendCurrentTab) && ($('currentTab') != undefined)) {
          // for elibrary to keep track of current tab through cgi
          sendCurrentTab(tabClasses[i]);
        }
      }
    }
  }
  else {
    // tab is clicked
    for (i = 0; i < tabClasses.length; i++) {
      if ((tabClasses[i] == panel) || (tabClasses[i]+" selected_tab" == panel)) {
        if ($(panel) != null) {
          $(panel).style.display = "block";
        }
        tabs[i].addClassName('selected_tab');
        if ((sendCurrentTab != undefined) && ($('currentTab') != undefined)) {
          // for elibrary to keep track of current tab through cgi
          sendCurrentTab(tabClasses[i]);
        }
      }
      else {
        $(tabClasses[i]).style.display = "none";
        tabs[i].removeClassName('selected_tab');
      }
    }
  }
}

function browserDetection() {
  // check the browser version so we can run conditional code later.
  // needs to be expanded to return all browsers.
  if (detectedBrowser == 'Microsoft Internet Explorer') {
    var searchFor  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (searchFor.exec( navigator.userAgent) != null)
      ieVersion = parseFloat( RegExp.$1 );
  }
  else {
    ieVersion = -1;
  }
}

function contentDecorations() {
  // add in content decorations - only if greater than ie6
  if (ieVersion > 6 || ieVersion == -1) {
    content_containers.each( function(content_container) {
      content_container.insert('<div class="top_edge"></div><div class="right_edge"></div><div class="bottom_edge"></div><div class="left_edge"></div><div class="top_left"></div><div class="top_right"></div><div class="bottom_right"></div><div class="bottom_left"></div>');
    });
  }
}

function renderColumns() {
  // some outside scripts may try to call renderColumns before data is loaded
  if (columns == null) {
    storeElements();
  }
  
  if (ieVersion == null) {
    browserDetection();
  }
  
  // resize all images with class slideShowImage to size of parent column if the width of the image is less than the width of the column
  if (columnImages != null && columnImages[0]) {
    columns.each( function(column) {
      var testColumnWidth = 0;
      var testColumnWidth = (column.offsetWidth)-columnWidthDifference;
      for (j = 0; j < columnImages.length; j++) {
        if (columnImages[j].descendantOf(column)) {
          if (columnImagesWidth[j] > testColumnWidth) {
            columnImages[j].style.width = testColumnWidth-columnWidthDifference+"px";
          }
          else {
            columnImages[j].style.width = columnImagesWidth[j]+"px";
          }
        }
      }
    });
  }
  
  // make the columns all the same height
  // reset column heights
  if ($('copyright').style.textAlign != "") {   
  columns.each( function(column) {
    column.style.height =  "";
  });
	
  
  column_container_height = columns[0].offsetHeight;
  

  // set to current column container height
  columns.each( function(column) {
    column.style.height =  "";
  });
  column_container_height = columns[0].offsetHeight;
  
  columns.each( function(column) {
    if (column.offsetHeight > column_container_height) {
      column_container_height = column.offsetHeight;
    }
  });
  
  if (ieVersion == 6) {
      column_container_height = column_container_height + margins;
  }
  
  columns.each( function(column) {
    if (!column.className.match(/pct100/)) {
      column.style.height = column_container_height + "px";
    }
  });

  if (nested_columns != '') {
    nested_columns.each( function(nested_column) {
      nested_column.style.height = "";
    });
    
    nested_column_container_height = nested_columns[0].offsetHeight;
    
    nested_columns.each( function(nested_column) {
      if (nested_column.offsetHeight > nested_column_container_height) {
        nested_column_container_height = nested_column.offsetHeight;
      }
    });
    
    if (ieVersion == 6) {
        nested_column_container_height = nested_column_container_height + margins;
    }
    
    nested_columns.each( function(nested_column) {
      if (!nested_column.className.match(/pct100/)) {
        nested_column.style.height = nested_column_container_height + "px";
      }
    });
  }
}  
  // fix last column width to prevent ie from moving columns around
  if (ieVersion == 6 || ieVersion == 7) {
    if (columns[columns.length-1].hasClassName("middle")) {
      // right to left support. turn off column borders based on orientation
      if (columns[columns.length-1].getStyle("float") == "left") {
        columns[columns.length-1].style.borderRight = "none";
      }
      else {
        columns[columns.length-1].style.borderLeft = "none";
      }
    }

    columns[columns.length-1].style.width = ieColumnWidth-.1+"%";
    if (nested_columns[0]) {
      nested_columns[nested_columns.length-1].style.width = ieNestedColumnWidth-.1+"%";
    }
  }
}

function rotateDisplay() {
   // iphone vertical size
  if (document.width < 480 ) {
    $$('.columns_container')[0].style.width = '321px';
    for (i = 0; i < columns.length; i++) {
      columns[i].addClassName('pct100');
    }
  }
  
  // iphone horizontal size
  if (document.width == 480) {
    for (i = 0; i < columns.length; i++) {
      columns[i].removeClassName('pct100');
    }
  } 
}

/*--- MODAL DIALOG BOX ---*/

function createModalDialogBox(content, contentTitle,  isIframe, hasIframeControls, isDraggable, isClosable, canMaximize, width, height) {
  // content -> url to load through ajax or iframe
  // contentTitle -> Title to display in modal window
  // isIframe -> load content into an iframe (true/false)
  // hasIframeControls -> display controls for Iframe navigation. forward, back, and open initial url in new window (true/false)
  // isDraggable -> modal window can be moved by the user
  // isClosable -> modal window has a close button
  // canMaximize -> modal window has a button that will maximize the window
  // width -> width of modal window in pixels or percentage (100px, 50%)
  // height -> height of modal window in pixels or percentage (100px, 50%)  
  
  var modalBackground = document.createElement('div');
  modalBackground.setAttribute('id', 'modalBackground');
  Element.extend(modalBackground);
  document.body.appendChild(modalBackground);
  
  if (modalBackground) {
    // get total height of document
    var documentHeight = 0;
    documentHeight += $$('.header_container')[0].offsetHeight;
    for (i = 0; i < $$('.header_menu_container').length; i++) {
      documentHeight += $$('.header_menu_container')[i].offsetHeight;
    }
    for (i = 0; i < $$('.columns_container').length; i++) {
      documentHeight += $$('.columns_container')[i].offsetHeight;
    }    
    documentHeight += $$('.footer_container')[0].offsetHeight;
    $('modalBackground').style.height = documentHeight+"px";
    // insert modal window into the main container which is modalBackground
    $('modalBackground').insert('<div id="modalWindow" style="display:none;"><div id="modalTitleBar"><div id="modalTitle"></div>');
    $('modalWindow').style.top = document.viewport.getScrollOffsets()[1]+'px';
    
    if (isClosable == true) {
      $('modalTitleBar').insert('<input id="modalClose" type="button" onclick="modalClose(\''+alert_closeMessage+'\');"/>');
    }
    if (width != '') {
      $('modalWindow').style.width = width;
    }
    if (height != '') {
      if (height.endsWith('%')) {
        height = height.substring(0, height.length-1);
        if (height.length < 3) {
          height = "0."+height;
          if (ieVersion == 6) {
             height = height * document.body.clientHeight;
          }
          else {
            height = Math.round(height * document.viewport.getHeight());
          }
        }
        else {
          if (ieVersion == 6) {
            height = document.body.clientHeight - 40;
          }
          else {
            height = document.viewport.getHeight() - 60;
          }
        }
        $('modalWindow').style.height = height+"px";
      }
    }
    if (canMaximize == true) {
      $('modalTitleBar').insert('<input id="modalMaximize" type="button" onclick="modalMaximize(\''+width+'\',\''+height+'\');"/>');
    }
    $('modalWindow').insert('</div><div id="modalContentContainer"></div><div class="top_edge"></div><div class="right_edge"></div><div class="bottom_edge"></div><div class="left_edge"></div><div class="top_left"></div><div class="top_right"></div><div class="bottom_right"></div><div class="bottom_left"></div></div>');
    $('modalTitle').update(contentTitle);
    if (isDraggable == true) {
      new Draggable('modalWindow', {handle: 'modalTitleBar', starteffect: null, endeffect:null} );
    }
  }
  
  if (isIframe == false) {
    Effect.Appear('modalWindow', { duration: 1.0, queue: 'end' });
    $('modalContentContainer').style.overflow = 'auto';
    new Ajax.Request(content,
    {
      // prevent caching
      method: 'post',
      onSuccess: function(transport) {
        var response =  transport.responseText;
        $('modalContentContainer').insert(response);
      },
      onFailure: function() {
        $('modalContentContainer').insert(msg_failedAjax);
      },
      onComplete: function() {
        initializeLoadedAjax();
      }
    });
  }
  else {
    // fade doesn't play well with iframes.
    $('modalWindow').style.display = "block";
    var initialHistoryLength = history.length;
    iframeHistory = history.length;
    iframeHeight =  $('modalWindow').offsetHeight - $('modalTitleBar').offsetHeight - 26;
    sizeModification = 0;
    $('modalContentContainer').insert('<iframe style="height:'+iframeHeight+'px;" name="modalIframe" id="modalIframe" src="'+content+'" frameborder="0" style="display:block"></iframe>');
    if (hasIframeControls == true) {
      $('modalContentContainer').insert('<div id="modalIframeControls"><input class="admin_button" type="button" id="modalIframeGoBack" onclick="modalIframeGoBack('+initialHistoryLength+');" value="'+button_modalIframeGoBack+'"/><input class="admin_button" type="button" id="modalIframeRemoveFrame" onclick="modalIframeRemoveFrame(\''+content+'\');" value="'+button_removeIframe+'"/><input class="admin_button" type="button" id="modalIframeGoForward" onclick="modalIframeGoForward();" value="'+button_modalIframeGoForward+'"/><div/>');
      if (ieVersion == 6) {
        sizeModification = 54;
        $('modalIframe').style.height = $('modalContentContainer').offsetHeight - $('modalIframeControls').offsetHeight - sizeModification + "px";
      }
      else {
        $('modalIframe').style.height = $('modalContentContainer').offsetHeight - $('modalIframeControls').offsetHeight + "px";
      }
    }
  }
}

function modalIframeGoBack(initialHistoryLength) {
  if (iframeHistory < history.length) {
    iframeHistory++;
    frames['modalIframe'].history.go(-1);
  }
}

function modalIframeGoForward(initialHistoryLength) {
    frames['modalIframe'].history.go(1);
}

function modalIframeRemoveFrame(initialURL) {
  window.open(initialURL, "sdPopup");
}

function modalMaximize(width, height) {
  if (width != $('modalWindow').style.width) {
    $('modalWindow').style.width = width;
    $('modalWindow').style.height = height+"px";
  }
  else {
    if (ieVersion == 6) {
      $('modalWindow').style.width = document.body.clientWidth-40+"px";
      $('modalWindow').style.height = document.body.clientHeight-40+"px";
    }
    else {
      $('modalWindow').style.width = document.viewport.getWidth()-60+"px";
      $('modalWindow').style.height = document.viewport.getHeight()-60+"px";
    }
  }
  if ($('modalIframe')) {
    if ($('modalIframeControls')) {
      if (ieVersion == 6) {
        sizeModification = 50;
        $('modalIframe').style.height = $('modalWindow').offsetHeight - $('modalIframeControls').offsetHeight - sizeModification + "px";
      }
      else {
        $('modalIframe').style.height = $('modalContentContainer').offsetHeight - $('modalIframeControls').offsetHeight + "px";
      }
    }
    else {
         $('modalIframe').style.height = $('modalWindow').offsetHeight - $('modalTitleBar').offsetHeight - 26 + "px";
    }
  }
}

function modalClose(closeMessage) {
  if (closeMessage) {
    // if calling closeMessage from outside createModalDialogBox, there will be no message
    // makes automatic closing possible
    var confirmClose = confirm(closeMessage);
    if (confirmClose) {
      Effect.Fade('modalBackground', { duration: 1.0, queue: 'end', afterFinish: function() {$('modalBackground').remove();} } );
    }
    else {
    }
  }
  else {
    Effect.Fade('modalBackground', { duration: 1.0, queue: 'end', afterFinish: function() {$('modalBackground').remove();} } );
  }
  
}

function submitForm(formName, submitAndMaximize, submitAndClose) {
  // formName -> id of form to submit
  // submitAndMaximize -> submit the form using id and maximize the window
  // submitAndClose -> submit the form using id and close modal window

  if ($('modalContentContainer')) {
    $(formName).request(
    {
      method: 'post',
      onSuccess: function(transport) {
        var response =  transport.responseText;
        $('modalContentContainer').innerHTML = response;
      },
      onFailure: function() {
        $('modalContentContainer').innerHTML = msg_failedAjax;
      },
      onComplete: function() {
        initializeLoadedAjax();
        if (submitAndMaximize) {
          modalMaximize();
        }
        if (submitAndClose) {
          modalClose();
        }
      }
    });
  }
  else {
    // not in a modal dialog box. submit form normally
    $(formName).request();
  }
}

function initializeLoadedAjax() {
  // this is for running code on the dom we just loaded through ajax
  // if a wizard panel is available on page load, show the first one, and the navigation
  if ($$('.wizard_panel')[0]) {
   ($$('.wizard_panel')[0]).style.display = "block";
   ($$('.wizard_navigation')[0]).style.display = "block";
   if ($$('.wizard_previous')[0]) {
     ($$('.wizard_previous')[0]).style.display = "none";
   }
  }
}

/*--- WIZARD ---*/

function wizard_validate(wizardContainer, currentPanel) {
  var wizard_panels = ($$('.'+wizardContainer+' .wizard_panel'));
  // modify this to false if needed.
  valid = true;
  
  if (wizard_panels[currentPanel]) {
    // passed in panel exists. do some validation here.
    // we can do custom validation based on the wizardContainer name
    // passed in.
    // if validation is not successful, return valid = false,
    // and mark invalid fields.
    $('previous_panel').value = currentPanel;
  }
  return valid;
}

function wizard_next(wizardContainer) {
  // pass in wizard container class. this allows for generic functions
  var wizard_panels = ($$('.'+wizardContainer+' .wizard_panel'));
  for (i = 0; i < wizard_panels.length; i++) {
    //find currently displayed panel
    if (wizard_panels[i].style.display == "block") {
      wizard_validate(wizardContainer, i);
      if (wizard_validate() == true) {
        // validation successful
        if (wizard_panels[i].getElementsBySelector('[class="select_a_panel"]')) {
          // branching inputs available on current panel. 
          // check to see which panel to jump to
          var selectedInputForBranching = wizard_panels[i].getElementsBySelector('[class="select_a_panel"]');
          for (j = 0; j < selectedInputForBranching.length; j++) {
            if (selectedInputForBranching[j].checked) {
              wizard_panels[i].style.display = "none";
              wizard_panels[selectedInputForBranching[j].value].style.display = "block";
              ($$('.'+wizardContainer)[0]).style.height = "90%";
              // displayed selected panel. stop looping.
              j = 999;
            }
            else {
              if (i < wizard_panels.length-1) {
                // validation was successful. hide this panel and show next
                wizard_panels[i].style.display = "none";
                i++;
                wizard_panels[i].style.display = "block";
                ($$('.'+wizardContainer)[0]).style.height = "90%";
              }
            }
          }
        }
        else {
          // just go to the next panel
          if (i < wizard_panels.length-1) {
            wizard_panels[i].style.display = "none";
            i++;
            wizard_panels[i].style.display = "block";
            ($$('.'+wizardContainer)[0]).style.height = "90%";
          }
        }
        if (i == wizard_panels.length-1) {
          ($$('.wizard_finish')[0]).style.display = "inline";
          ($$('.wizard_next')[0]).style.display = "none";
        }
        if (i == 0) {
          ($$('.wizard_previous')[0]).style.display = "none";
        } 
        else {
          ($$('.wizard_previous')[0]).style.display = "inline";
        }
      }
    }
  }
}

function wizard_previous(wizardContainer) {
  // pass in wizard container class. this allows for generic functions
  var wizard_panels = ($$('.'+wizardContainer+' .wizard_panel'));
  for (i = 0; i < wizard_panels.length; i++) {
    //find currently displayed panel
    if (wizard_panels[i].style.display == "block") {
      // don't validate current panel if trying to go to previous panel
      // user may be trying to view previous information to make the
      // current form valid, so we don't want them to get stuck.
       if (i > 0) {
        wizard_panels[i].style.display = "none";
        i--;
        wizard_panels[i].style.display = "block";
      }
      if (i < wizard_panels.length-1) {
        ($$('.wizard_next')[0]).style.display = "inline";
        ($$('.wizard_finish')[0]).style.display = "none";
      }
      if (i == 0) {
        ($$('.wizard_previous')[0]).style.display = "none";
      } 
      else {
        ($$('.wizard_previous')[0]).style.display = "inline";
      }
    }
  }
}

/*--- Slideshow ---*/
function nextSlideShow(id) {
  var currentSlide;
  var nextSlide;
  titles =  $$('.'+id+' .slideshow_titles .slideshow_title');
  slides =  $$('.'+id+' .slideshow_images img');
  description =  $$('.'+id+' .slideshow_description .slideshow_text');
  for (i=0; i < slides.length; i++) {
    if (slides[i].style.display != "none") {
      currentSlide = i;
      nextSlide = i;
      nextSlide++;
      if (nextSlide >= slides.length) {
        nextSlide = 0;
      }
    }
  }
  titles[currentSlide].style.display = "none";
  slides[currentSlide].style.display = "none";
  description[currentSlide].style.display = "none";
  new Effect.Appear(titles[nextSlide], { duration:0.5 });
  new Effect.Appear(slides[nextSlide], { 
    duration:0.5, 
    afterFinish: function() {
      slideshow_images_container = slides[nextSlide].getOffsetParent();
      slideshow_images_container.style.height = slides[nextSlide].offsetHeight+"px"; 
      new Effect.Appear(description[nextSlide], { 
        duration:0.5, 
        afterFinish: function() {
          slideshow_description_container = description[nextSlide].getOffsetParent();
          slideshow_description_container.style.top =  slideshow_images_container.offsetHeight+90+"px";
          ($$('.'+id+' .slideshow_footers')[0]).style.top = slideshow_images_container.offsetHeight+slideshow_description_container.offsetHeight+95+"px";
          ($$('.'+id)[0]).style.height = slideshow_images_container.offsetHeight+slideshow_description_container.offsetHeight+($$('.'+id+' .slideshow_footers')[0]).offsetHeight+95+"px";
        }
      });
    } 
  });
}

function previousSlideShow(id) {
  var currentSlide;
  var nextSlide;
  titles =  $$('.'+id+' .slideshow_titles .slideshow_title');
  slides =  $$('.'+id+' .slideshow_images img');
  description =  $$('.'+id+' .slideshow_description .slideshow_text');
  for (i=0; i < slides.length; i++) {
    if (slides[i].style.display != "none") {
      currentSlide = i;
      nextSlide = i;
      nextSlide--;
      if (nextSlide <= -1 ) {
        nextSlide = slides.length-1;
      }
    }
  }
  titles[currentSlide].style.display = "none";
  slides[currentSlide].style.display = "none";
  description[currentSlide].style.display = "none";
  new Effect.Appear(titles[nextSlide], { duration:0.5 });
  new Effect.Appear(slides[nextSlide], { 
    duration:0.5, 
    afterFinish: function() {
      slideshow_images_container = slides[nextSlide].getOffsetParent();
      slideshow_images_container.style.height = slides[nextSlide].offsetHeight+"px"; 
      new Effect.Appear(description[nextSlide], { 
        duration:0.5, 
        afterFinish: function() {
          slideshow_description_container = description[nextSlide].getOffsetParent();
          slideshow_description_container.style.top =  slideshow_images_container.offsetHeight+90+"px";
          ($$('.'+id+' .slideshow_footers')[0]).style.top = slideshow_images_container.offsetHeight+slideshow_description_container.offsetHeight+95+"px";
          ($$('.'+id)[0]).style.height = slideshow_images_container.offsetHeight+slideshow_description_container.offsetHeight+($$('.'+id+' .slideshow_footers')[0]).offsetHeight+95+"px";
        }
      });
    } 
  });  
}

function playSlideShow(id, duration) {
    if (typeof(duration)=='undefined') {
        duration = 10000;
    }
    $$('.'+id+' .playSlideShow')[0].style.display='none';
	$$('.'+id+' .stopSlideShow')[0].style.display='inline-block';
  play = self.setInterval("nextSlideShow(\'"+id+"\')", duration);
}

function stopSlideShow(id) {
	$$('.'+id+' .playSlideShow')[0].style.display='inline-block';
	$$('.'+id+' .stopSlideShow')[0].style.display='none';
  window.clearInterval(play);
}

/*--- WEB APP SPECIFIC JS ----------------------------------------------------*/

/* web app specific initialization code goes here */
function initializeWebApp() {
  // from Enterprise v2
  
  // ie can't display iframes with only an image as the source and still have a transparent background
    if($('headerblock')!=undefined){

        if (ieVersion > -1) {
            if ($('headerblock')) {
                iframeSource = $('headerblock').src;
                if (iframeSource.endsWith("png") || iframeSource.endsWith("gif") || iframeSource.endsWith("jpg")) {
                    $('header').insert('<div class="branding_container"><div style="background-image:url('+iframeSource+') !important;"></div> <div class="branding_subheading"></div></div>');
                }
                else {
                    $('headerblock').style.display = 'block';
                }
            }
        }
        else {
            $('headerblock').style.display = 'block';
        }
    }

  if ($$('#languagePicker div')[0]) {
    if ( $$('#languagePicker div')[0].empty() ) {
      $$('.header_menu_container')[0].style.display = 'none';
    }
  }
  
  if ($('recordsOptions') && $('recordsOptions').className == ""){
    $('recordsOptions').style.display = 'none';
    var checkedRecord = $$('.checkedRecordContainer');
    var checkedRecordLength = checkedRecord.length;
    for (i=0; i<checkedRecordLength; i++) {
      checkedRecord[i].style.display = 'none';
    }
  }
  if ($$('.properties')) {
    var properties = $$('.properties');
    for (i = 0; i < properties.length; i++) {
      var anchors = properties[i].select('a');
      for (j = 0; j < anchors.length; j++) {
        anchors[0].className = "documentSummary_first_anchor";
        if (ieVersion == 6) {
          anchors[0].insert('<div style="float:left; clear:both; margin-top:-6px;"></div>');
        }
      }
    }
  }
  if (ieVersion != -1) {
    if (document.getElementById("coverImage")) {
      imageSource = document.getElementById("coverImage").src;
      // the image is blank, but ie returns the host url.
      if ((imageSource.charAt(imageSource.length-1) == "/")) {
        document.getElementById("coverImage").style.display = 'none';
      }
    }
  }
  if ($('profilePalette')) {
    $('profilePalette').style.display = "none";
  }
}

/* display checkboxes for search results */
function displayCheckBoxes() {
  var checkedRecord = $$('.checkedRecordContainer');
  var checkedRecordLength = checkedRecord.length;
  if ($('recordsOptions').offsetHeight > 0) {
    new Effect.BlindUp('recordsOptions', {duration:0.5 } );
    for (i=0; i<checkedRecordLength; i++) {
      new Effect.Fade(checkedRecord[i], { duration:0.5});
    }
  }
  else {
    new Effect.BlindDown('recordsOptions', {duration:0.5 } );
    for (i=0; i<checkedRecordLength; i++) {
      checkedRecord[i].style.display = 'none';
      new Effect.Appear(checkedRecord[i], { duration:0.5 });
    }
    $('recordsOptions').style.position = 'relative';
  }
}

/* display checkboxes for federated search results */
function displayFedCheckBoxes(id) {
  var checkedRecord = $$('.fedCheckedRecordContainer'+id);
  var checkedRecordLength = checkedRecord.length;
  if ($('fedRecordsOptions'+id).offsetHeight > 0) {
    new Effect.BlindUp('fedRecordsOptions'+id, {duration:0.5 } );
    for (i=0; i<checkedRecordLength; i++) {
      new Effect.Fade(checkedRecord[i], { duration:0.5});
    }
  }
  else {
    new Effect.BlindDown('fedRecordsOptions'+id, {duration:0.5 } );
    for (i=0; i<checkedRecordLength; i++) {
      checkedRecord[i].style.display = 'none';
      new Effect.Appear(checkedRecord[i], { duration:0.5 });
    }
    $('fedRecordsOptions'+id).style.position = 'relative';
  }
}

function displayRecordOptions() {
  if ($('recordsOptions').offsetHeight > 0) {
    new Effect.BlindUp('recordsOptions', {duration:0.5 } );
  }
  else {
    new Effect.BlindDown('recordsOptions', {duration:0.5 } );
    $('recordsOptions').style.position = 'relative';
  }
}

function getRadioCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function slideShow(id)
{
    if(document.getElementById(id).style.display=='none' || document.getElementById(id).style.display=='')
    {
        Effect.SlideDown(id, { duration: 0.5 });
    }
}

function justShow(id)
{
    Effect.SlideDown(id, { duration: 0.5 });    
}

function slideHide(id)
{
    if(document.getElementById(id).style.display!='none')
    {
        Effect.SlideUp(id, { duration: 0.5 });
    }
}

function onRoleChange(initial)
{
    var selectedRole = document.getElementById('roleSelect').options[document.getElementById('roleSelect').selectedIndex].value;
    if(selectedRole == 'ROLE_PROFILE_ADMIN' && initial==0)
    {
        slideShow('profilePalette');
    }
    else if(selectedRole == 'ROLE_PROFILE_ADMIN')
    {
        justShow('profilePalette');
    }
    else
    {
        slideHide('profilePalette');
    }
}


function toggleDivs(showId, hideId)
{
    document.getElementById(hideId).style.display = 'none';
    document.getElementById(showId).style.display = 'block';
}

function boldCurrentLocation(currentLocation)
{

    var listItems = $$('.'+currentLocation);
    if(listItems.length > 0)
    {
        listItems[0].style.fontWeight ="bold";
    }
}

function showWait(that, string)
{
    that.innerHTML="Working"+string;
    if(string.length<4)
    {
        string = string+'.';
    }
    else
    {
        string = '';
    }
    var t = setTimeout(function() {showWait(that,string);},500);
}
