/* DOM scripting to force IE6 to perform :hover on <li> tags */
sfHover = function() 
{
    var sfEls = document.getElementById("nav").getElementsByTagName("li");
if (document.getElementById("hideDropDowns")) {
var dropDownFrame = document.getElementById("hideDropDowns");
}
for (var i=0; i<sfEls.length; i++) {
sfEls[i].onmouseover=function() {
className = this.className;
this.className+=" iehover";
if (dropDownFrame) {
dropDownFrame.style.visibility = "visible";
}
//remove comments for image swapping on top level nav items
//alert (this.className);
//switchImage('topnav_' + className,'on');
}
sfEls[i].onmouseout=function() {
this.className=this.className.replace(new RegExp(" iehover\\b"), "");
if (dropDownFrame) {
dropDownFrame.style.visibility = "hidden";
}
//remove comments for image swapping on top level nav items
//switchImage('topnav_' + this.className,'off');
}
}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);



function toggle_class(ele,cssClass) {
//console.log('ele=' + ele + ' cssClass=' + cssClass);
if (ele != '' && cssClass != '') {
var eleObj = document.getElementById(ele);
if(eleObj) {
var myClass = eleObj.className; 
if(!myClass) {
eleObj.className = cssClass;
} else if(myClass != cssClass) {
eleObj.className = cssClass;
} else {
//console.log('Not empty class');
eleObj.className = '';
} 
}
}
}

/* Return URL parameter utility */
/* Spry is using for Quick Find and for print page functionality */
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}


/* Text size widget script for resizing text on the page */

function fontSizeChange(newstyle) {
//active = getActiveStyleSheet();
switch (newstyle) {
case 'regular' : 
setActiveStyleSheet('regular');
break;
case 'larger' : 
setActiveStyleSheet('larger');
break;
case 'largest' : 
setActiveStyleSheet('largest');
break;
default :
setActiveStyleSheet('regular');
break;
}
}

function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
}

function getActiveStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
return null;
}

function getPreferredStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) return a.getAttribute("title");
}
return null;
}

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return (c.substring(nameEQ.length,c.length));
}
return null;
}

window.onload = function(e) {
var cookie = readCookie("style");
//alert(cookie);
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
}

window.onunload = function(e) {
var title = getActiveStyleSheet();
createCookie("style", title, 365);
}

var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
if (title == 'null') {
title = getPreferredStyleSheet();
}

setActiveStyleSheet(title);


/* DHTML popovers */
function getOSName()
{
var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
return OSName;
}


function showSplash(suffix) 
{
document.getElementById('overlaySplash' + suffix).style.visibility='visible';
document.getElementById('overlaySplashinner' + suffix).style.visibility='visible';
if (document.getElementById('Form' + suffix)) {
document.getElementById('Form' + suffix).style.visibility='visible';
document.getElementById('Form' + suffix).style.height=null; 
document.getElementById('Form' + suffix).style.display='block';
}
if (document.getElementById('Response' + suffix)) {
document.getElementById('Response' + suffix).style.visibility='hidden';
document.getElementById('Response' + suffix).style.height=0; 
document.getElementById('Response' + suffix).style.display='none';
} 
document.getElementById('overlaySplash' + suffix).style.display='block';
document.getElementById('overlaySplashinner' + suffix).style.display='block';
}

function hideSplash(suffix) 
{
document.getElementById('overlaySplash' + suffix).style.visibility='hidden';
document.getElementById('overlaySplashinner' + suffix).style.visibility='hidden';
if (document.getElementById('Form' + suffix)) {
document.getElementById('Form' + suffix).style.visibility='hidden';
document.getElementById('Form' + suffix).style.height=null; 
document.getElementById('Form' + suffix).style.display='none';
}
if (document.getElementById('Response' + suffix)) {
document.getElementById('Response' + suffix).style.visibility='hidden';
document.getElementById('Response' + suffix).style.height=0; 
document.getElementById('Response' + suffix).style.display='none';
} 
document.getElementById('overlaySplash' + suffix).style.display='none';
document.getElementById('overlaySplashinner' + suffix).style.display='none';
}

/* Rotate callouts in right-hand column, presumes 2 callouts. Also rotates hp get involved. */
var random_display = 1; // 0 = no, 1 = yes

function generate(x, y) {
var range = y - x + 1;
return Math.floor(Math.random() * range) + x;
}

function getNextCallout(number_of_callout,callout_list) {
if (random_display) {
i = generate(0, number_of_callout-1);
}
else {
i = (i+1) % number_of_callout;
}
var new_callout = callout_list[i];
return(new_callout);
}

function rotateNextCallout(number,list,id) {
var new_callout = getNextCallout(number,list);
document.getElementById(id).innerHTML = new_callout;
}

function rotateNextCalloutInOrder(place,total,list,id) {
if (place >= total) {
var new_callout = list[0];
} else {
var new_callout = list[place];
}
document.getElementById(id).innerHTML = new_callout;
}

/* rotate callouts onLoad */ 
function rotateCallout() 
{
    if (document.getElementById("callout1")) 
    {
        if(callout1_list)
        {
            if (callout1_list.length != 0) 
            {
                document.getElementById("callout1").setAttribute("class","sidebarWidget");
                document.getElementById("callout1").setAttribute("className","sidebarWidget"); 
                rotateNextCallout(number_of_callout1,callout1_list,"callout1");
            }
        }
    }
    if (document.getElementById("callout2")) 
    {
        if (callout2_list.length != 0) 
        {
            document.getElementById("callout2").setAttribute("class","sidebarWidget");
            document.getElementById("callout2").setAttribute("className","sidebarWidget"); 
            rotateNextCallout(number_of_callout2,callout2_list,"callout2");
        } 
    }
    if (document.getElementById("callout3")) 
    {
        if (callout3_list.length != 0) 
        {
            document.getElementById("callout3").setAttribute("class","sidebarWidget");
            document.getElementById("callout3").setAttribute("className","sidebarWidget"); 
            rotateNextCallout(number_of_callout3,callout3_list,"callout3");
        } 
    }
    if (document.getElementById("callout4")) 
    {
        if (callout4_list.length != 0) 
        {
            document.getElementById("callout4").setAttribute("class","sidebarWidget");
            document.getElementById("callout4").setAttribute("className","sidebarWidget"); 
            rotateNextCallout(number_of_callout4,callout4_list,"callout4");
        } 
    }
    if (document.getElementById("getInvolved")) 
    {
        if (getInvolved_list.length != 0) 
        {
            document.getElementById("getInvolved").setAttribute("class","clearfix");
            document.getElementById("getInvolved").setAttribute("className","clearfix");
            var count = readCookie('getInvolvedCount');
            if (count == null) 
            {
                count=0;
            } 
            else 
            {
                count++;
            }
            rotateNextCalloutInOrder(count,number_of_getInvolved,getInvolved_list,"getInvolved");
            if (count >= number_of_getInvolved) 
            {
                createCookie('getInvolvedCount', 0, 999); 
            } 
            else 
            {
                createCookie('getInvolvedCount', count, 999);
            }
        } 
    } 
}

/* Setup spry services to return Quick Find data, check URL first for parameter on load */
var dataFolder = '/data/quickfind/';
var initialLoad = dataFolder + 'initial.xml';
var dsServices = new Spry.Data.XMLDataSet(initialLoad, "/services/service",{useCache:false});
var dsSynonyms = new Spry.Data.NestedXMLDataSet(dsServices, "synonyms/synonym");

var quickFindLook = gup('quickFind');
if (quickFindLook != '') { 
setText(quickFindLook + '.xml');
}

function setText(url){
var lookupUrl = dataFolder + url;
dsServices.setURL(lookupUrl);
dsServices.loadData();
}

/* print page functionality */
/* check for print url param onLoad */
function checkPrint() { 
var printCheck = gup('print');
if (printCheck == 1) { 
setPrintStyleSheet();
}
else
{
unSetPrintStyleSheet();
}
}

function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}

addLoadEvent( function(){ add_print_link( 'nav' ) } );

function add_print_link( id ){
if( !document.getElementById ||
!document.getElementById( id ) ) return;

// add extra functions to page tools list
var print_page = document.getElementById( id );

// create print link
var print_function = document.createElement('p');
print_function.className = 'print-link';
print_function.onclick = function(){ print_preview(); return false; };
print_function.appendChild( document.createTextNode( 'Print the Page' ) );

}

function print_preview() {
//set the print url param
var a;
a = window.location.href;
if(a.indexOf("?") != -1) {
if(a.indexOf("print") == -1) { 
window.location.href=a + '&print=1';
}
else {
window.location.href=a; 
}
}
else
{
window.location.href=a + '?print=1'
}
}

function setPrintStyleSheet() {
var a, b;
a = document.getElementById("printPreviewStyle");
b = document.getElementById("printStyle"); 
a.disabled = false;
b.disabled = false; 
add_preview_message();
window.print();
}

function unSetPrintStyleSheet() {
var a, b;
a = document.getElementById("printPreviewStyle");
b = document.getElementById("printStyle"); 
a.disabled = true;
b.disabled = true; 
}


function add_preview_message(){
var main_content = document.getElementById('page');
var main_body = main_content.parentNode;

if (document.getElementById){

var preview_message = document.createElement('div');
preview_message.id = 'preview-message';

// Create Heading
var preview_header = document.createElement('h3');
var preview_header_text = document.createTextNode('This is a print preview of this page');
preview_header.appendChild(preview_header_text);

// Create paragraph
var preview_para = document.createElement('p');
var preview_para_text = document.createTextNode('This box will not appear when you print. ');

var cancel_function_link = document.createElement('a');
cancel_function_link.onclick = function(){ cancel_print_preview(); return false; };
cancel_function_link.setAttribute('href', '#'); 
var cancel_function_link_text = document.createTextNode('Return to the existing page.');
cancel_function_link.appendChild(cancel_function_link_text);
preview_para.appendChild(preview_para_text); //
preview_para.appendChild(cancel_function_link);

// Put it all toegether
preview_message.appendChild(preview_header); 
preview_message.appendChild(preview_para);
main_body.insertBefore(preview_message, main_content);

}
}

function removePrintParam () {
currentLocation=window.location.href;
currentLocation=currentLocation.replace(/(&|\?)print=[^&]+/i,"");
window.location.href = currentLocation;
}


function cancel_print_preview() {
// Destroy the preview message
var print_preview = document.getElementById('preview-message');
var main_body = print_preview.parentNode;
main_body.removeChild(print_preview);

// Switch back stylesheet
//setActiveStyleSheet('default');
unSetPrintStyleSheet();
removePrintParam();
}

// Survey Cookie 

var noDaysCookieLasts = 999; // number of days the survey cookie should last

function checkSurveyCount() {
var page = window.location;
if (page == 'http://www.inova.org' || page == 'http://www.inova.org/' || page == 'http://www.inova.org/index.jsp') {
var count = readCookie('surveyCount');
if (count == null) {
count=1;
createCookie('surveyCount', count, noDaysCookieLasts);
}
else {
count++;
if (count == 2) {
showSplash('UserSurvey') ; 
}
createCookie('surveyCount', count, noDaysCookieLasts);
// remove below line before going to prod
//showSplash('UserSurvey') ; 
   }
}
}

//trim functions
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
return stringToTrim.replace(/\s+$/,"");
}


//form validation
function emailCheck(sentStr) {
var at="@";
var dot=".";
var str=trim(sentStr);
var lat=str.indexOf(at);
var lstr=str.length;
var ldot=str.indexOf(dot);
var alertMessage = "The email address " + str + " is invalid.";
if (str.indexOf(at)==-1){
alert(alertMessage);
return false;
}

if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert(alertMessage);
return false;
}

if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert(alertMessage);
return false;
}

if (str.indexOf(at,(lat+1))!=-1){
alert(alertMessage);
return false;
}

if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
alert(alertMessage);
return false;
}

if (str.indexOf(dot,(lat+2))==-1){
alert(alertMessage);
return false;
}

if (str.indexOf(" ")!=-1){
alert(alertMessage);
return false;
}
return true;
}


function getXhttp() {
var ajax_request;
if ( window.ActiveXObject ) {
var mSoftVersions = [
'MSXML2.DOMDocument.5.0',
'MSXML2.DOMDocument.4.0',
'MSXML2.DOMDocument.3.0',
'MSXML2.DOMDocument.2.0',
'MSXML2.DOMDocument',
'Microsoft.XmlDom',
'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP'
];
for ( i=0; i<mSoftVersions.length; i++ ) {
try {
ajax_request = new ActiveXObject ( mSoftVersions[i] );
} catch (e) {}
}
} else if (!ajax_request && typeof XMLHttpRequest != 'undefined') {
try {
ajax_request = new XMLHttpRequest;
} catch (e) {}
} else if (!ajax_request && window.createRequest) {
try {
ajax_request = window.createRequest;
} catch (e) {}
} else {
ajax_request = false;
}
return ajax_request;
}

function emailAFriend() {
var xml = getXhttp();
if ( !xml )
return false;
var url = "/forms/eProc_SendFriend.jsp";
xml.open('POST', url, true);
var location = document.getElementById('loc').value;
var name = document.getElementById('Name').value;
var from = document.getElementById('From').value;
var to = document.getElementById('To').value;
var message = document.getElementById('Message').value; 
var subject = 'Your friend has recommended a page from Inova.org';
var docloc = document.getElementById('loc').value;
if(from==""){
alert("Please enter your email address.");
return false;
} else {
var arrSender = from.split(",");
var arrSenderLen = arrSender.length;
if (arrSenderLen > 1) {
alert("Please enter only one sender email address.");
return false;
} else {
arrSender.splice(0,1,trim(arrSender[0]));
if(emailCheck(from)==false) {
return false;
}
}
}
if(to==""){
                alert("Please enter a recipient's email address.");
return false;
  } else {
     var arrRecipients = to.split(",");
var arrRecipientsLen = arrRecipients.length;
if (arrRecipientsLen > 10) {
                 alert("Please note that you are limited to sending ten emails at one time. Please limit this send to ten recipients.");
return false; 
} else {
for ( var i=0, len=arrRecipientsLen; i<len; ++i ){
arrRecipients.splice(i,1,trim(arrRecipients[i]));
if(emailCheck(arrRecipients[i])==false) {
return false;
}
}
}
}
if(location==""){
location = 'http://www.inova.org'; 
} 
var params = 'loc=' + location + '&Name=' + name + '&From=' + from + '&To=' + to + '&Message=' + message + '&subject=' + subject + '&docLoc=' + docloc;

xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xml.setRequestHeader("Content-length", params.length);
xml.setRequestHeader("Connection", "close");

xml.onreadystatechange = function() {//Call a function when the state changes.
if(xml.readyState == 4 && xml.status == 200) {
var responseMessage = "<h3>Email Sent</h3><br><p>Thank you for your interest.</p><p>An email has been sent to the following " + arrRecipientsLen + " recipient(s) with a link to this page:<br>"; 

for ( var i=0, len=arrRecipientsLen; i<len; ++i ){
responseMessage += arrRecipients[i] + "<br>";
}

responseMessage += "<\/p><div class=\"buttonsResponse\" ><a href=\"javascript:void(0);\" onclick=\"javascript: hideSplash('EmailThisPage'); \">Close</a><\/div>";
} else if(xml.readyState == 3) {
var responseMessage = "<h3>Status:</h3><br><p>Recieving data...</p>";
} else if(xml.readyState == 2) {
var responseMessage = "<h3>Status:</h3><br><p>Data sent...</p>";
} else if(xml.readyState == 1) {
var responseMessage = "<h3>Status:</h3><br><p>Connection successfully opened...</p>";
} else {
var responseMessage = "<h3>Error Occured</h3><br><p>There was a problem in sending your email. Please try again or contact the system administrator.</p><div class=\"buttonsResponse\" ><a href=\"javascript:void(0);\" onclick=\"javascript: hideSplash('EmailThisPage'); \">Close</a><\/div>";
}
document.getElementById('FormEmailThisPage').style.height=0;
document.getElementById('FormEmailThisPage').style.display='none'; 
document.getElementById('FormEmailThisPage').style.visibility='hidden';
document.getElementById('ResponseEmailThisPage').style.height=null;
document.getElementById('ResponseEmailThisPage').style.display='block'; 
document.getElementById('ResponseEmailThisPage').style.visibility='visible';
document.getElementById('ResponseEmailThisPage').innerHTML = responseMessage;
}


xml.send(params);
//ANYTHING EXTRA IS ADDED HERE.
}

var alreadyContactedMyInova = 0;

function establishMyInovaSession() {
if (alreadyContactedMyInova != 1) {
document.getElementById('myInovaLoad').innerHTML = '<iframe src="https://my.inova.com/" style="visibility:hidden; height: 0; width: 0;"></iframe>';
alreadyContactedMyInova = 1;
}
}

function detectMacXFF2() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (/firefox[\/\s](\d+\.\d+)/.test(userAgent)) {
    var ffversion = new Number(RegExp.$1);
    if (ffversion < 3 && userAgent.indexOf('mac') != -1) {
      return true;
    }
  }
}

if (detectMacXFF2()) {
// attach the Firefox 2 Mac stylesheet

} else {
// attach the one for everyone else
var CSSFile = 'opacity.css';
}

var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = '/css/' + CSSFile;
document.getElementsByTagName("head")[0].appendChild(cssNode);

function doWorkPlaceLogin() {  
var uName = document.workplacelogin.un.value; 
var pWord = document.workplacelogin.pw.value; 
//window.location="http://www.advantageworklife.com/site/1074/FMPro?-db=sites_login.fp5&-lay=data&-format=../adv/logindirect.html&idclient=1074&clientCode=Inova&username="+uName+"&password="+pWord+"&-new"; 
window.location="http://www.powerflexweb.com/result.php?username="+uName+"&password="+pWord+"&id=1074&code=inova"; 
}

/* onPageLoad, do these */
window.onload = function(e) {
checkPrint();
rotateCallout();
setStyle();
// checkSurveyCount();
if (document.getElementById('emailFriend') != null) {
document.emailFriend.loc.value = window.location;
} 
}