﻿/****************************************************************/
/*                  Start Main Functions                        */
/****************************************************************/
//Defined on HTMLHead.ascx:
//    var cometBaseUrl
//    var browserName
//    var browserVersion
//    var pngBlankGif
//    var pngIEFixFile

/*Correctly handle PNG transparency in Win IE 5.5 & 6.*/
if(browserName == 'IE' && browserVersion < 7){
    document.styleSheets[0].addRule('img', 'behavior: url('+pngIEFixFile+')');
    document.styleSheets[0].addRule('div', 'behavior: url('+pngIEFixFile+')');
}

// for simpler debugging
var log;
if (window.console && window.console.log)
    log = window.console.log;
else
    log = function() {};
    

/****** Used for OpenPDF ******/
var openPDFCustAdminId = '';
var openPDFCustUserId = '';
var openPDFSourceId = '';
var openPDFDocumentId = 0;
var openPDFLibraryId = 0;
var openPDFPageName = "";
var firstTimeHere = 1;
/******************************/

function openDemoPage(demoType)
{
    var pageName = window.location.toString() 
    if (pageName.indexOf('?') != -1) {
        location.href= pageName+ '&Demo='+demoType;
    } else {
        location.href= pageName+ '?Demo='+demoType;
    }
}

function clearInput(itemId) {
    switch (document.getElementById(itemId).value) {
        case "Enter Description":
            document.getElementById(itemId).value = "";
            break;
        case "Enter Category Name":
            document.getElementById(itemId).value = "";
            break;
        case "Enter Health Hazard":
            document.getElementById(itemId).value = "";
            break;
        case "Enter Physical Hazard":
            document.getElementById(itemId).value = "";
            break;
        case "Enter Target Organ":
            document.getElementById(itemId).value = "";
            break;
        case "Enter PPE":
            document.getElementById(itemId).value = "";
            break;
        case "Enter DOT Hazard Class":
            document.getElementById(itemId).value = "";
            break;
        case "Enter Safety Phrase":
            document.getElementById(itemId).value = "";
            break;
        case "Enter Risk Phrase":
            document.getElementById(itemId).value = "";
            break;
        case "Enter Division Name":
            document.getElementById(itemId).value = "";
            break;
        case "Enter Facility Name":
            document.getElementById(itemId).value = "";
            break;
        case "Enter Location Name":
            document.getElementById(itemId).value = "";
            break;
        case "Enter Physical State":
            document.getElementById(itemId).value = "";
            break;
        case "Enter Synonym":
            document.getElementById(itemId).value = "";
            break;
        case "Enter Group Name":
            document.getElementById(itemId).value = "";
            break;
        case "Province if Outside U.S.":
            document.getElementById(itemId).value = "";
            break;
        case "Other if not listed":
            document.getElementById(itemId).value = "";
            break;
        default:
            break;
    }
}

function projectPath() {
    applocation = window.location;
    pathname = window.location.pathname;
    projectname = pathname.split("\/");
    
    e = (applocation.toString()).indexOf(pathname);
    
    // First urlpath to be used with Stevie and Diana, 
    // due to the use of the Boston directory on those servers.
    // Live server does not have a Boston directory and 
    // therefore does not need the projectname added to the end of the path.
    // Marketing site on all servers needs the projectname[1].
    if (projectname[1].toLowerCase() == 'marketing' || projectname[1].toLowerCase() == 'boston'){
        urlpath = (applocation.toString()).substring(0, e) + "\/" + projectname[1];
    } else {
        urlpath = (applocation.toString()).substring(0, e);
    }
    
    return urlpath;
}

function showHideArrow(arrow,div,color,updateCookie){
    pathname = window.location.pathname;
    splitPathname = pathname.split("\/");
    pathnameArrayLength = splitPathname.length;
    for(i=1; i < pathnameArrayLength; i++) {
        if (splitPathname[i].indexOf(".") != -1) {
            splitPathname[i] = splitPathname[i].toLowerCase();
            if (splitPathname[i] == "hazards.aspx" ||  splitPathname[i] == "physicalproperties.aspx") {
                if (openedDiv == 'true')
                    return;
            }
        }
    } 

    if (document.getElementById(arrow).name == 'up'){
		document.getElementById(arrow).src = projectPath() + '/Images/' + color + '_arrow_dn.gif';
		document.getElementById(arrow).name = 'down';
		document.getElementById(div).style.display = 'none';
	}else{
		document.getElementById(arrow).src = projectPath() + '/Images/' + color + '_arrow_up.gif';
		document.getElementById(arrow).name = 'up';
		document.getElementById(div).style.display = 'block';
	}
}

function readLeftNavigationCookie() {
    //need to make sure that this doesn't get called if they are looking at GM embedded in HQ
    if (hQCall != 'True') {
        var cookieInformation = document.cookie.toString();
        if (cookieInformation.indexOf('GMLeftNavigationInformation') != -1) {
            //to differentiate between the HQ cookie information and the GM cookie information, 
            //create a variable to start pulling the substrings only after the HQAdminNavigation flag
            var navigationalSection = cookieInformation.substring(cookieInformation.indexOf('GMLeftNavigationInformation=') + 28,cookieInformation.length)
            var accountAtAGlanceExpanded = navigationalSection.substring(navigationalSection.indexOf('AccountAtAGlanceExpanded=') + 25,navigationalSection.indexOf('&SearchAndAddMSDSsExpanded='));
            var searchAndAddMSDSsExpanded = navigationalSection.substring(navigationalSection.indexOf('SearchAndAddMSDSsExpanded=') + 26,navigationalSection.indexOf('&ManageYourMSDSsExpanded='));
            var manageYourMSDSsExpanded = navigationalSection.substring(navigationalSection.indexOf('ManageYourMSDSsExpanded=') + 24,navigationalSection.indexOf('&End='));

            if (accountAtAGlanceExpanded != 'true') {
                showHideArrow('AccountAtAGlanceArrowImage','AccountAtAGlance', 'blk');
            }
            if (searchAndAddMSDSsExpanded != 'true') {
                showHideArrow('SearchAndAddArrowImage','SearchAndAdd', 'wht');
            }
            if (manageYourMSDSsExpanded != 'true') {
                showHideArrow('ManageMSDSArrowImage','ManageMSDS', 'blk');
            }
        } else{
            resetCookie("GMLeftNavigationInformation=AccountAtAGlanceExpanded=&SearchAndAddMSDSsExpanded=&ManageYourMSDSsExpanded=&End=",-1);
            document.cookie = "GMLeftNavigationInformation=AccountAtAGlanceExpanded=true&SearchAndAddMSDSsExpanded=true&ManageYourMSDSsExpanded=true&End=true;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";
        }
    }
}

function readEbinderCookie() {
    var cookieInformation = document.cookie.toString();
    if (cookieInformation.indexOf('GMEbinderInformation') != -1) {
        var pageName = (window.location.toString()).toLowerCase();

        if (pageName.indexOf('ebinder/default.aspx') != -1) {
            //if ebinder search (adv search)
            var ebinderAdvSearchExpanded  = cookieInformation.substring(cookieInformation.indexOf('EbinderAdvSearchExpanded=') + 25,cookieInformation.indexOf('&SummaryInformationExpanded='));
            if (ebinderAdvSearchExpanded == 'true') { showHideArrow('AdvancedSearchArrowImage','AdvancedSearchDefaultClose', 'blk'); }
            
        } else if (pageName.indexOf('ebinder') != -1) {
            //Ebinder summary information
            var summaryInformationExpanded  = cookieInformation.substring(cookieInformation.indexOf('SummaryInformationExpanded=') + 27,cookieInformation.indexOf('&HealthHazardsExpanded='));
            if (summaryInformationExpanded == 'false') { showHideArrow('AdvancedSearchArrowImage','AdvancedSearch', 'blk'); }
            
        }else if (pageName.indexOf('search/default.aspx') != -1 || pageName.indexOf('search/nullresults.aspx') != -1) {
            //if ebinder search (adv search)
            var advSearchExpanded  = cookieInformation.substring(cookieInformation.indexOf('AdvSearchExpanded=') + 18,cookieInformation.indexOf('&EbinderAdvSearchExpanded='));
            if (advSearchExpanded == 'true') { showHideArrow('AdvancedSearchArrowImage','AdvancedSearchDefaultClose', 'blk'); }
            
        } else if (pageName.indexOf('ebinder/hazards.aspx') != -1) {
            //if hazards page
            var healthHazardsExpanded = cookieInformation.substring(cookieInformation.indexOf('HealthHazardsExpanded=') + 22,cookieInformation.indexOf('&PhysicalHarzardsExpanded='));
            var physicalHarzardsExpanded = cookieInformation.substring(cookieInformation.indexOf('PhysicalHarzardsExpanded=') + 25,cookieInformation.indexOf('&TargetOrganExpanded='));
            var targetOrganExpanded = cookieInformation.substring(cookieInformation.indexOf('TargetOrganExpanded=') + 20,cookieInformation.indexOf('&PPEExpanded='));
            var ppeExpanded = cookieInformation.substring(cookieInformation.indexOf('PPEExpanded=') + 12,cookieInformation.indexOf('&SafetyPhrasesExpanded='));
            var safetyPhrasesExpanded = cookieInformation.substring(cookieInformation.indexOf('SafetyPhrasesExpanded=') + 22,cookieInformation.indexOf('&DOTHazardClassExpanded='));
            var dotHazardClassExpanded = cookieInformation.substring(cookieInformation.indexOf('DOTHazardClassExpanded=') + 23,cookieInformation.indexOf('&RiskPhrasesExpanded='));
            var riskPhrasesExpanded = cookieInformation.substring(cookieInformation.indexOf('RiskPhrasesExpanded=') + 20,cookieInformation.indexOf('&PhysicalPropertiesExpanded='));
            
            if (healthHazardsExpanded == 'true') {
                showHideArrow('HealthHazardsArrowImage','HealthHazardsGrid','blk');
            }
            if (physicalHarzardsExpanded == 'true') {
                showHideArrow('PhysicalHazardsArrowImage','PhysicalHazardsGrid','blk');
            }
            if (targetOrganExpanded == 'true') {
                showHideArrow('TargetOrgansArrowImage','TargetOrgansGrid','blk');
            }
            if (ppeExpanded == 'true') {
                showHideArrow('PPEsArrowImage','PPEsGrid','blk');
            }
            if (safetyPhrasesExpanded == 'true') {
                showHideArrow('SafetyPhrasesArrowImage','SafetyPhrasesGrid','blk');
            }
            if (dotHazardClassExpanded == 'true') {
                showHideArrow('DOTHazardsArrowImage','DOTHazardsGrid','blk');
            }
            if (riskPhrasesExpanded == 'true') {
                showHideArrow('RiskPhrasesArrowImage','RiskPhrasesGrid','blk');
            }
        } else if (pageName.indexOf('ebinder/physicalproperties.aspx') != -1) {
           //if physical properties page
            var physicalPropertiesExpanded = cookieInformation.substring(cookieInformation.indexOf('PhysicalPropertiesExpanded') + 27,cookieInformation.indexOf('&GMEbinderInformationEnd='));
            if (physicalPropertiesExpanded != 'true') {
                showHideArrow('HealthHazardsArrowImage','HealthHazardsGrid','blk');
            }
        } 
    } else {
        resetCookie("GMEbinderInformation=AdvSearchExpanded=&EbinderAdvSearchExpanded=&SummaryInformationExpanded=&HealthHazardsExpanded=&PhysicalHarzardsExpanded=&TargetOrganExpanded=&PPEExpanded=&SafetyPhrasesExpanded=&DOTHazardClassExpanded=&RiskPhrasesExpanded=&PhysicalPropertiesExpanded=&GMEbinderInformationEnd=",-1);
        document.cookie = "GMEbinderInformation=AdvSearchExpanded=false&EbinderAdvSearchExpanded=false&SummaryInformationExpanded=true&HealthHazardsExpanded=false&PhysicalHarzardsExpanded=false&TargetOrganExpanded=false&PPEExpanded=false&SafetyPhrasesExpanded=false&DOTHazardClassExpanded=false&RiskPhrasesExpanded=false&PhysicalPropertiesExpanded=true&GMEbinderInformationEnd=true;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";
    }
}

function setExpandEbinderCookie(imageId) {
    var cookieInformation = document.cookie.toString();
    var pageName = (window.location.toString()).toLowerCase();
    
    var advSearchExpanded  = cookieInformation.substring(cookieInformation.indexOf('AdvSearchExpanded=') + 18,cookieInformation.indexOf('&EbinderAdvSearchExpanded='));
    var ebinderAdvSearchExpanded  = cookieInformation.substring(cookieInformation.indexOf('EbinderAdvSearchExpanded=') + 25,cookieInformation.indexOf('&SummaryInformationExpanded='));
    
    var summaryInformationExpanded  = cookieInformation.substring(cookieInformation.indexOf('SummaryInformationExpanded=') + 27,cookieInformation.indexOf('&HealthHazardsExpanded='));
    
    var healthHazardsExpanded = cookieInformation.substring(cookieInformation.indexOf('HealthHazardsExpanded=') + 22,cookieInformation.indexOf('&PhysicalHarzardsExpanded='));
    var physicalHarzardsExpanded = cookieInformation.substring(cookieInformation.indexOf('PhysicalHarzardsExpanded=') + 25,cookieInformation.indexOf('&TargetOrganExpanded='));
    var targetOrganExpanded = cookieInformation.substring(cookieInformation.indexOf('TargetOrganExpanded=') + 20,cookieInformation.indexOf('&PPEExpanded='));
    var ppeExpanded = cookieInformation.substring(cookieInformation.indexOf('PPEExpanded=') + 12,cookieInformation.indexOf('&SafetyPhrasesExpanded='));
    var safetyPhrasesExpanded = cookieInformation.substring(cookieInformation.indexOf('SafetyPhrasesExpanded=') + 22,cookieInformation.indexOf('&DOTHazardClassExpanded='));
    var dotHazardClassExpanded = cookieInformation.substring(cookieInformation.indexOf('DOTHazardClassExpanded=') + 23,cookieInformation.indexOf('&RiskPhrasesExpanded='));
    var riskPhrasesExpanded = cookieInformation.substring(cookieInformation.indexOf('RiskPhrasesExpanded=') + 20,cookieInformation.indexOf('&PhysicalPropertiesExpanded='));
    var physicalPropertiesExpanded = cookieInformation.substring(cookieInformation.indexOf('PhysicalPropertiesExpanded') + 27,cookieInformation.indexOf('&GMEbinderInformationEnd='));
    
    if (imageId == 'SummaryInformationArrow') {
        //summary infomartion user control up/down arrow
        summaryInformationExpanded = 'false';
        if (document.getElementById('AdvancedSearchArrowImage').name == 'up') {summaryInformationExpanded = 'true';}
    } else if (pageName.indexOf('ebinder/default.aspx') != -1) {
        //if ebinder search (adv search)
        var ebinderAdvSearchExpanded  = 'false';
        if (document.getElementById('AdvancedSearchArrowImage').name == 'up') {ebinderAdvSearchExpanded = 'true';}
    } else if (pageName.indexOf('search/default.aspx') != -1 || pageName.indexOf('search/nullresults.aspx') != -1) {
        //if msds search (adv search)
        var advSearchExpanded  = 'false';
        if (document.getElementById('AdvancedSearchArrowImage').name == 'up') {advSearchExpanded = 'true';}            
    } else if (pageName.indexOf('ebinder/hazards.aspx') != -1) {
        //if hazards page
        var healthHazardsExpanded = 'false';
        var physicalHarzardsExpanded = 'false';
        var targetOrganExpanded = 'false';
        var ppeExpanded = 'false';
        var safetyPhrasesExpanded = 'false';
        var dotHazardClassExpanded = 'false';
        var riskPhrasesExpanded = 'false';
        
        if (document.getElementById('HealthHazardsArrowImage').name == 'up')  {healthHazardsExpanded = 'true';}
        else if (document.getElementById('PhysicalHazardsArrowImage').name == 'up'){physicalHarzardsExpanded = 'true';}
        else if (document.getElementById('TargetOrgansArrowImage').name == 'up')   {targetOrganExpanded = 'true';}
        else if (document.getElementById('PPEsArrowImage').name == 'up')           {ppeExpanded = 'true';}
        else if (document.getElementById('SafetyPhrasesArrowImage').name == 'up')  {safetyPhrasesExpanded = 'true';}
        else if (document.getElementById('DOTHazardsArrowImage').name == 'up')     {dotHazardClassExpanded = 'true';}
        else if (document.getElementById('RiskPhrasesArrowImage').name == 'up')    {riskPhrasesExpanded = 'true';}
        
    } else if (pageName.indexOf('ebinder/physicalproperties.aspx') != -1) {
       //if physical properties page
        var physicalPropertiesExpanded = 'false';
        if (document.getElementById('HealthHazardsArrowImage').name == 'up') {physicalPropertiesExpanded = 'true';}
    }
    
    resetCookie("GMEbinderInformation=AdvSearchExpanded=&EbinderAdvSearchExpanded=&SummaryInformationExpanded=&HealthHazardsExpanded=&PhysicalHarzardsExpanded=&TargetOrganExpanded=&PPEExpanded=&SafetyPhrasesExpanded=&DOTHazardClassExpanded=&RiskPhrasesExpanded=&PhysicalPropertiesExpanded=&GMEbinderInformationEnd=",-1);
    document.cookie = "GMEbinderInformation=AdvSearchExpanded=" + advSearchExpanded + "&EbinderAdvSearchExpanded=" + ebinderAdvSearchExpanded + "&SummaryInformationExpanded=" + summaryInformationExpanded + "&HealthHazardsExpanded=" + healthHazardsExpanded + "&PhysicalHarzardsExpanded=" + physicalHarzardsExpanded + "&TargetOrganExpanded=" + targetOrganExpanded + "&PPEExpanded=" + ppeExpanded + "&SafetyPhrasesExpanded=" + safetyPhrasesExpanded + "&DOTHazardClassExpanded=" + dotHazardClassExpanded + "&RiskPhrasesExpanded=" + riskPhrasesExpanded + "&PhysicalPropertiesExpanded=" + physicalPropertiesExpanded + "&GMEbinderInformationEnd=true;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";
}

function readTierIICookie() {
    var cookieInformation = document.cookie.toString();
    if (cookieInformation.indexOf('GMTierIIInformation') != -1) {
        var pageName = (window.location.toString()).toLowerCase();
        
        var physicalStateTierIIExpanded = cookieInformation.substring(cookieInformation.indexOf('PhysicalStateTierIIExpanded=') + 28,cookieInformation.indexOf('&RegulatoryTierIIExpanded='));
        var regulatoryTierIIExpanded = cookieInformation.substring(cookieInformation.indexOf('RegulatoryTierIIExpanded=') + 25,cookieInformation.indexOf('&PhysicalHazardsTierIIExpanded='));
        var physicalHazardsTierIIExpanded = cookieInformation.substring(cookieInformation.indexOf('PhysicalHazardsTierIIExpanded=') + 30,cookieInformation.indexOf('&HealthHazardsTierIIExpanded='));
        var healthHazardsTierIIExpanded = cookieInformation.substring(cookieInformation.indexOf('HealthHazardsTierIIExpanded=') + 28,cookieInformation.indexOf('&IngredientsTierIIExpanded='));
        var ingredientsTierIIExpanded = cookieInformation.substring(cookieInformation.indexOf('IngredientsTierIIExpanded=') + 26,cookieInformation.indexOf('&GMTierIIInformationEnd='));

        if (physicalStateTierIIExpanded != 'true') {
            showHideArrow('PhysicalStateArrowImage','InvPhysicalStateGridRows','blk');
        }
        if (regulatoryTierIIExpanded != 'true') {
            showHideArrow('RegulatoryCategoriesArrowImage','InvRegulatoryCategoriesGridRows','blk');
        }
        if (physicalHazardsTierIIExpanded != 'true') {
            showHideArrow('PhysicalHazardsArrowImage','InvPhysicalHazardsGridRows','blk');
        }
        if (healthHazardsTierIIExpanded != 'true') {
            showHideArrow('HealthHazardsArrowImage','InvHealthHazardsGridRows','blk');
        }
        if (ingredientsTierIIExpanded != 'true') {
            showHideArrow('IngredientArrowImage','InvIngredientsGridRows','blk');
        }
    } else {
        resetCookie("GMTierIIInformation=PhysicalStateTierIIExpanded=&RegulatoryTierIIExpanded=&PhysicalHazardsTierIIExpanded=&HealthHazardsTierIIExpanded=&IngredientsTierIIExpanded=&GMTierIIInformationEnd=",-1);
        document.cookie = "GMTierIIInformation=PhysicalStateTierIIExpanded=true&RegulatoryTierIIExpanded=true&PhysicalHazardsTierIIExpanded=true&HealthHazardsTierIIExpanded=true&IngredientsTierIIExpanded=true&GMTierIIInformationEnd=true;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";
    }
}

function setExpandTierIICookie(imageId) {
    //if inventory tier ii page
    var physicalStateTierIIExpanded = 'false';
    var regulatoryTierIIExpanded = 'false';
    var physicalHazardsTierIIExpanded = 'false';
    var healthHazardsTierIIExpanded = 'false';
    var ingredientsTierIIExpanded = 'false';

    if (document.getElementById('PhysicalStateArrowImage').name == 'up')  {physicalStateTierIIExpanded = 'true';}
    if (document.getElementById('RegulatoryCategoriesArrowImage').name == 'up')  {regulatoryTierIIExpanded = 'true';}
    if (document.getElementById('PhysicalHazardsArrowImage').name == 'up')  {physicalHazardsTierIIExpanded = 'true';}
    if (document.getElementById('HealthHazardsArrowImage').name == 'up')  {healthHazardsTierIIExpanded = 'true';}
    if (document.getElementById('IngredientArrowImage').name == 'up')  {ingredientsTierIIExpanded = 'true';}
   
    resetCookie("GMTierIIInformation=PhysicalStateTierIIExpanded=&RegulatoryTierIIExpanded=&PhysicalHazardsTierIIExpanded=&HealthHazardsTierIIExpanded=&IngredientsTierIIExpanded=&GMTierIIInformationEnd=",-1);
    document.cookie = "GMTierIIInformation=PhysicalStateTierIIExpanded=" + physicalStateTierIIExpanded + "&RegulatoryTierIIExpanded=" + regulatoryTierIIExpanded + "&PhysicalHazardsTierIIExpanded=" + physicalHazardsTierIIExpanded + "&HealthHazardsTierIIExpanded=" + healthHazardsTierIIExpanded + "&IngredientsTierIIExpanded=" + ingredientsTierIIExpanded + "&GMTierIIInformationEnd=true;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";
}

function showHide(activeVariableName,inactiveVariableName,searchSuggestEnabled){
    if (searchSuggestEnabled != 'False' || searchSuggestEnabled == null) {
        if (activeVariableName != ""){
            document.getElementById(activeVariableName).style.display = 'block';
        }
        if (inactiveVariableName != ""){
            document.getElementById(inactiveVariableName).style.display = 'none';
        }
    }
}

function showHidePdf(arrow,div,color,divArrowDownHeight,divArrowUpHeight,pdfUrl,pdfWidth,pdfHeight){
    if (document.getElementById(arrow).name == 'up'){
        document.getElementById(arrow).src = projectPath() + '/Images/' + color + '_arrow_dn.gif';
        document.getElementById(arrow).name = 'down';
        document.getElementById(div).style.display = 'none';		            
        titlebar_h = divArrowDownHeight;
        loadwindow(pdfUrl,pdfWidth,pdfHeight)
    }else{
        document.getElementById(arrow).src = projectPath() + '/Images/' + color + '_arrow_up.gif';
        document.getElementById(arrow).name = 'up';
        document.getElementById(div).style.display = 'block';
        titlebar_h = divArrowUpHeight;
        loadwindow(pdfUrl,pdfWidth,pdfHeight)
    }
}

var oldContentHeight = "";
var oldOverFlowHeight = "";
var heightDifference = "";
function showHidePdfSummary(arrow,color){
    if (document.getElementById(arrow).name == 'up'){
        document.getElementById(arrow).src = projectPath() + '/Images/' + color + '_arrow_dn.gif';
        document.getElementById(arrow).name = 'down';
        SummaryDivId.style.display = 'none';		            
        
        oldContentHeight = ContentHeight;
        ContentHeight = 40;
        ContentDivId.style.height = ContentHeight + "px";
        
        heightDifference = oldContentHeight - ContentHeight;
        
        oldOverFlowHeight = parseInt(OverflowDivId.style.height);
        OverflowDivId.style.height = ContentHeight + "px";
       
        oldMainDivHeight = parseInt(MainDivId.style.height);
        MainDivId.style.height = (parseInt(MainDivId.style.height) - heightDifference) + "px";
    }else{
        document.getElementById(arrow).src = projectPath() + '/Images/' + color + '_arrow_up.gif';
        document.getElementById(arrow).name = 'up';
        SummaryDivId.style.display = 'block';
        
        oldContentHeight = "140";
        oldOverFlowHeight = "140";
        var pageName = (window.location.toString()).toLowerCase();
        if (pageName.indexOf('search') != -1 || pageName.indexOf('findmsds') != -1) {
                oldContentHeight = "110";
                oldOverFlowHeight = "110";
        }else if (pageName.indexOf('ebinder') != -1) {
            if (pageName.indexOf('default') == -1) {
                //GM eBinder PDF small
                oldContentHeight = "156";
                oldOverFlowHeight = "156";
            }
        }
        
        ContentHeight = oldContentHeight;
        ContentDivId.style.height = ContentHeight + "px";

        OverflowDivId.style.height = oldOverFlowHeight + "px";

        MainDivId.style.height = (parseInt(MainDivId.style.height) + heightDifference) + "px";
    }
}

function trimString (stringValue) {
  stringValue = this != window? this : stringValue;
  return stringValue.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function forceAlphaNumeric(stringValue){
    return stringValue.replace(/[^a-zA-Z0-9]+/g,'');
}

//pass in an array of HTML element Id's and this function will remove the inner html. 
function clearHTMLElements(htmlElements){
    for (i in htmlElements){
        currentHTML = document.getElementById(htmlElements[i]);    
        currentHTML.innerHTML = '';
    }
}

function selectAllResultRows(id,checkboxName){
    var checkBox = document.getElementById(id);
    var allElements = document.getElementsByTagName("input");
    var i = 0;
    for(i = 0; i<allElements.length; i++) {
    //'searchResultsCheckbox'
        if (allElements[i].id.indexOf(checkboxName) == 0 ){
            if (checkBox.checked == true){
                allElements[i].checked = true;
            }else{
                allElements[i].checked = false;
            }
        }
    }
}

function resetFormFields(inputFields,selectFields,checkBoxFields,inputValues,selectValues,checkBoxValues) {
    var allInputElements = document.getElementsByTagName("input");
    var allSelectElements = document.getElementsByTagName("select");
    var i = 0;
    for(i = 0; i < allInputElements.length; i++) {
        //Set all input fields to default values
        for (r = 0; r < inputFields.length; r++){
            if (allInputElements[i].id.indexOf(inputFields[r]) >= 0){
                allInputElements[i].value = inputValues[r];
                break;
            }
        }
        //Set all checkboxes to default values
        for (n = 0; n < checkBoxFields.length; n++){
            if (allInputElements[i].id.indexOf(checkBoxFields[n]) >= 0){
                allInputElements[i].checked = checkBoxValues[n];
                break;
            }
        }
    }
    //Set all dropdowns to default values
    for(s = 0; s < allSelectElements.length; s++) {
        for (j = 0; j < selectFields.length; j++){
            if (allSelectElements[s].name.indexOf(selectFields[j]) >= 0){
                allSelectElements[s].selectedIndex = selectValues[s];
                break;
            }
        }
    }
}

function addBookmark(title, url) {
    if (window.sidebar) { // firefox
          window.sidebar.addPanel(title, url,"");
    } else if( document.all ) { //MSIE
            window.external.AddFavorite( url, title);
    } else {
           alert("Your browser does not current support this functionality. Browsers that support this functionality include: Internet Explorer and Firefox.");
    }
}

function submitForm(theForm,pageName,urlParameters){
    theForm.action = pageName + '?' + urlParameters;
    theForm.submit();
}

function switchLoginInput(htmlControlId, passwordControl) {
    if (htmlControlId.indexOf("LoginName") != -1) {
        if (!visitedName) {
            visitedName = true;
            document.getElementById(htmlControlId).value = "";
            document.getElementById(htmlControlId).style.color = '#000000';
        }
    } else {
        if (!visitedPassword) {
            visitedPassword = true;
            document.getElementById(htmlControlId).style.display = 'none';
            document.getElementById(passwordControl).style.display = 'inline';
            document.getElementById('LoginPassword').focus();
        }
    }
}


/**********************************************************************/
/*                   Roll Down/Up Functions                           */
/**********************************************************************/
function getContentHeight(tempDivValue) {
    //document.getElementById('EbinderTabContentSection').style.height = '151px';
    var tempDivTop = elementGetTop(document.getElementById(tempDivValue));
    document.getElementById('EbinderTabContentSection').style.height = (tempDivTop - elementGetTop(document.getElementById('EbinderTabContentSection')) + 50) + 'px';
    document.getElementById('FooterUserControl').style.top = document.getElementById('EbinderTabContentSection').style.height;
}

/*********************************************************************************/
/*                              START SLIDE UP/DOWN                              */
/*********************************************************************************/


var openedDiv = "false";
var callingRowId = "";
var movingRowId = "";
var revealingRowId = "";
var growingElementId = "";
var tempDivId = "";
var clickElementId = "";
var totalGrowHeight = "";
var topBorders = "false";
var bottomBorders = "false";
var leftStyle = "";
var textData = "";
var textInputId = "";
var oldLinkValue = "";
var doneYet = "false";
var existingOffSet = 'false';
var siblingArray = [];
var isHazardsPage = false;
var isEditRegulatoryPage = false;
var isEditLocationsPage = false;
var isEditMasterIngredientsPage = false;
var isIngredientsPage = false;


var initialLink = "";
function showHideSlideDown(divName,linkName, cancelButton){
    if (document.getElementById(divName).style.display == 'none' || document.getElementById(divName).style.display == ''){
        document.getElementById(divName).style.display = 'block';
        
        if (openedDiv == 'true') {
            document.getElementById(movingRowId).style.display = 'none';
        }
        
        openedDiv = 'true';
        initialLink = linkName;
        movingRowId = divName;
    }else{
        if(linkName == initialLink || cancelButton == 'true' || cancelButton == true)
        {
            document.getElementById(divName).style.display = 'none';
            openedDiv = 'false';
            movingRowId = '';
            initialLink = '';
        } else {
            initialLink = linkName;
        }
    }
}




//--------------------------------------------------------//        
// This function initializes variables and positions      //
// for the moveUp function, which rolls the element/div up//
// the screen. All of the variables necessary are Global  //
// variables initialized in the initializeMoveDown.       //
//--------------------------------------------------------//  


//--------------------------------------------//        
// This function gets the very Top coordinate //
// for the element passed to it. Used on the  //
// standard, new queue and eBinder searchs.   //
//--------------------------------------------//        
//function elementGetTop(imgElem) {
//    yPos = 0;
//    yPos = imgElem.offsetTop;
//    tempEl = imgElem.offsetParent;
//    while (tempEl != null && existingOffSet == 'false') {
//        yPos += tempEl.offsetTop;
//	    tempEl = tempEl.offsetParent;
//    }
//    return yPos;
//}
	    
//--------------------------------------------//        
// This function gets the far Left coordinate //
// for the element passed to it. Used on the  //
// standard, new queue and eBinder searchs.   //
//--------------------------------------------//        
//function elementGetLeft(imgElem)
//{
//    xPos = imgElem.offsetLeft;
//    tempEl = imgElem.offsetParent;
//    while (tempEl != null && existingOffSet == 'false') {
//        xPos += tempEl.offsetLeft;
//	    tempEl = tempEl.offsetParent;
//    }
//    return xPos;
//}
/**********************************************************************/
/*                   End Roll Down/Up Functions                       */
/**********************************************************************/

/**********************************************************************/
/*                        Pop Up Functions                            */
/**********************************************************************/

//--------------------------------------//
// This function changes the border for //
// mouse overs and mouse outs.  It also //
// changes the background color for the //
// eBinder pages when the are clicked.  //
//--------------------------------------//

function rollOver(divId,borderColor, bgColor, handPointer) {
    borderInformation = '1px solid ' + borderColor;
    document.getElementById(divId).style.borderTop = borderInformation;
    document.getElementById(divId).style.borderBottom = borderInformation;
    if(bgColor != "") {
        document.getElementById(divId).style.background = bgColor;
    }
    if (handPointer = 'yes') {
        document.getElementById(divId).style.cursor = 'pointer';
    } else {
        document.getElementById(divId).style.cursor = 'default';
    }
}

//--------------------------------------//
// Global variables used for the Pop Up //
// information divs on the standard,    //
// new queue and eBinder searchs.       //
//--------------------------------------//

var isIE = document.all?true:false;
var xMousePosition;
var yMousePosition;

//-----------------------------------------//
// This functions displays the information //
// pop up that is used on the standard,    //
// new queue and eBinder searchs. It also  //
// has a timeout function for when the     //
// mouse is no longer over the image that  //
// initiated the pop up or the pop up div  //
// itself. For the closing procedure, see  //
// closeDiv().                             //
//-----------------------------------------//  
      
var imageTop;
var popDivName;
var popImageName;
    
var quickHintDiv = "";
function populateQuickHint(divName, quickHintsId)
{
    quickHintDiv = document.getElementById(divName);
    var projectPathVariable = projectPath()
    var shortProjectPath = projectPathVariable.split("/")
    var fullProjectPath = cometBaseUrl + '/QuickHints';

    sendCometRequest('processQuickHintInformation',shortProjectPath[2],fullProjectPath,'QuickHintId,' + quickHintsId);
}
function processQuickHintInformation()
{
    if (comet.readyState == 4) {
        if (comet.status == 200) {
            var urlPath = (window.location.toString()).toLowerCase();
            quickHintDiv.innerHTML = getRootElementInformation(comet).replace('Flash/Interactive.aspx',marketingUrlPath + 'Flash/Interactive.aspx');
        }
    }
}

var popUpTypeName = '';
function getShowProductMouseOver(divName,imageName,popUpType){
    //document.getElementById(divName).style.zIndex = 100;
    //document.getElementById(divName).style.display = "block";
    
    var imageLeft
    popUpTypeName = popUpType
    popDivName = divName;
    popImageName = imageName;
    
	if (popUpType == 'Availability') {
		imageLeft = elementGetLeft(document.getElementById(imageName)) - 360;
	    imageTop = elementGetTop(document.getElementById(imageName)) + 10;
	} else if (popUpType == 'QuickHints') {
	    var pageName = (window.location.pathname).toLowerCase();
	    document.getElementById("HideDropDown").style.height = IframeHeight;
	    document.getElementById("HideDropDown").style.top = IframeTop;
	    document.getElementById("HideDropDown").style.left = IframeLeft;
	    document.getElementById("HideDropDown").style.display = "block";
	    if (hQCall){
	        if (pageName.indexOf('findmsds/ebinder.aspx') != -1 || pageName.indexOf('findmsds/default.aspx') != -1 ) {
	            
		        document.getElementById(divName).style.left = "318px";
	            document.getElementById(divName).style.top = "152px";
	            document.getElementById(divName).style.display = "block";
            } else {
		        document.getElementById(divName).style.left = "340px";
	            document.getElementById(divName).style.top = "13px";
	            document.getElementById(divName).style.display = "block";
            }
        }else{
            if (pageName.indexOf('findmsds/ebinder.aspx') != -1 || pageName.indexOf('findmsds/default.aspx') != -1 ) {
		        document.getElementById(divName).style.left = "318px";
	            document.getElementById(divName).style.top = "152px";
	            document.getElementById(divName).style.display = "block";
            } else {
		        document.getElementById(divName).style.left = "529px";
	            document.getElementById(divName).style.top = "102px";
	            document.getElementById(divName).style.display = "block";
            }
        }
	} else if (popUpType == 'RegulatoryDescription') {
        imageLeft = elementGetLeft(document.getElementById(imageName)) + 27;
        imageTop = elementGetTop(document.getElementById(imageName)) + 3;
	} else {
        imageLeft = elementGetLeft(document.getElementById(imageName)) + 19;
        imageTop = elementGetTop(document.getElementById(imageName));
    }
	
//	var pageName = (window.location.pathname).toLowerCase();
//	if (pageName.indexOf('inventorymanager/managebyfacility') != -1 && popUpType !='QuickHints') {
//	    document.getElementById("TestIFrame").style.display = "block";
//	    document.getElementById("TestIFrame").style.left = imageLeft + "px";
//	}
	
	if (popUpType != 'QuickHints') {
        document.getElementById(divName).style.left= imageLeft + "px";
        //Start the mouse watching
        var IE = document.all ? true : false;
        if (!IE) {
            window.captureEvents(Event.MOUSEMOVE);
            window.onclick = getMouseLocationStart;
        } else {
            document.onclick = getMouseLocationStart;
        }
    }
}
function getMouseLocationStart(e) 
{
   var posX = 0;
   var posY = 0;
   var e = (!e) ? window.event : e;
   if (e.pageX || e.pageY) {
      posX = e.pageX;
      posY = e.pageY;
   }
   else if (e.clientX || e.clientY) {
      if (document.body.scrollLeft || document.body.scrollTop) {
         posX = e.clientX + document.body.scrollLeft;
         posY = e.clientY + document.body.scrollTop;
      }
      else {
         posX = e.clientX + document.documentElement.scrollLeft;
         posY = e.clientY + document.documentElement.scrollTop;
      }
   }
   
   //End the mouse watching and set div top
   window.onclick = null;
   document.onclick = null;
   
   document.getElementById(popDivName).style.top = posY + "px";
   
    var pageName = (window.location.pathname).toLowerCase();
    if (pageName.indexOf('inventorymanager/managebyfacility') != -1) {
        document.getElementById("TestIFrame").style.top = posY + "px";
    }
    
    //zooming function for information divs
    if (popUpTypeName != 'RegulatoryDescription' && popUpTypeName != 'Availability') {
        var divTopPosition = (document.getElementById(popDivName).style.top).replace('px','');
        var divLeftPosition = (document.getElementById(popDivName).style.left).replace('px','');
        if (fullPopUpHeight != 0 || fullPopUpWidth != 0) {
            zoomInformationDiv(fullPopUpHeight, fullPopUpWidth, divLeftPosition, divTopPosition, true); //Default ebinder page
        } else {
            zoomInformationDiv(150, 400, divLeftPosition, divTopPosition, true); //Default ebinder page
        }
    } else {
        document.getElementById(popDivName).style.display = 'inline';
        document.getElementById(popDivName).style.zIndex = '500';
    }
}

/************************************************************/
/*               Information Div Zoom In/Out                */
/************************************************************/

var currentLoopNumber = 0;
var startHeight = 0;
var startWidth = 0;
var negativeFactor = 1;

function zoomInformationDiv(fullHeight,fullWidth,endingLeftPosition,endingTopPosition,restartZoom,closeingDiv) {
    if (restartZoom) {
        if (closeingDiv) {
            startHeight = fullHeight;
            startWidth = fullWidth;
            negativeFactor = -1;
            //remove the inner conent while it's zooming out
            document.getElementById(popDivName).style.display = 'none';
        } else {
            startHeight = 0;
            startWidth = 0;
            negativeFactor = 1;
            
            document.getElementById('TempInformationDiv').style.top = elementGetTop(document.getElementById(popImageName)) + 'px';
            document.getElementById('TempInformationDiv').style.left = elementGetLeft(document.getElementById(popImageName)) + 'px';
        }
        currentLoopNumber = 0;
    }
    
    //display the information pop and remove the inner conent while it's zooming out
    document.getElementById('TempInformationDiv').style.display = 'inline';
    
    //Calculate the amount to increment height and width
    var numberOfLoops = 15;
    var heightIncrement = fullHeight / numberOfLoops;
    var widthIncrement = fullWidth / numberOfLoops;
    startHeight = startHeight + (heightIncrement * negativeFactor);
    startWidth = startWidth + (widthIncrement * negativeFactor);

    //Calculate increments for the top and left movements
    var leftIncrement = ((endingLeftPosition - elementGetLeft(document.getElementById(popImageName))) / numberOfLoops) / 2;
    var topIncrement = ((endingTopPosition - elementGetTop(document.getElementById(popImageName))) / numberOfLoops) / 2;

    //round up to 1 for zooming out
    if (leftIncrement < 1 && leftIncrement > 0) { leftIncrement = 1; }
    if (topIncrement < 1 && topIncrement > 0) { topIncrement = 1; }
    //round down to -1 from zooming in
    if (leftIncrement > -1 && leftIncrement < 0) { leftIncrement = -1; }
    if (topIncrement > -1 && topIncrement < 0) { topIncrement = -1; }
    
    if (startWidth >= 0 && startHeight >= 0) {
        document.getElementById('ShadowImage').style.width = startWidth + 'px';
        document.getElementById('ShadowImage').style.height = startHeight + 'px';
    }
    
    //Move the entire section over so that it's more 3D
    //only increment left and top every other loop since it only has a small distance to travel
    if (currentLoopNumber % 2) {
        document.getElementById('TempInformationDiv').style.left = elementGetLeft(document.getElementById('TempInformationDiv')) + leftIncrement + 'px';
        document.getElementById('TempInformationDiv').style.top = elementGetTop(document.getElementById('TempInformationDiv')) + topIncrement + 'px';
    }
    
    //set the timer to continually increment the height and widht until it hits it's full dimensions
    if (currentLoopNumber >= numberOfLoops) {
        if (negativeFactor > 0) {
            document.getElementById(popDivName).style.display = 'inline';
            document.getElementById('TempInformationDiv').style.left = elementGetLeft(document.getElementById(popDivName)) - 5 + 'px';
            document.getElementById('TempInformationDiv').style.top = elementGetTop(document.getElementById(popDivName)) - 5 + 'px';
            document.getElementById('TempInformationDiv').style.display = 'none';
            
	        if ((window.location.pathname).toLowerCase().indexOf('inventorymanager/managebyfacility') != -1) {
	            //Calculate the info div height
	            var divTop = elementGetTop(document.getElementById("InformationDivTopImage"));
	            var divBottom = elementGetTop(document.getElementById("InformationDivBottomImage"));
	            var inforDivHeight = (divBottom - divTop + 13) + 'px';
	            document.getElementById("TestIFrame").style.display = "block";
	            document.getElementById("TestIFrame").style.left = elementGetLeft(document.getElementById("InformationDivTopImage")) + "px";
	            document.getElementById("TestIFrame").style.height = inforDivHeight;
	        }
        } else {
            closeDivNow(popDivName);
            closeDivNow('TempInformationDiv');
        }
    } else {
        currentLoopNumber = currentLoopNumber + 1;
        setTimeout("zoomInformationDiv("+fullHeight+","+fullWidth+","+endingLeftPosition+","+endingTopPosition+",false)",7); //5 seconds = 5000
    }
}

function closeDivNowZoom() {
    if (fullPopUpHeight != 0 || fullPopUpWidth != 0) {
        zoomInformationDiv(fullPopUpHeight, fullPopUpWidth, elementGetLeft(document.getElementById(popImageName)) - 15,elementGetTop(document.getElementById(popImageName)),true,true); //Default ebinder page
    } else {
        zoomInformationDiv(198, 646, elementGetLeft(document.getElementById(popImageName)) - 15,elementGetTop(document.getElementById(popImageName)),true,true); //Default ebinder page
    }
    //zoomInformationDiv(198,646,elementGetLeft(document.getElementById(popImageName)) - 15,elementGetTop(document.getElementById(popImageName)),true,true);
}

//------------------------------------------//        
// This function immediately closes the pop //
// up with no delay. Used on the standard,  //
// new queue and eBinder searchs.           //
//------------------------------------------//        
function closeDivNow(divId) {
    document.getElementById(divId).style.display = "none";
    document.getElementById(divId).style.zIndex = '';
}

//--------------------------------------------//        
// This function gets the left coordinate of  //
// the mouse. Used on the standard, new queue //
// and eBinder searchs.                       //
//--------------------------------------------//        
function getMouseXPosition(e) 
{
  var _x;
  if (!isIE) {
    _x = e.pageX;
  }
  if (isIE) {
    _x = event.clientX + document.body.scrollLeft;
  }
  xMousePosition = _x
  return true;
}

//--------------------------------------------//        
// This function gets the top coordinate of   //
// the mouse. Used on the standard, new queue //
// and eBinder searchs.                       //
//--------------------------------------------//        
function getMouseYPosition(e) 
{
  var _y;
  if (!isIE) 
  {
    _y = e.pageY;
  }
  if (isIE) 
  {
    _y = event.clientY + document.body.scrollTop;
  }
  yMousePosition = _y
  return true;
}
/**********************************************************************/
/*                      End Pop Up Functions                          */
/**********************************************************************/


/**********************************************************************/
/*                      Top and Left Functions                        */
/**********************************************************************/
//--------------------------------------------//        
// This function gets the far left coordinate //
// for the element passed to it. Used on the  //
// standard, new queue and eBinder searchs.   //
//--------------------------------------------//        
function elementGetLeft(imgElem) {
    xPos = imgElem.offsetLeft;
    tempEl = imgElem.offsetParent;
    var pageName = (window.location.toString()).toLowerCase();
    while (tempEl != null && existingOffSet == 'false') {
	    xPos += tempEl.offsetLeft;
	    tempEl = tempEl.offsetParent;
    }
    if(browserName != 'IE'){
        if(pageName.indexOf('ebinder/default.aspx') != -1){
            if(hQCall == 'True'){
                xPos = 77;
            }else{
                xPos = 266;
            }
        }
    }
    return xPos;
}

//--------------------------------------------//        
// This function gets the very Top coordinate //
// for the element passed to it. Used on the  //
// standard, new queue and eBinder searchs.   //
//--------------------------------------------//        
function elementGetTop(imgElem) {
    yPos = 0;
    yPos = imgElem.offsetTop;
    tempEl = imgElem.offsetParent;
    while (tempEl != null && existingOffSet == 'false') {
	    yPos += tempEl.offsetTop;
	    tempEl = tempEl.offsetParent;
    }
    return yPos;
}
/**********************************************************************/
/*                    End Top and Left Functions                      */
/**********************************************************************/


/****************************************************************/
/*                        DRAG/DROP ROWS                        */
/****************************************************************/
    
    var destinationGridID;
    
    var Drag = {
        obj : null,
        gridName : null,
        
        init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
        {
        
	        o.hmode	= bSwapHorzRef ? false : true ;
	        o.vmode	= bSwapVertRef ? false : true ;
            
	        o.root = oRoot && oRoot != null ? oRoot : o ;
            
	        if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
	        if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
	        if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
	        if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

	        o.minX	= typeof minX != 'undefined' ? minX : null;
	        o.minY	= typeof minY != 'undefined' ? minY : null;
	        o.maxX	= typeof maxX != 'undefined' ? maxX : null;
	        o.maxY	= typeof maxY != 'undefined' ? maxY : null;

	        o.xMapper = fXMapper ? fXMapper : null;
	        o.yMapper = fYMapper ? fYMapper : null;

	        o.root.onDragStart	= new Function();
	        o.root.onDragEnd	= new Function();
	        o.root.onDrag		= new Function();
        },

        start : function(e)
        {
            
            if(!e){var e = window.event};
            var targ = e.target?e.target:e.srcElement;
            
            //exit out if the label or white space in the row isn't selected
            //if((targ.className != 'draggable' && targ.parentNode.className != 'draggable') || targ.nodeName == 'IMG' || targ.nodeName == 'A' || openedDiv == 'true'){
            var firstCheck = false
            var secondCheck = false
            var thirdCheck = false
            
            if (targ == null) {
                return;
            }else if (targ.id == "") {
                return;
            }else if((targ.className != 'draggable' && targ.parentNode.className != 'draggable' && targ.parentNode.parentNode.className != 'draggable') || targ.nodeName == 'IMG' || targ.nodeName == 'A'){
                return;
            }
//            } else if(targ.className != 'draggable' || targ.nodeName == 'IMG' || targ.nodeName == 'A'){
//                firstCheck = true;
//            } else if (targ.parentNode.className != 'draggable') {
//                secondCheck = true;
//            } else if (targ.parentNode.parentNode.className != 'draggable') {
//                thirdCheck = true;
//            }
//            if (firstCheck || secondCheck || thirdCheck) then { return; }
            
            if (targ.parentNode.className == 'draggable') {
                targ = targ.parentNode;
            } else if (targ.parentNode.parentNode.className == 'draggable') {
                targ = targ.parentNode.parentNode;
            }
            
            //find if the page is Hazards.aspx
            pathname = window.location.pathname;
            splitPathname = pathname.split("\/");
            pathnameArrayLength = splitPathname.length;
            for(i=1; i < pathnameArrayLength; i++)
            {
                if (splitPathname[i].indexOf(".") != -1)
                {
                    if (splitPathname[i].toLowerCase() == "hazards.aspx")
                    {
                        isHazardsPage = true;
                    }
                }
            } 
            
            //get the destinationGrid and set the global variable to it
            if (isHazardsPage) {
                gridsCurrentArray = new Array('HealthHazardsGrid', 'PhysicalHazardsGrid', 'TargetOrgansGrid', 'PPEsGrid', 'SafetyPhrasesGrid', 'DOTHazardsGrid', 'RiskPhrasesGrid');
                gridsAvailableArray = new Array('HealthHazardsHidingDiv', 'PhysicalHazardsHidingDiv', 'TargetOrgansHidingDiv', 'PPEsHidingDiv', 'SafetyPhrasesHidingDiv', 'DOTHazardsHidingDiv', 'RiskPhrasesHidingDiv');
                var canDrag = false;
                
                for (var i = 0; i < gridsAvailableArray.length; i++) {
                    if (document.getElementById(gridsAvailableArray[i]).style.display == 'block') {
                        canDrag = true;
                    }
                }
            } else {
                if (document.getElementById('HealthHazardsHidingDiv').style.display == 'block') {
                    canDrag = true;
                }
            }
            
            if (canDrag) {
                var parentRow = document.getElementById(targ.id).parentNode;
                var o = document.getElementById(targ.id);
                o.style.backgroundColor = document.getElementById(parentRow.id).style.backgroundColor;
                parentRow.style.height = '23px';
		        
                Drag.init(targ);
                Drag.obj = o;
	            
	            o.style.position = 'relative';
	            o.style.zIndex = 550;
	            o.style.border = 'solid 1px #CCCC99';
	            o.style.height = '21px';
	            o.style.width = '335px';

	            e = Drag.fixE(e);
                var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
                var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
	            o.root.onDragStart(x, y);

	            o.lastMouseX	= e.clientX;
	            o.lastMouseY	= e.clientY;

	            if (o.hmode) {
		            if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
		            if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
	            } else {
		            if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
		            if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
	            }

	            if (o.vmode) {
		            if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
		            if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
	            } else {
		            if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
		            if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
	            }

                //get the destinationGrid and set the global variable to it
                var gridName = "";
                
                if (o.parentNode.parentNode.id != '') {
                    if (o.parentNode.parentNode.id.indexOf('Available') != -1) {
                        if (isHazardsPage) {
                            for (var i = 0; i < gridsCurrentArray.length; i++) {
                                if (document.getElementById(gridsCurrentArray[i]).style.display == 'block') {
                                    var e = gridsCurrentArray[i].indexOf('Grid');
                                    gridName = gridsCurrentArray[i].substring(0, e);
                                    destinationGridID = 'Encaps' + gridName + 'RowsCurrent';
                                }
                            }
                        } else {
                            gridName = 'HealthHazards';
                            destinationGridID = 'EncapsHealthHazardsRowsCurrent';
                        }
                    }else if(o.parentNode.parentNode.id.indexOf('Current') != -1){
                        if (isHazardsPage) {
                            for (var i = 0; i < gridsAvailableArray.length; i++) {
                                if (document.getElementById(gridsAvailableArray[i]).style.display == 'block') {
                                    var e = gridsAvailableArray[i].indexOf('HidingDiv');
                                    gridName = gridsCurrentArray[i].substring(0, e);
                                    destinationGridID = 'Encaps' + gridName + 'RowsAvailable';
                                }
                            }
                        } else {
                            if (document.getElementById('HealthHazardsHidingDiv').style.display == 'block') {
                                    gridName = 'HealthHazards';
                                    destinationGridID = 'EncapsHealthHazardsRowsAvailable';
                            }
                        }
                    } else {
                        destinationGridID = 'none';
                    }
                } else {
                    destinationGridID = 'none';
                }
                
                //In FF, the drag stays in the scrollable area so setting overflow to inherit fixes 
                //the dragging div, but then the availalbe grid expands cuz there's no scroll
                //if (isHazardsPage && destinationGridID.indexOf("Current") > 0) {
                //    document.getElementById('Encaps' + gridName + 'RowsAvailable').style.overflow = 'inherit';
                //}
                
                Drag.gridName = gridName;
                document.onmousemove	= Drag.drag;
                document.onmouseup		= Drag.end;
            }
            
	        return false;
        },

        drag : function(e)
        {
	        e = Drag.fixE(e);
	        var o = Drag.obj;

	        var ey	= e.clientY;
	        var ex	= e.clientX;
	        var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
	        var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
	        var nx, ny;

	        if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
	        if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
	        if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
	        if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

	        nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
	        ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

	        if (o.xMapper)		nx = o.xMapper(y)
	        else if (o.yMapper)	ny = o.yMapper(x)

	        Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
	        Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
	        Drag.obj.lastMouseX	= ex;
	        Drag.obj.lastMouseY	= ey;

	        Drag.obj.root.onDrag(nx, ny);
	        
	        return false;
        },

        end : function()
        {
            //document.getElementById("EncapsHealthHazardsRowsAvailable").style.overflow = 'scroll';
		    
            document.onmousemove = null;
	        document.onmouseup   = null;
	        
	        Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
								        parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
			
	        var targ = Drag.obj;
            var isInsideGrid = false;
            
            //the destination grid is known in a global variable that's set in the start drag function
            if (Drag.gridName != "") {
                isInsideGrid = getCoords(targ, Drag.gridName + 'TempDiv');
            }
            
            //Variables needed for the add/remove functions (UserRegDocId is determined in web method call)
            var urlPath = (window.location.toString()).toLowerCase();
            var dragItemId;
            var dragItemName;
            var dragRegulatoryDescription;
            var dragItemDocId;
            
            //Set variables for the Groups Page
            if (urlPath.indexOf('ebinder/groups.aspx') != -1) {
                var rowID = targ.parentNode.id;
                if (rowID.indexOf('Current') != -1) 
                    dragItemId = rowID.substring(0,rowID.indexOf('Current'));
                 else 
                    dragItemId = rowID.substring(0,rowID.indexOf('Available'));
                dragItemName = targ.lastChild.previousSibling.innerHTML;
                dragItemDocId = targ.lastChild.id;
            
            //Set variables for the Regulatory Categories Page    
            } else if (urlPath.indexOf('regulatory.aspx') != -1){
                var rowID = targ.parentNode.id;
                if (rowID.indexOf('Current') != -1) 
                    dragItemId = rowID.substring(0,rowID.indexOf('Current'));
                 else 
                    dragItemId = rowID.substring(0,rowID.indexOf('Available'));
                dragItemName = targ.firstChild.nextSibling.lastChild.innerHTML;
                dragRegulatoryDescription = targ.lastChild.previousSibling.value;
            
            //Set variables for the Hazards Page    
            } else if (urlPath.indexOf('hazards.aspx') != -1 || urlPath.indexOf('physicalproperties.aspx') != -1) {
                var rowID = targ.parentNode.id;
                if (destinationGridID.indexOf('Current') != -1) {
                    dragItemId = rowID.substring(Drag.gridName.length,rowID.indexOf('Plus'));
                    dragItemName = targ.parentNode.firstChild.firstChild.lastChild.lastChild.innerHTML; //this breaks because the add function sets the HTML up differently then the xsl
                } else {
                    dragItemId = rowID.substring(Drag.gridName.length,rowID.indexOf('Minus'));
                    dragItemName = targ.parentNode.lastChild.lastChild.innerHTML;
                }
            }
            
            //Add the row, Delete the row, or Cancel the drag accordingly
            if (isInsideGrid) {
            
                //Remove or add the row
                if (destinationGridID.indexOf('Current') != -1) {
                    if (urlPath.indexOf('ebinder/groups.aspx') != -1) {
                        addGroupsPickListItem(dragItemId,0,dragItemName,'Available');
                    
                    } else if (urlPath.indexOf('regulatory.aspx') != -1){
                        addRegulatoryPickListItem(dragItemId,dragItemName,dragRegulatoryDescription,'Available');
                    
                    } else if (urlPath.indexOf('hazards.aspx') != -1) {
                        if (Drag.gridName == 'HealthHazards')   {addUserDocumentHazard(dragItemId,'HealthHazards','EncapsHealthHazardsRows',dragItemName,'AddUserDocumentHealthHazard','UserHealthHazardsId','DeleteUserDocumentHealthHazard','UserDocumentHealthHazardsId');}
                        if (Drag.gridName == 'PhysicalHazards') {addUserDocumentHazard(dragItemId,'PhysicalHazards','EncapsPhysicalHazardsRows',dragItemName,'AddUserDocumentPhysicalHazard','UserPhysicalHazardsId','DeleteUserDocumentPhysicalHazard','UserDocumentPhysicalHazardsId');}
                        if (Drag.gridName == 'TargetOrgans')    {addUserDocumentHazard(dragItemId,'TargetOrgans','EncapsTargetOrgansRows',dragItemName,'AddUserDocumentTargetOrgan','UserTargetOrgansId','DeleteUserDocumentTargetOrgan','UserDocumentTargetOrgansId');}
                        if (Drag.gridName == 'PPEs')            {addUserDocumentHazard(dragItemId,'PPEs','EncapsPPEsRows',dragItemName,'AddUserDocumentPPE','UserPPEsId','DeleteUserDocumentPPE','UserDocumentPPEId');}
                        if (Drag.gridName == 'SafetyPhrases')   {addUserDocumentHazard(dragItemId,'SafetyPhrases','EncapsSafetyPhrasesRows',dragItemName,'AddUserDocumentSafetyPhrase','UserSafetyPhrasesId','DeleteUserDocumentSafetyPhrase','UserDocumentSafetyPhrasesId');}
                        if (Drag.gridName == 'DOTHazards')      {addUserDocumentHazard(dragItemId,'DOTHazards','EncapsDOTHazardsRows',dragItemName,'AddUserDocumentDOT','UserDOTHazardsId','DeleteUserDocumentDOT','UserDocumentDOTId');}
                        if (Drag.gridName == 'RiskPhrases')     {addUserDocumentHazard(dragItemId,'RiskPhrases','EncapsRiskPhrasesRows',dragItemName,'AddUserDocumentRiskPhrase','UserRiskPhrasesId','DeleteUserDocumentRiskPhrase','UserDocumentRiskPhrasesId');}
                    } else if (urlPath.indexOf('physicalproperties.aspx') != -1) {
                        addUserDocumentHazard(dragItemId,'HealthHazards','EncapsHealthHazardsRows',dragItemName,'AddUserDocumentPhysicalState','UserPhysicalStateId','DeleteUserDocumentPhysicalState','UserDocumentPhysicalStatesId');
                    }
                    
                } else {
                    
                    if (urlPath.indexOf('ebinder/groups.aspx') != -1) {
                        deleteGroupsPickListItem(dragItemId,dragItemDocId,dragItemName,'Current')
                    
                    } else if (urlPath.indexOf('regulatory.aspx') != -1){
                        deleteRegulatoryPickListItem(dragItemId,dragItemName,dragRegulatoryDescription,'Current');
                    
                    } else if (urlPath.indexOf('hazards.aspx') != -1) {
                        if (Drag.gridName == 'HealthHazards')   {deleteUserDocumentHazard(dragItemId,'HealthHazards','EncapsHealthHazardsRows',dragItemName,'DeleteUserDocumentHealthHazard','UserDocumentHealthHazardsId','AddUserDocumentPHealthHazard','UserHealthHazardsId');}
                        if (Drag.gridName == 'PhysicalHazards')   {deleteUserDocumentHazard(dragItemId,'PhysicalHazards','EncapsPhysicalHazardsRows',dragItemName,'DeleteUserDocumentPhysicalHazard','UserDocumentPhysicalHazardsId','AddUserDocumentPhysicalHazard','UserPhysicalHazardsId');}
                        if (Drag.gridName == 'TargetOrgans')   {deleteUserDocumentHazard(dragItemId,'TargetOrgans','EncapsTargetOrgansRows',dragItemName,'DeleteUserDocumentTargetOrgan','UserDocumentTargetOrgansId','AddUserDocumentTargetOrgan','UserTargetOrgansId');}
                        if (Drag.gridName == 'PPEs')   {deleteUserDocumentHazard(dragItemId,'PPEs','EncapsPPEsRows',dragItemName,'DeleteUserDocumentPPE','UserDocumentPPEId','AddUserDocumentPPE','UserPPEsId');}
                        if (Drag.gridName == 'SafetyPhrases')   {deleteUserDocumentHazard(dragItemId,'SafetyPhrases','EncapsSafetyPhrasesRows',dragItemName,'DeleteUserDocumentSafetyPhrase','UserDocumentSafetyPhrasesId','AddUserDocumentSafetyPhrase','UserSafetyPhrasesId');}
                        if (Drag.gridName == 'DOTHazards')   {deleteUserDocumentHazard(dragItemId,'DOTHazards','EncapsDOTHazardsRows',dragItemName,'DeleteUserDocumentDOT','UserDocumentDOTId','AddUserDocumentDOT','UserDOTHazardsId');}
                        if (Drag.gridName == 'RiskPhrases')   {deleteUserDocumentHazard(dragItemId,'RiskPhrases','EncapsRiskPhrasesRows',dragItemName,'DeleteUserDocumentRiskPhrase','UserDocumentRiskPhrasesId','AddUserDocumentRiskPhrase','UserRiskPhrasesId');}
                    } else if(urlPath.indexOf('physicalproperties.aspx') != -1) {
                        deleteUserDocumentHazard(dragItemId,'HealthHazards','EncapsHealthHazardsRows',dragItemName,'DeleteUserDocumentPhysicalState','UserDocumentPhysicalStatesId','AddUserDocumentPhysicalState','UserPhysicalStateId');
                    }
                }
            } else {
                targ.style.left = '0px';
                targ.style.top = '0px';
                targ.style.position = '';
                sortHazardDivs(targ.parentNode.parentNode.id, Drag.gridName);
            }
            
            //set properties back to original state
            targ.style.zIndex = 1;
            targ.style.border = 'none';
            targ.style.width = null;
            targ.style.height = 'auto';
            document.getElementById(targ.id).parentNode.style.height = 'auto';
            isHazardsPage = false;
            
	        Drag.obj = null;
        },

        fixE : function(e)
        {
	        if (typeof e == 'undefined') e = window.event;
	        if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
	        if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
	        return e;
        }
    };
    
    function getCoords(targ, tempDivName)
    {   
        if (destinationGridID != null || destinationGridID != 'none' || destinationGridID != 'undefined') {
            //get the row's coordinates
            var row_Top = findPosY(targ) + 'px';
            var row_Bottom = (parseInt(row_Top) + 23) + 'px';
            var row_Left = findPosX(targ) + 'px';
            var row_Right = (parseInt(row_Left) + 339) + 'px';
            
            //get the grid's coordinates
            a_Top = elementGetTop(document.getElementById(destinationGridID)) + 'px';
            a_Bottom = elementGetTop(document.getElementById(tempDivName)) + 'px';
            var a_Left = elementGetLeft(document.getElementById(destinationGridID)) + 'px';
            var a_Right = (parseInt(a_Left) + 339) + 'px';
            
            //test to see if any part of the row is inside the grid
            if ((((row_Top > a_Top) && (row_Top < a_Bottom)) || ((row_Bottom > a_Bottom) && (row_Bottom < a_Bottom))) && (((row_Left > a_Left) && (row_Left < a_Right)) || ((row_Right > a_Left) && (row_Right < a_Right)))) {
                return true;
            } else {
                return false;
            }
        }
    }
    
    function findPosX(obj)
    {
        var curleft = 0;
        if (obj.offsetParent) {
	        while (obj.offsetParent) {
		        curleft += obj.offsetLeft
		        obj = obj.offsetParent;
	        }
        }
        else if (obj.x)
	        curleft += obj.x;
        return curleft;
    }

    function findPosY(obj)
    {
        var curtop = 0;
        if (obj.offsetParent) {
	        while (obj.offsetParent) {
		        curtop += obj.offsetTop
		        obj = obj.offsetParent;
	        }
        }
        else if (obj.y)
	        curtop += obj.y;
        return curtop;
    }
    

/****************************************************************/
/*                     END DRAG/DROP ROWS                       */
/****************************************************************/


/****************************************************************/
/*                  ADD, REMOVE, & SORT ROWS                    */
/****************************************************************/
var displayOrder = 0;

function removeFromCurrent(gridName, outerdiv, divID, rowText, divToRemove, addWebMethod, addWebVariable, removeWebMethod, removeWebVariable) 
{
    if (openedDiv == 'true') { return; }
        
    pageName = (window.location.pathname).toLowerCase();
    if (pageName.indexOf('regulatory.aspx') != -1) {
        closeDivNow('DescriptionDiv');
    }
    
    //make sure that the edit grid is showing
    showHazardsEditDiv(gridName + 'HidingDiv', gridName + 'EditLink')
    
    //remove row from the 'current' grid
    var d = document.getElementById(outerdiv + 'Current');
    var olddiv = document.getElementById(gridName + divToRemove + 'Minus');
    d.removeChild(olddiv);
    
    //delete grayed row from the 'available' grid
    var d = document.getElementById(outerdiv + 'Available');
    var olddiv = document.getElementById(gridName + divID + 'Grayed');
    d.removeChild(olddiv);
    
    //add row to the 'available' grid as active
    var d = document.getElementById(outerdiv + 'Available');
    var newdiv = document.createElement('div');
    newdiv.className = 'ts5 hazardRow';
    newdiv.id = gridName + divID + 'Plus';
    d.appendChild(newdiv);
    
    //(remove the hidden input because it gets picked up with the innerHTML of the div)
    if (rowText.toString().toLowerCase().indexOf("&lt;input") != -1) {
        rowText = rowText.substring(0,rowText.toString().toLowerCase().indexOf("&lt;input"));
    } else if (rowText.toString().toLowerCase().indexOf("<input") != -1) {
        rowText = rowText.substring(0,rowText.toString().toLowerCase().indexOf("<input"));
    }
    displayRowText = reverseConvertCharacters(rowText)
    rowText = rowText.replace("\'", "\\\'");
    
    //add the html for the row depending on the page
    if (gridName != 'DOTHazards' && gridName != 'SafetyPhrases' && gridName != 'RiskPhrases') {
        newdiv.innerHTML = '<div id="' + gridName + 'Draggable' + divID + '" class="draggable"><div id="' + gridName + divID + 'MainRow"><img src="' + projectPath() + '/Images/PlusIcon.gif" class="hazardsPlusImage" onclick="javascript:lockPickListImage(this);addUserDocumentHazard(\'' + divID + '\',\'' + gridName + '\',\'' + outerdiv + '\',\'' + rowText + '\',\'' + addWebMethod + '\',\'' + addWebVariable + '\',\'' + removeWebMethod + '\',\'' + removeWebVariable + '\',\'\',sessionId);" /><div class="pickListGrayContainer"><a class="ls4 availableEditLink" id="' + gridName + divID + 'EditLink" href="javascript: showHideSlideDown(\'Edit' + gridName + divID + 'SlideDownDiv\',\'' + gridName + divID + 'EditLink\',\'\');populateEditDeleteDivs(edit' + gridName + 'InnerHtml,\'Edit\',\'' + divID + '\',\'' + rowText + '\',\'Edit' + gridName + divID + 'SlideDownDiv\');">Edit</a><div class="ts5 availableElement" id="' + newdiv.id + 'Text">' + displayRowText + '</div></div></div></div><div class="editSlideDownDiv" id="Edit' + gridName + divID + 'SlideDownDiv"></div>';
    } else {
        if (displayOrder < 10) {
            if (displayOrder.substring(0,2) != '00') {
                displayOrder = '00' + displayOrder;
            }
        } else if (displayOrder < 100) {
            if (displayOrder.substring(0,1) != '0') {
                displayOrder = '0' + displayOrder;
            }
        }
        newdiv.innerHTML = '<div id="' + gridName + 'Draggable' + divID + '" class="draggable"><div id="' + gridName + divID + 'MainRow"><img src="' + projectPath() + '/Images/PlusIcon.gif" class="hazardsPlusImage" onclick="javascript:lockPickListImage(this);addUserDocumentHazard(\'' + divID + '\',\'' + gridName + '\',\'' + outerdiv + '\',\'' + rowText + '\',\'' + addWebMethod + '\',\'' + addWebVariable + '\',\'' + removeWebMethod + '\',\'' + removeWebVariable + '\',\'\',sessionId);" /><div class="pickListGrayContainer"><div class="ts5 availableEditLink" id="' + newdiv.id + 'Text">' + displayRowText + '<input type="hidden" id="'+ divID +'DisplayOrder" value="' + displayOrder + '" /></div></div></div></div>';
   
    }
    
    //lastly resort the grid
    sortHazardDivs(outerdiv + 'Current',gridName);
    sortHazardDivs(outerdiv + 'Available',gridName);
    
    //recalculate height of the page
    setHazardsPageHeight(gridName);
}

function addToCurrent(gridName, outerdiv, divID, rowText, divToRemove, addWebMethod, addWebVariable, removeWebMethod, removeWebVariable) {
    if (openedDiv == 'true')
        return;
        
    pageName = (window.location.pathname).toLowerCase();
    if (pageName.indexOf('regulatory.aspx') != -1) {
        closeDivNow('DescriptionDiv');
    }
    
    var d = document.getElementById(outerdiv + 'Current');    
    
    //remove the no items message row if present
    var noItems = document.getElementById(gridName + 'NoCurrentItems')
    if (noItems != null){
        d.removeChild(noItems);
    }
    
    //add row to the 'current' grid
    var newdiv = document.createElement('div');
    newdiv.className = 'hazardRow';
    newdiv.id = gridName + divID + 'Minus';
    newdiv.setAttribute('userid',divToRemove);
    d.appendChild(newdiv);
    
    //(remove the hidden input because it gets picked up with the innerHTML of the div)
    if (rowText.toString().toLowerCase().indexOf("&lt;input") != -1) {
        rowText = rowText.substring(0,rowText.toString().toLowerCase().indexOf("&lt;input"));
    } else if (rowText.toString().toLowerCase().indexOf("<input") != -1) {
        rowText = rowText.substring(0,rowText.toString().toLowerCase().indexOf("<input"));
    }
    displayRowText = reverseConvertCharacters(rowText)
    rowText = rowText.replace("\'", "\\\'");
    
    if (gridName != 'DOTHazards' && gridName != 'SafetyPhrases' && gridName != 'RiskPhrases') {
        newdiv.innerHTML = '<div id="' + gridName + 'Draggable' + divID + '" class="draggable"><img src="' + projectPath() + '/Images/MinusIcon.gif" class="hazardsMinusImage" onclick="javascript:lockPickListImage(this);deleteUserDocumentHazard(\'' + divID + '\',\'' + gridName + '\',\'' + outerdiv + '\',\'' + rowText + '\',\'' + removeWebMethod + '\',\'' + removeWebVariable + '\',\'' + addWebMethod + '\',\'' + addWebVariable + '\',\'\',sessionId)" alt="" /><div class="ts5 gridText" id="' + newdiv.id + 'Text">' + displayRowText + '</div></div>'; 
    } else {
        newdiv.innerHTML = '<div id="' + gridName + 'Draggable' + divID + '" class="draggable"><img src="' + projectPath() + '/Images/MinusIcon.gif" class="hazardsMinusImage" onclick="javascript:lockPickListImage(this);deleteUserDocumentHazard(\'' + divID + '\',\'' + gridName + '\',\'' + outerdiv + '\',\'' + rowText + '\',\'' + removeWebMethod + '\',\'' + removeWebVariable + '\',\'' + addWebMethod + '\',\'' + addWebVariable + '\',\'\',sessionId)" alt="" /><div class="ts5 gridText" id="' + newdiv.id + 'Text">' + displayRowText + '<input type="hidden" id="'+ divID +'DisplayOrder" value="' + displayOrder + '"/></div></div>'; 
    }
           
    //add a grayed out row to the 'available' grid
    var d = document.getElementById(outerdiv + 'Available');
    var othernewdiv = document.createElement('div');
    othernewdiv.className = 'ts5 hazardRow';
    othernewdiv.id = gridName + divToRemove + 'Grayed';
    d.appendChild(othernewdiv);
    
 //add the html for the row
    if (gridName != 'DOTHazards' && gridName != 'SafetyPhrases' && gridName != 'RiskPhrases') {
        othernewdiv.innerHTML = '<div id="' + gridName + 'NonDraggable' + divToRemove + '">' + 
                                '<img src="' + projectPath() + '/Images/Spacer.gif" class="hazardsSpacerImage" alt="" />' + 
                                '<div class="pickListGrayContainer">' + 
                                '<a href="javascript: showHideSlideDown(\'Edit' + gridName + divToRemove + 'SlideDownDiv\')" id="' + gridName + divToRemove + 'EditLink" class="ls4 availableEditLink">Edit</a>' +
                                '<div class="ts5 availableElementGrayed" id="' + othernewdiv.id + 'Text">' + displayRowText + '</div></div></div>' +
                                '<div id="Edit' + gridName + divToRemove + 'SlideDownDiv" class="editSlideDownDiv">' +
                                '<input type="text" id="' + gridName + divToRemove + 'TextBox" value="' + rowText + '" class="ts2 inputBox editTextBox" />' +
                                '<input type="button" id="' + gridName + divToRemove + 'SaveButton"  class="button buttonSave addNewSave" value="Save" onclick=\"addEditHazardsFunction(\'' + gridName + divToRemove + 'TextBox\',1,\''+outerdiv+'\',\''+divToRemove+'\',\'HealthHazards\', \''+addWebMethod.replace('AddUserDocument','AddEditUser')+'\', \''+addWebMethod.replace('AddUserDocument','')+'\', \''+ addWebMethodVariable +'\',\'\',\''+addWebMethod+'\',\''+addWebMethodVariable+'\',\''+removeWebMethod+'\',\''+removeWebMethodVariable+'\');" />' +
                                '<input type="reset" id="' + gridName + divToRemove + 'CancelButton" class="button buttonCancel addNewCancel" value="Cancel" onclick="showHideSlideDown(\'Edit' + gridName + divToRemove + 'SlideDownDiv\')" />' +
                                '<a href="javascript: showHideSlideDown(\'Edit' + gridName + divToRemove + 'SlideDownDivConfirm\');" id="' + gridName + divToRemove + 'DeleteButton" class="ls6 addNewDeleteLink">Delete</a></div>' +
                                '<div id="Edit' + gridName + divToRemove + 'SlideDownDivConfirm" class="editSlideDownDiv"><div class="ts5 confirmDeleteText">Click to confirm removal of this item</div>' +
                                '<input type="button" id="' + gridName + divToRemove + 'ConfirmDeleteButton"  class="button buttonConfirmDelete addNewConfirmDelete" value="Confirm Delete" onclick=\"showHideSlideDown(\'Edit' + gridName + divToRemove + 'SlideDownDiv\',\'\',\'true\');deleteHazardsFunction(\''+divToRemove+'\',\''+outerdiv+'\',\'HealthHazards'+divToRemove+'Plus\',\''+removeWebMethod+'\',\''+removeWebMethodVariable+'\');\"/>' +
                                '<input type="reset" id="' + gridName + divToRemove + 'ConfirmCancelButton" class="button buttonCancel addNewCancel" value="Cancel" onclick="showHideSlideDown(\'Edit' + gridName + divToRemove + 'SlideDownDivConfirm\')" /></div>';
    } else {
        othernewdiv.innerHTML = '<div id="' + gridName + 'NonDraggable' + divToRemove + '"><img src="' + projectPath() + '/Images/Spacer.gif" class="hazardsSpacerImage" alt="" /><div class="pickListGrayContainer"><div class="ts5 availableElementGrayed availableRiskSafetyDotGray" id="' + othernewdiv.id + 'Text">' + displayRowText + '<input type="hidden" id="'+ divToRemove +'DisplayOrder" value="' + displayOrder + '"/></div></div></div>';
    }
    
    //remove the active row from the 'available' grid
    var d = document.getElementById(outerdiv + 'Available');
    var olddiv = document.getElementById(gridName + divToRemove + 'Plus');
    d.removeChild(olddiv);
    
    //lastly resort the grid
    sortHazardDivs(outerdiv + 'Current',gridName);
    sortHazardDivs(outerdiv + 'Available',gridName);
    
    //recalculate height of the page
    setHazardsPageHeight(gridName);
}

function sortHazardDivs(theID,outerGridName) {
    
    //user the passed in grid name
    if (outerGridName != ''){
        gridName = outerGridName;
    } else {
        gridName = '';
    }
    
    var numberChildren = document.getElementById(theID).childNodes.length;
    
    var urlPath = (window.location.toString()).toLowerCase();
    if(browserName == 'Safari') {
        numberChildren += 2;
    }
    
    //only sort if there are items in the grid 
    //otherwise, insert the no items assigned row.
    if (numberChildren == 0) {
        var d = document.getElementById(theID);
        var newdiv = document.createElement('div');
        newdiv.className = 'ts5 hazardRow hazardNoItemAssignedRow';
        newdiv.id = gridName + 'NoCurrentItems';
        d.appendChild(newdiv);
        newdiv.innerHTML = 'No items currently assigned';
        hasNoItemsId = newdiv.id;
    }else{
        if (document.getElementById(theID).firstChild.id.indexOf('NoCurrentItems') == -1) {
            var currDivs = new Array();
            var valuesToSort = [];
            var sortedDivs = [];
            var index = 0;
            var strippedName = '';
            var theParentNode = document.getElementById(theID);
            
            for(var i = 0; i < theParentNode.childNodes.length; i++) {
	            if(theParentNode.childNodes[i].nodeType == 1) {
	                if (gridName != 'DOTHazards' && gridName != 'SafetyPhrases' && gridName != 'RiskPhrases') {
	                    //create array of parent div's for sorting
	                    //strip out non alphanumeric characters and whitespace
	                    strippedName = forceAlphaNumeric(document.getElementById(theParentNode.childNodes[i].id + 'Text').innerHTML);
	                    //force uppercase for correct sorting
	                    strippedName = strippedName.toUpperCase();
	                    currDivs[strippedName] = theParentNode.childNodes[i].id;
		                valuesToSort.push(strippedName);
	                } else {
	                    temp = theParentNode.childNodes[i].id.replace('RiskPhrases','');
	                    temp = temp.replace('SafetyPhrases','');
	                    temp = temp.replace('DOTHazards','');
	                    temp = temp.replace('Minus','');
	                    temp = temp.replace('Plus','');
	                    temp = temp.replace('Grayed','');
	                    temp = temp.replace('Gray','');
	                    strippedName = document.getElementById(temp + 'DisplayOrder').value;
	                    for (var j = 0; j < 3; j++) {
	                        if (strippedName.substr(0,1) == '0') {
	                            strippedName = strippedName.substr(1,strippedName.length);
	                        }
	                    }
	                    if (strippedName < 10) {
	                        strippedName = '00'+strippedName;
	                    } else if (strippedName < 100) {
	                        strippedName = '0'+strippedName;
	                    }
	                    currDivs[strippedName] = theParentNode.childNodes[i].id;
		                valuesToSort.push(strippedName);
	                }
	            }
            }
            valuesToSort.sort();
            
            //determine background colors for even and odd rows
            for (var i = 0; i < valuesToSort.length; i++) {
                if ((Math.round(i/2)) == (i/2)) {
                    document.getElementById(currDivs[valuesToSort[i]]).style.backgroundColor = '#FFFFFF';
                } else {
                    document.getElementById(currDivs[valuesToSort[i]]).style.backgroundColor = '#F7F7F7';
                }
                //add the div elements into an array
                sortedDivs[i] = document.getElementById(currDivs[valuesToSort[i]]);
            }
            
            //add sorted rows back into the grids
            for (var i = 0; i < sortedDivs.length; i++) {
	            theParentNode.appendChild(sortedDivs[i]);
	        }
	    }
    }
}

/****************************************************************/
/*                END ADD, REMOVE, & SORT ROWS                  */
/****************************************************************/


/****************************************************************/
/*                    SHOW/HIDE PICK LISTS                      */
/****************************************************************/
var oldHazardsEditLink;

function hideOtherGrids(gridArray) 
{
    if (openedDiv == 'true')
        return;
     
    for (x = 0; x < gridArray.length; x++) {
        hideGrid(gridArray[x] + 'ArrowImage', gridArray[x] + 'Grid');
        closeHazardsDivNow(gridArray[x] + 'HidingDiv');
    }
}

function hideGrid(arrow, div) 
{
    if (openedDiv == 'true')
        return;
    
    document.getElementById(arrow).src = projectPath() + '/Images/blk_arrow_dn.gif';
    document.getElementById(arrow).name = 'down';
    document.getElementById(div).style.display = 'none';
}

function closeHazardsDivNow(divId)
{
    if (openedDiv == 'true')
        return;
    
    //roll the hiding div in
    document.getElementById(divId).style.display = 'none';
    
    //enable the edit link
    var editLink = divId.substring(0, divId.indexOf('Hiding')) + 'EditLink';
    if (document.getElementById(editLink).disabled) {
        document.getElementById(editLink).setAttribute('href', oldHazardsEditLink);
        document.getElementById(editLink).disabled = false;
        document.getElementById(editLink).className = 'ls4 gridEditLink';
        document.getElementById(editLink).style.color = '#095BA6';
        document.getElementById(divId + 'Arrow').src = '../Images/BlackArrowRight.gif';
    }
    
    //find if the page is Hazards.aspx
    pathname = window.location.pathname;
    splitPathname = pathname.split("\/");
    pathnameArrayLength = splitPathname.length;
    for(i=1; i < pathnameArrayLength; i++)
    {
        if (splitPathname[i].indexOf(".") != -1) {
            if (splitPathname[i] == "hazards.aspx" ||  splitPathname[i] == "physicalproperties.aspx") {
                //set the page height back to normal
                if (divId.indexOf('Hiding') != -1) {
                    if (parseInt(document.getElementById('EbinderTabContentSection').style.height) > 280) {
                        document.getElementById('EbinderTabContentSection').style.height = 'auto';
                    }
                }
            }
        }
    }
}

function showHazardsEditDiv(gridName,linkName)
{
    //set the grid's top position (this won't change)
    document.getElementById(gridName).style.position = '';
    
    var gridTop = elementGetTop(document.getElementById(linkName)) + 2;
    var currentLeft = elementGetLeft(document.getElementById(linkName)) + 74;
    
    document.getElementById(gridName).style.top = gridTop + 'px';
    document.getElementById(gridName).style.left = currentLeft + 'px';
    
    if (document.getElementById(linkName) != "") {
        oldHazardsEditLink = document.getElementById(linkName).href;
        document.getElementById(linkName).disabled = true;
        document.getElementById(linkName).removeAttribute('href');
        document.getElementById(linkName).className = 'ts5 gridEditLink';
        document.getElementById(linkName).style.color = '#919191';
        document.getElementById(gridName + 'Arrow').src = '../Images/GrayArrowRight.gif';
    }
        
    document.getElementById(gridName).style.display = 'block';
    
    setHazardsPageHeight(gridName);
}

function setHazardsPageHeight(gridName) {
    //move the bottom of the page down if hiding list is longer than the page
    if (gridName.indexOf('HidingDiv') != -1) {
        var gridTempDivID = gridName.substring(0, (gridName.indexOf('HidingDiv'))) + 'TempDiv';
    } else {
        var gridTempDivID = gridName + 'TempDiv';
    }
    
    //find if the page is Hazards.aspx
    pathname = window.location.pathname;
    splitPathname = pathname.split("\/");
    pathnameArrayLength = splitPathname.length;
    for(i=1; i < pathnameArrayLength; i++) {
        if (splitPathname[i].indexOf(".") != -1) {
            if (splitPathname[i].toLowerCase() == "hazards.aspx") {
                var tempDivTop = elementGetTop(document.getElementById(gridTempDivID));
                var gridBottomDivTop = elementGetTop(document.getElementById('HazardsGridBottomDiv'));
                var ebinderContentSection = document.getElementById('EbinderTabContentSection');
                if (tempDivTop >= elementGetTop(document.getElementById('HazardsFooter'))) {
                    document.getElementById('EbinderTabContentSection').style.height = (tempDivTop - elementGetTop(ebinderContentSection) + 50) + 'px';
                    document.getElementById('FooterUserControl').style.top = document.getElementById('EbinderTabContentSection').style.height;
                }else if ((gridBottomDivTop + 50) >= elementGetTop(document.getElementById('HazardsFooter'))) {
                    document.getElementById('EbinderTabContentSection').style.height = (gridBottomDivTop - elementGetTop(ebinderContentSection) + 50) + 'px';
                    document.getElementById('FooterUserControl').style.top = document.getElementById('EbinderTabContentSection').style.height;
                }
            }
        }
    }
}

/****************************************************************/
/*                  END SHOW/HIDE PICK LISTS                    */
/****************************************************************/


/*********************************************************************************/
/*                     START RESIZE TEXTAREA BOX MK'S CODE                       */
/*********************************************************************************/
function textareaResize(textareaName){
    var textareaRows = document.getElementById(textareaName);
    if (browserName == 'Opera') {	
        textareaRows.rows = 2;
    } else if (browserName == 'Netscape' || browserName == 'Firefox') {
        textareaRows.rows = 1;
    } else if (browserName == 'IE') {
        textareaRows.rows = 3;
    } else {
        textareaRows.rows = 3;
    }
}
/*********************************************************************************/
/*                       END RESIZE TEXTAREA BOX MK'S CODE                       */
/*********************************************************************************/

/*********************************************************************************/
/*                      START SHOW HIDE DROPDOWN MK'S CODE                       */
/*********************************************************************************/
function showHideDropdown(showHideDivName,showDivDropdownName,showHideDivDropdownName){
    var groupSelectedValue = document.getElementById(showDivDropdownName).selectedIndex;
    if (groupSelectedValue == 0){
        document.getElementById(showHideDivName).style.display = 'none';
        if (showHideDivDropdownName != "") {
            document.getElementById(showHideDivDropdownName).selectedIndex = 0
        }
    }else {
        document.getElementById(showHideDivName).style.display = 'block';
        if (showHideDivDropdownName != "") {
            document.getElementById(showHideDivDropdownName).selectedIndex = 0
        }
    }
}
/*********************************************************************************/
/*                       END SHOW HIDE DROPDOWN MK'S CODE                        */
/*********************************************************************************/

/*********************************************************************************/
/*                        START GET PAGE SIZE MK'S CODE                          */
/*********************************************************************************/
function resizeWindow(divToResize,operaValue,netscapeValue,microsoftValue){
    var divOriginalSize = document.getElementById(divToResize).style.height;
    if (divOriginalSize == ''){
        if (browserName == 'Opera') {	        
            //document.getElementById(divToResize).style.height = operaValue;
            document.getElementById(divToResize).style.minHeight = operaValue;
        } else if (browserName == 'Netscape' || browserName == 'Firefox'){
            //document.getElementById(divToResize).style.height = netscapeValue;
            document.getElementById(divToResize).style.minHeight = netscapeValue;
        } else if (browserName == 'IE' && browserVersion.indexOf('7') != -1) {
            document.getElementById(divToResize).style.minHeight = microsoftValue;
        } else {
            document.getElementById(divToResize).style.height = microsoftValue;
        }
    }else{
        if (browserName == 'Opera') {	
            if (divOriginalSize < operaValue) {
                //document.getElementById(divToResize).style.height = operaValue;
                document.getElementById(divToResize).style.minHeight = operaValue;
            }
        } else if (browserName == 'Netscape' || browserName == 'Firefox') {
            if (divOriginalSize < netscapeValue) {
                //document.getElementById(divToResize).style.height = netscapeValue;
                document.getElementById(divToResize).style.minHeight = netscapeValue;
            }
        } else if (browserName == 'IE' && browserVersion.indexOf('7') != -1) {
            if (divOriginalSize < microsoftValue) {
                document.getElementById(divToResize).style.minHeight = microsoftValue;
            }
        } else {
            if (divOriginalSize < microsoftValue) {
                document.getElementById(divToResize).style.height = microsoftValue;
            }
        }
    }	        
}	    
/*********************************************************************************/
/*                          END GET PAGE SIZE MK'S CODE                          */
/*********************************************************************************/	    

/*********************************************************************************/
/*                         BEGIN COMET FUNCTIONS                                 */
/*********************************************************************************/	
var comet;
var informationElements = new Array()
var pdfInformationElements = new Array()
var divInformationElements = new Array()
var pdfPopUp = "";
var searchSpecial = "";



function getSearchSuggestion(evt,searchFragment){
    //var suggestChecked = document.getElementById('EnableSearchSuggest');
    //if (suggestChecked.checked == true){

        evt = (evt) ? evt : (window.event) ? event : null;
        if (evt){
            var typeEvent = (evt.charCode) ? evt.charCode :
            ((evt.keyCode) ? evt.keyCode :
            ((evt.which) ? evt.which : 0));
            if (typeEvent == 32 || typeEvent == 8 || ((typeEvent > 46 && typeEvent < 112) || typeEvent > 123)){
                var pageName = window.location.toString();
                var suggestElements = new Array();
                var i;
                for (i=1;i<=10;i++){
                    if (pageName.indexOf('NullResultsRequestForm') < 0){
                        suggestElements[i] = 'Suggestion' + i;
                    }else{
                        suggestElements[i] = 'NullSuggestion' + i;
                    }
                }
                clearHTMLElements(suggestElements);
                var projectPathVariable = projectPath()
                var shortProjectPath = projectPathVariable.split("/")
                
                if (pageName.indexOf('AddLocalMsds') < 0){       
                    if (pageName.indexOf('Request/Default') < 0 && pageName.indexOf('NullResultsRequestForm') < 0){
                        var fullProjectPath = cometBaseUrl + '/SearchSuggest';         
                    }else{
                        var fullProjectPath = cometBaseUrl + '/MSDSonlineManufacturerSearchSuggest';         
                    }
                    sendCometRequest('processSearchSuggestion',shortProjectPath[2],fullProjectPath,'SearchFragment,' + searchFragment);
                } else {
                    var fullProjectPath = cometBaseUrl + '/ManufacturerSearchSuggest';         
                    sendCometRequest('processSearchSuggestion',shortProjectPath[2],fullProjectPath,'SearchFragment,' + searchFragment + ';CustomerAdministratorId,' + customerAdministratorId);
                }
            }
        }
    //}
}

function processSearchSuggestion(){
    if (comet.readyState == 4) {
        if (comet.status == 200) {
            if (comet.responseText.indexOf('No Records Found') < 0){
                //suggestions were returned
                var suggestions = getRootElementInformation(comet).split('%BREAK%');
                var fullSuggestions = getRootElementInformation(comet).split('%BREAK%');
                var currentHTML
                var hiddenHTML
                var nullCurrentHTML
                var pageName = window.location.toString();
                if (pageName.indexOf('AddLocalMsds') > 0){ 
                    var z
                    for (z=0;z<suggestions.length;z++){
                        hiddenHTML = document.getElementById('HiddenSuggestion' + (z+1));
                        hiddenHTML.innerHTML = suggestions[z].toUpperCase();
                        hiddenHTML.style.display = 'block';
                    }
                }
                if (pageName.indexOf('NullResultsRequestForm') > 0){ 
                    var y
                    for (y=0;y<suggestions.length;y++){
                        if (suggestions[y].length > 24) {
                            suggestions[y] = suggestions[y].substring(0,24) + '...'
                        }
                        nullCurrentHTML = document.getElementById('NullSuggestion' + (y+1));
                        nullCurrentHTML.innerHTML = suggestions[y].toUpperCase();
                        nullCurrentHTML.style.display = 'block';
                        hiddenHTML = document.getElementById('FullSuggestion' + (y+1));
                        hiddenHTML.innerHTML = fullSuggestions[y].toUpperCase();
                    }
                }
                var i
                for (i=0;i<suggestions.length;i++){
                    if (suggestions[i].length > 24) {
                        suggestions[i] = suggestions[i].substring(0,24) + '...'
                    }
                    currentHTML = document.getElementById('Suggestion' + (i+1));
                    currentHTML.innerHTML = suggestions[i].toUpperCase();
                    currentHTML.style.display = 'block';
                    if (pageName.indexOf('Request/Default') > 0){
                        hiddenHTML = document.getElementById('FullSuggestion' + (i+1));
                        hiddenHTML.innerHTML = fullSuggestions[i].toUpperCase();
                    }
                }                
                
                if (pageName.indexOf('AddLocalMsds') < 0){ 
                    if (pageName.indexOf('Request/Default') < 0 && pageName.indexOf('NullResultsRequestForm') < 0){
                        textBox = document.getElementById('ProductNameText');
                    }else{
                        textBox = document.getElementById('ManufacturerName');
                        if(pageName.indexOf('NullResultsRequestForm') > 0){
                            nullCurrentHTML = document.getElementById('NullSearchSuggest');
                        }
                    }
                } else {
                    textBox = document.getElementById('ManufacturerNameText');
                    hiddenHTML = document.getElementById('HiddenSearchSuggest');
                }
                currentHTML = document.getElementById('SearchSuggest');
                
                if (browserName == 'IE'){
                    var divTop = elementGetTop(textBox) + 17 + 'px';
                    var divLeft = elementGetLeft(textBox) + 2 + 'px'
                }else{
                    var divTop = elementGetTop(textBox) + 17 + 'px';
                    var divLeft = elementGetLeft(textBox) + 'px'
                }               
                currentHTML.style.top = divTop;
                currentHTML.style.left = divLeft;
                if (pageName.indexOf('AddLocalMsds') < 0 && pageName.indexOf('Request/Default') < 0 && pageName.indexOf('NullResultsRequestForm') < 0){ 
                    document.getElementById('RevisionDate').style.visibility = 'hidden';
                }
                    currentHTML.style.display = 'block';
            }            
        } else {
            updateMessageBox(true,'',5);
        }
    }
}

function searchSuggestHighlight(id,on){
    var elementToChange = document.getElementById(id);
    if (on == true){
        elementToChange.style.color = '#095BA6';
        elementToChange.style.backgroundColor = '#9DBDDB';
        elementToChange.style.cursor = 'pointer';
    }else{
        elementToChange.style.color = '#000000';
        elementToChange.style.backgroundColor = '#FFFFFF';
        elementToChange.style.cursor = 'default';
    }
}

function searchSuggestSelect(id){
    var pageName = window.location.toString();
    if (pageName.indexOf('AddLocalMsds') > 0){ 
        id = id.substring(10);
        id = 'HiddenSuggestion' + id;
        }
    if (pageName.indexOf('NullResultsRequestForm') > 0){ 
        id = id.substring(10);
        id = 'FullSuggestion' + id;
        }
    var selectedElement = document.getElementById(id);
    if (pageName.indexOf('AddLocalMsds') < 0){ 
        if (pageName.indexOf('Request/Default') < 0 && pageName.indexOf('NullResultsRequestForm') < 0){
            var textBox = document.getElementById('ProductNameText');
        }else{
            var textBox = document.getElementById('ManufacturerName');
        }
    } else {
        var textBox = document.getElementById('ManufacturerNameText');
    }

    textBox.value = selectedElement.innerHTML.replace(/&amp;/g, '&');
}

function hideSearchSuggest(){
    var pageName = window.location.toString();
    var searchSuggest = document.getElementById('SearchSuggest');
    searchSuggest.style.display = 'none';
    if (pageName.indexOf('AddLocalMsds') < 0 && pageName.indexOf('Request/Default') < 0 && pageName.indexOf('NullResultsRequestForm') < 0){ 
        document.getElementById('RevisionDate').style.visibility = 'visible';
        }
}

//-----------------------------------//
//      Synonym Comet Functions      //
//-----------------------------------//

//------------------------------------------------//
//  Start Previous/Next and Row Change Functions  //
//------------------------------------------------//

//--------------------------------------------//        
// This function changes the background color //
// for the eBinder pages when the divs are    //
// clicked.                                   //
//--------------------------------------------//        

var ebinderTotalResultsCount;

function getRequestPageNumber(){
    var requestQueryPageNumber = window.location.href;
    var requestPageNumber = window.location.href;
    splitRequestPageNumber = requestPageNumber.split("\/");
    requestPageNumberArrayLength = splitRequestPageNumber.length;
    if (requestQueryPageNumber.indexOf('PageNumber') != -1 && requestQueryPageNumber.indexOf('default') != -1) {
        for(i=1; i < requestPageNumberArrayLength; i++) {                          
            if (splitRequestPageNumber[i].indexOf(".") != -1) {
                splitRequestPageNumber[i] = splitRequestPageNumber[i].toLowerCase();
                splitRequestPageNumber[i] = splitRequestPageNumber[i].replace('default.aspx?','');
                splitRequestPageNumber[i] = splitRequestPageNumber[i].split('&');
                 for(var j=0; j < splitRequestPageNumber[i].length; j++) {
                    requestPageNumber = splitRequestPageNumber[i][0];
                  }
            }
        }
        requestPageNumber = requestPageNumber.replace('pagenumber=',''); 
    }else{
        var cookiePageNumber = readCookie(3);
        cookiePageNumber = parseInt(cookiePageNumber);
        requestPageNumber = cookiePageNumber;
    }
    return requestPageNumber;
}

function changeRowColor(divId,newDiv,event)
{   
    //don't change row color if clicking on pdf or icon image
    if (event) {
        var eventTarget = event.target?event.target:event.srcElement;
        if (eventTarget != null){
            if (eventTarget.nodeName == 'IMG'){
                return;
            }
        }
    }
        
    // pageSize variable is equal to the Session("PageSize") - pageSize set on ebinder/default.aspx page
    var sessionPageSize = pageSize;
    var requestPageNumber = getRequestPageNumber();
    requestPageNumber = requestPageNumber.toString();
    if (requestPageNumber.indexOf(';') != -1){
        var requestPageArray = new Array();
        requestPageArray = requestPageNumber.split(';');
        requestPageNumber = requestPageArray[0];
    }
    requestPageNumber = parseInt(requestPageNumber);

    var cookiePageNumber = readCookie(3);
    cookiePageNumber = parseInt(cookiePageNumber);
        
    var requestQueryPageNumber = window.location.href;
    if ((requestPageNumber != cookiePageNumber) && (requestPageNumber == 1) && ((requestQueryPageNumber.indexOf('PageNumber') == -1))){
        requestPageNumber = cookiePageNumber;
    }
    whiteBorderInformation = '1px solid #FFFFFF';
    grayBorderInformation = '1px solid #F7F7F7';
    var i;
    var startNumber;
    var endNumber;
    var potentialEndNumber;
    if (requestPageNumber == 1){
        startNumber = 1;
        potentialEndNumber = sessionPageSize;
        if (potentialEndNumber > ebinderTotalResultsCount){
            endNumber = ebinderTotalResultsCount;
        }else{
            endNumber = potentialEndNumber;
        }
    }else{
        startNumber = ((requestPageNumber-1)*sessionPageSize) + 1;
        potentialEndNumber = startNumber + (sessionPageSize - 1);
        if (potentialEndNumber > ebinderTotalResultsCount){
            endNumber = ebinderTotalResultsCount;
        }else{
            endNumber = potentialEndNumber;
        }
    }
    for(i = startNumber; i <= endNumber; i++)
    {
       if (i != endNumber){
            j = i + 1;
            grayDivId = "searchGrayResults" + j;
    
            if (document.getElementById(grayDivId) != null) {
                    grayOnClickDiv = "searchGrayResultsOnClick" + j;
                    document.getElementById(grayDivId).style.borderTop = grayBorderInformation;
                    document.getElementById(grayDivId).style.borderBottom = grayBorderInformation;
                    document.getElementById(grayDivId).style.background = '#F7F7F7';
                    document.getElementById(grayDivId).style.display = 'block';
                    document.getElementById(grayOnClickDiv).style.display = 'none';

                whiteDivId = "searchResults" + i;
                whiteOnClickDiv = "searchResultsOnClick" + i;
                document.getElementById(whiteDivId).style.borderTop = whiteBorderInformation;
                document.getElementById(whiteDivId).style.borderBottom = whiteBorderInformation;
                document.getElementById(whiteDivId).style.background = '#FFFFFF';
                document.getElementById(whiteDivId).style.display = 'block';
                document.getElementById(whiteOnClickDiv).style.display = 'none';
                i++;
            }
        }
    }
    document.getElementById(divId).style.display = "none";
    document.getElementById(newDiv).style.display = "block";
}


function checkRowColor(isPreviousNextLinks,linkName,customerAdministratorId,customerUserId){
    // Get AutoNumber from Cookie to define what row should be highlighted
    if (typeof(window['ebinderProductNameValue']) != 'undefined'){
        if (ebinderTotalResultsValue != ""){
            ebinderTotalResultsCount = ebinderTotalResultsValue;
        }
        if (ebinderProductNameValue != ""){
            ebinderProductNameValue = replaceSpecialCharacters(ebinderProductNameValue);
            var ebinderOpenPdf = '0';
            var pageName = (window.location.toString()).toLowerCase();
            if (pageName.indexOf('ebinder') != -1) {
                if (pageName.indexOf('default') == -1) {
                    ebinderOpenPdf = readCookie(5);
                    
                }
            }
            document.cookie = "UserEbinderInformation=EbinderAutoNumber="+ebinderAutoNumberValue+"&EbinderDocumentName="+encodeURIComponent(ebinderProductNameValue)+"&EbinderDocumentId="+ebinderUserDocumentIdValue+"&EbinderPageNumber="+ebinderPageNumberValue+"&EbinderLibraryId="+ebinderLibraryId+"&EbinderOpenPdf=" + ebinderOpenPdf + "&EbinderEnd=yes;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";
        }
    }
    var cookiePageNumber = readCookie(3);
    cookiePageNumber = parseInt(cookiePageNumber);

    var oddEvenCookiePage = eval(cookiePageNumber)/2;
    var comparisonCookiePage = Math.round(oddEvenCookiePage);
    var isEvenNumberPage = false;
    if (oddEvenCookiePage == comparisonCookiePage){
        isEvenNumberPage = true;
    }
    var colorRowSearch;
    var colorHighlightedRowSearch;
    var rowNumber = readCookie(0);
    if (isPreviousNextLinks == 1) {
        rowNumber = parseInt(rowNumber);
        if (linkName == 'Next'){
            rowNumber = rowNumber + 1;
        }else{
            rowNumber = rowNumber - 1;
        }
    }
        
    oddEvenNumber = eval(rowNumber)/2;
    var comparisonNumber = Math.round(oddEvenNumber);
    var isEvenNumberRow = false;
    if (comparisonNumber == oddEvenNumber){
        isEvenNumberRow = true;
    }
    if (((comparisonNumber == oddEvenNumber) && (isEvenNumberPage == false)) || ((comparisonNumber != oddEvenNumber) && (isEvenNumberPage == true) && (isEvenNumberRow == false))) {
        colorRowSearch = 'searchGrayResults' + rowNumber;
        colorHighlightedRowSearch = 'searchGrayResultsOnClick' + rowNumber;
    } else {
        colorRowSearch = 'searchResults' + rowNumber;
        colorHighlightedRowSearch = 'searchResultsOnClick' + rowNumber;
    }
    
    // Get Page Number from QueryString and Cookie to make sure that if the user is on the page
    // that has the row that should be highlighted it is - otherwise still allow the user to page 
    // through without calling the function to highlight the row
    var requestQueryPageNumber = window.location.href;
    if (requestQueryPageNumber.indexOf('PageNumber') != -1) {
        var requestPageNumber = getRequestPageNumber();
        if ((cookiePageNumber == requestPageNumber) && (requestQueryPageNumber.indexOf('PageNumber') != -1)){
            changeRowColor(colorRowSearch, colorHighlightedRowSearch);
        }    
    }else{
        // if the user is coming to the ebinder page from the ebinder link (no paging)
        // then check to see if the row that should be highlighted is on the first page
        changeRowColor(colorRowSearch, colorHighlightedRowSearch);
    }   
    if ((rowNumber == 1) && (cookiePageNumber == 1)){
        document.getElementById('PreviousLink').innerHTML = "<label class='ts16'>&lt;Previous MSDS</label>";
    }else{
        document.getElementById('PreviousLink').innerHTML = '<A class=ls4 id=PreviousNextText1 href="javascript:movePreviousNextMsds(\'Previous\');">&lt;Previous MSDS</A>';
    }
    if (typeof(window['ebinderTotalResultsValue']) != 'undefined'){
        if (ebinderTotalResultsValue != ""){
            if (rowNumber == ebinderTotalResultsValue){
                document.getElementById('NextLink').innerHTML = "<label class='ts16'>Next MSDS&gt;</label>";
            }else{
                document.getElementById('NextLink').innerHTML = '<A class=ls4 id=PreviousNextText2 href="javascript:movePreviousNextMsds(\'Next\');">Next MSDS&gt;</A>';
            }
            var cookieLibraryId = readCookie(4);
            cookieLibraryId = parseInt(cookieLibraryId);
            if (isNaN(cookieLibraryId)){
                cookieLibraryId = readCookie(4);
            }
            openPDFLibraryId = cookieLibraryId;
            openPDFDocumentId = ebinderUserDocumentId;
            
            libraryId = cookieLibraryId.toString();
            libraryFolder = libraryId.substr(0,3);
            var ebinderLibraryPathValue = libraryFolder + "/" + libraryId + ".pdf";
            var beginningDeclaration = "";
            if ((hQCall == 'True' && hqClientType == '0') || hQCall == ''){
                if (hQCall == 'True'){
                    beginningDeclaration = 'parent.';
                }
                //if ((window.location.pathname).toLowerCase() == "/ebinder/default.aspx") {
                
                    //document.getElementById('ViewPdf').innerHTML = '<a href="javascript:updateOpenPdfCookie(1);'+beginningDeclaration+'openPDF(\'10\',\'10\',\'960\',\'140\',\'260\',\''+cookieLibraryId+'\',\''+ebinderUserDocumentId+'\',\'informationDiv\',true,\'\',\'\',\'\',\''+customerAdministratorId+'\',\''+customerUserId+'\',\'10\',\''+ebinderSelectedProductName+'\',\''+hqClientType+'\',\'\',\''+browserName+'\',\''+browserVersion+'\');"><img class=tabsHeaderImages alt="" src="'+projectPath()+'/Images/PdfIcon2.gif"></a>';
                //} else {
                    document.getElementById('ViewPdf').innerHTML = '<a href="javascript:updateOpenPdfCookie(1);'+beginningDeclaration+'openPDF(\'10\',\'10\',\'960\',\'140\',\'260\',\''+cookieLibraryId+'\',\''+ebinderUserDocumentId+'\',\'informationDiv\',true,\'\',\'\',\'\',\''+customerAdministratorId+'\',\''+customerUserId+'\',\'10\',\''+ebinderSelectedProductName+'\',\''+hqClientType+'\',\'\',\''+browserName+'\',\''+browserVersion+'\');"><img class=tabsHeaderImages alt="" src="'+projectPath()+'/Images/PdfIcon2.gif"></a>';
                    if(! firstTimeHere) {
                        updateOpenPdfCookie(1);
                        if(hQCall == 'True') {
                            parent.openPDF('10', '10', '960', '140', '260', cookieLibraryId, ebinderUserDocumentId, 'informationDiv', true, '', '', '', customerAdministratorId, customerUserId, '10', ebinderSelectedProductName, hqClientType, '', browserName, browserVersion);
                        } else {
                            openPDF('10', '10', '960', '140', '260', cookieLibraryId, ebinderUserDocumentId, 'informationDiv', true, '', '', '', customerAdministratorId, customerUserId, '10', ebinderSelectedProductName, hqClientType, '', browserName, browserVersion);
                        }
                    } else {
                        firstTimeHere = 0;
                    }
                //}
                
                if (document.getElementById('PrintLabelLink')) {
                    document.getElementById('PrintLabelLink').href = 'javascript:' + beginningDeclaration + 'ebinderPrintLabel(' + ebinderUserDocumentId + ');';
                }
            }else{
                document.getElementById('ViewPdf').innerHTML = '<A href="javascript:loadwindow(\''+httpPath+libraryPath+ebinderLibraryPathValue+'\',796,508,\''+ebinderUserDocumentId+'\')"><IMG class=tabsHeaderImages alt="" src="'+projectPath()+'/Images/PdfIcon.gif"></A>';
                updateOpenPdfCookie(1);
                openPDF('10', '10', '960', '140', '260', cookieLibraryId, ebinderUserDocumentId, 'informationDiv', true, '', '', '', customerAdministratorId, customerUserId, '10', ebinderSelectedProductName, hqClientType, '', browserName, browserVersion);
                
                if (document.getElementById('PrintLabelLink')) {
                    document.getElementById('PrintLabelLink').href = 'javascript:' + beginningDeclaration + 'ebinderPrintLabel(' + ebinderUserDocumentId + ');';
                }
            }
            
//            if ((window.location.pathname).toLowerCase() == "/ebinder/default.aspx") {
//                document.getElementById('ViewPdf').innerHTML = '<A href="javascript:updateOpenPdfCookie(1);openPDF(\'10\',\'10\',\'960\',\'140\',\'260\',\'' + cookieLibraryId + '\',\''+ebinderUserDocumentId+'\',\'informationDiv\',true,\'\',\'\',\'\',\''+customerAdministratorId+'\',\''+customerUserId+'\',\'10\',\''+ebinderSelectedProductName+'\',\''+browserName+'\',\''+browserVersion+'\');"><IMG class=tabsHeaderImages alt="" src="'+projectPath()+'/Images/PdfIcon2.gif"></A>';
//            } else {
//                document.getElementById('ViewPdf').innerHTML = '<A href="javascript:updateOpenPdfCookie(1);openPDF(\'10\',\'10\',\'960\',\'140\',\'260\',\'' + cookieLibraryId + '\',\''+ebinderUserDocumentId+'\',\'informationDiv\',true,\'\',\'\',\'\',\''+customerAdministratorId+'\',\''+customerUserId+'\',\'10\',\''+ebinderSelectedProductName+'\',\''+browserName+'\',\''+browserVersion+'\');"><IMG class=tabsHeaderImages alt="" src="'+projectPath()+'/Images/PdfIcon2.gif"></A>';
//            }
        }
    }

    if (isPreviousNextLinks == 1) {
        var cookieDocumentName = document.getElementById('EbinderProductNameRow' + rowNumber).innerHTML;
      
        if (browserName == 'Opera') {	
            cookieDocumentName = cookieDocumentName.replace('</A>','');
        } else if (browserName == 'Netscape' || browserName == 'Firefox') {
            cookieDocumentName = cookieDocumentName.replace('</a>','');
        } else {
            cookieDocumentName = cookieDocumentName.replace('</A>','');
        }
        var entireStringLength = cookieDocumentName.length;
        var anchorTagLength = cookieDocumentName.lastIndexOf('>');
        anchorTagLength = anchorTagLength + 1;
        cookieDocumentName = cookieDocumentName.substring(anchorTagLength,entireStringLength);
        cookieDocumentName = trimString(cookieDocumentName);
        cookieDocumentName = replaceSpecialCharacters(cookieDocumentName);
        
        var entireProductNameInnerHtml = document.getElementById('NewProductColumn' + rowNumber).innerHTML;
        var idPattern = /<img.+id=["|']?(\d+)["|']?.*\/?>/i;
        var cookieDocumentId = idPattern.exec(entireProductNameInnerHtml)[1];   
        
        var entireLibraryIdInnerHtml = document.getElementById('ViewMsdsColumn' + rowNumber).innerHTML;
        
        if (browserName == 'Opera') {	
            entireLibraryIdInnerHtml = entireLibraryIdInnerHtml.replace(rowNumber+'<A id="','');
            entireLibraryIdInnerHtml = entireLibraryIdInnerHtml.split('"');
        } else if (browserName == 'Netscape' || browserName == 'Firefox' || browserName == 'Safari') {
            entireLibraryIdInnerHtml = entireLibraryIdInnerHtml.replace(rowNumber+'<a id="','');
            entireLibraryIdInnerHtml = entireLibraryIdInnerHtml.split('"');
        } else {
            entireLibraryIdInnerHtml = entireLibraryIdInnerHtml.replace(rowNumber+'<A id=','');
            entireLibraryIdInnerHtml = entireLibraryIdInnerHtml.split(' ');
        }
        var cookieLibraryId = entireLibraryIdInnerHtml[0];
        
        updateEbinderPreviousNextCookies(rowNumber,cookiePageNumber,cookieDocumentId,cookieDocumentName,cookieLibraryId,customerAdministratorId,customerUserId);
    }    
}

function readCookie(arrayValue){
    var returnValue;
    var cookieInformation = document.cookie.toString();
    if (cookieInformation.indexOf('UserEbinderInformation') != -1) {
        if (arrayValue == 0) {
            var autoNumber = cookieInformation.substring(cookieInformation.indexOf('EbinderAutoNumber=') + 18,cookieInformation.indexOf('&EbinderDocumentName'));
            returnValue = autoNumber;
        }else if(arrayValue == 1){
            var documentName = cookieInformation.substring(cookieInformation.indexOf('EbinderDocumentName=') + 20,cookieInformation.indexOf('&EbinderDocumentId'));
            returnValue = decodeURIComponent(documentName);
        }else if(arrayValue == 2){
            var documentId = cookieInformation.substring(cookieInformation.indexOf('EbinderDocumentId=') + 18,cookieInformation.indexOf('&EbinderPageNumber'));
            returnValue = documentId;
        }else if(arrayValue == 3){
            var pageNumber = cookieInformation.substring(cookieInformation.indexOf('EbinderPageNumber=') + 18,cookieInformation.indexOf('&EbinderLibraryId'));
            if (pageNumber == '0'){pageNumber = '1';}
            returnValue = pageNumber;
        }else if(arrayValue == 4){
            var LibraryId = cookieInformation.substring(cookieInformation.indexOf('EbinderLibraryId=') + 17,cookieInformation.indexOf('&EbinderOpenPdf'));
            returnValue = LibraryId;
        }else if(arrayValue == 5){
            var LibraryId = cookieInformation.substring(cookieInformation.indexOf('EbinderOpenPdf=') + 15,cookieInformation.indexOf('&EbinderEnd'));
            returnValue = LibraryId;
        }
    }
    return returnValue;
}

function replaceSpecialCharacters(stringToCheck){
    if (stringToCheck.indexOf("&amp;") != -1){
        //stringToCheck = stringToCheck.replace("&amp;","~A~M~P~S~E~M~I~");   
        var characterToRemove = "&amp;";
        var characterToReplaceWith = "~A~M~P~S~E~M~I~";
        var temporaryHolder = "" + stringToCheck; 
        var positionOfCharacter;

        while (temporaryHolder.indexOf(characterToRemove) > -1) {
            positionOfCharacter = temporaryHolder.indexOf(characterToRemove);
            temporaryHolder = "" + (temporaryHolder.substring(0, positionOfCharacter) + characterToReplaceWith + 
            temporaryHolder.substring((positionOfCharacter + characterToRemove.length), temporaryHolder.length));
        }
        stringToCheck = temporaryHolder;        
    }
    if (stringToCheck.indexOf("&") != -1){
        //stringToCheck = stringToCheck.replace("&","~A~M~P~");        
        var characterToRemove = "&";
        var characterToReplaceWith = "~A~M~P~";
        var temporaryHolder = "" + stringToCheck; 
        var positionOfCharacter;

        while (temporaryHolder.indexOf(characterToRemove) > -1) {
            positionOfCharacter = temporaryHolder.indexOf(characterToRemove);
            temporaryHolder = "" + (temporaryHolder.substring(0, positionOfCharacter) + characterToReplaceWith + 
            temporaryHolder.substring((positionOfCharacter + characterToRemove.length), temporaryHolder.length));
        }
        stringToCheck = temporaryHolder;        
    }
    if (stringToCheck.indexOf(",") != -1){
        //stringToCheck = stringToCheck.replace(",","~C~O~M~M~A~");
        var characterToRemove = ",";
        var characterToReplaceWith = "~C~O~M~M~A~";
        var temporaryHolder = "" + stringToCheck; 
        var positionOfCharacter;

        while (temporaryHolder.indexOf(characterToRemove) > -1) {
            positionOfCharacter = temporaryHolder.indexOf(characterToRemove);
            temporaryHolder = "" + (temporaryHolder.substring(0, positionOfCharacter) + characterToReplaceWith + 
            temporaryHolder.substring((positionOfCharacter + characterToRemove.length), temporaryHolder.length));
        }
        stringToCheck = temporaryHolder;
    }
    if (stringToCheck.indexOf(";") != -1){ 
        var characterToRemove = ";";
        var characterToReplaceWith = "~S~E~M~I~";
        var temporaryHolder = "" + stringToCheck; 
        var positionOfCharacter;

        while (temporaryHolder.indexOf(characterToRemove) > -1) {
            positionOfCharacter = temporaryHolder.indexOf(characterToRemove);
            temporaryHolder = "" + (temporaryHolder.substring(0, positionOfCharacter) + characterToReplaceWith + 
            temporaryHolder.substring((positionOfCharacter + characterToRemove.length), temporaryHolder.length));
        }
        stringToCheck = temporaryHolder;
    }
    return stringToCheck;
}
function placeSpecialCharacters(stringToCheck){
    if (stringToCheck.indexOf("~A~M~P~S~E~M~I~")){
        stringToCheck = stringToCheck.replace("~A~M~P~S~E~M~I~","&");
        var characterToRemove = "~A~M~P~S~E~M~I~";
        var characterToReplaceWith = "&";
        var temporaryHolder = "" + stringToCheck; 
        var positionOfCharacter;

        while (temporaryHolder.indexOf(characterToRemove) > -1) {
            positionOfCharacter = temporaryHolder.indexOf(characterToRemove);
            temporaryHolder = "" + (temporaryHolder.substring(0, positionOfCharacter) + characterToReplaceWith + 
            temporaryHolder.substring((positionOfCharacter + characterToRemove.length), temporaryHolder.length));
        }
        stringToCheck = temporaryHolder;
    }
    if (stringToCheck.indexOf("~A~M~P~")){
        stringToCheck = stringToCheck.replace("~A~M~P~","&");
        var characterToRemove = "~A~M~P~";
        var characterToReplaceWith = "&";
        var temporaryHolder = "" + stringToCheck; 
        var positionOfCharacter;

        while (temporaryHolder.indexOf(characterToRemove) > -1) {
            positionOfCharacter = temporaryHolder.indexOf(characterToRemove);
            temporaryHolder = "" + (temporaryHolder.substring(0, positionOfCharacter) + characterToReplaceWith + 
            temporaryHolder.substring((positionOfCharacter + characterToRemove.length), temporaryHolder.length));
        }
        stringToCheck = temporaryHolder;
    }
    if (stringToCheck.indexOf("~C~O~M~M~A~")){
        stringToCheck = stringToCheck.replace("~C~O~M~M~A~",",");
        var characterToRemove = "~C~O~M~M~A~";
        var characterToReplaceWith = ",";
        var temporaryHolder = "" + stringToCheck; 
        var positionOfCharacter;

        while (temporaryHolder.indexOf(characterToRemove) > -1) {
            positionOfCharacter = temporaryHolder.indexOf(characterToRemove);
            temporaryHolder = "" + (temporaryHolder.substring(0, positionOfCharacter) + characterToReplaceWith + 
            temporaryHolder.substring((positionOfCharacter + characterToRemove.length), temporaryHolder.length));
        }
        stringToCheck = temporaryHolder;
    }
    if (stringToCheck.indexOf("~S~E~M~I~")){    
        var characterToRemove = "~S~E~M~I~";
        var characterToReplaceWith = ";";
        var temporaryHolder = "" + stringToCheck; 
        var positionOfCharacter;

        while (temporaryHolder.indexOf(characterToRemove) > -1) {
            positionOfCharacter = temporaryHolder.indexOf(characterToRemove);
            temporaryHolder = "" + (temporaryHolder.substring(0, positionOfCharacter) + characterToReplaceWith + 
            temporaryHolder.substring((positionOfCharacter + characterToRemove.length), temporaryHolder.length));
        }
        stringToCheck = temporaryHolder;
    }
    return stringToCheck;
}

function updateEbinderPreviousNextCookies(autoNumber,pageNumber,documentId,documentName,libraryId,customerAdministratorId,customerUserId){
    if (documentName == 'EbinderProductNameRow'){
        var productNameRow = 'EbinderProductNameRow' + autoNumber;
        var productName = document.getElementById(productNameRow).innerHTML;
        if (browserName == 'Opera') {	
            productName = productName.replace('<A href="Synonyms.aspx" class="ls4" title="Click to edit this product.">','');
            documentName = productName.replace('</A>','');
        } else if (browserName == 'Netscape' || browserName == 'Firefox' || browserName == 'Safari') {
            productName = productName.replace('<a href="Synonyms.aspx" class="ls4" title="Click to edit this product.">','');
            documentName = productName.replace('</a>','');
        } else {
            productName = productName.replace('<A class=ls4 title="Click to edit this product." href="Synonyms.aspx">','');
            documentName = productName.replace('</A>','');
        }
    }
    ebinderSelectedProductName = documentName.replace("'","\'");

    var cookiePageNumber = getRequestPageNumber();    
    documentName = trimString(documentName);
    documentName = replaceSpecialCharacters(documentName);
    var ebinderOpenPdf = 0;
    var pageName = (window.location.toString()).toLowerCase();
    if (pageName.indexOf('ebinder') != -1) {
        //if (pageName.indexOf('default') == -1) {
            ebinderOpenPdf = readCookie(5);
        //}
    }
    resetCookie("UserEbinderInformation=EbinderAutoNumber=&EbinderDocumentName=&EbinderDocumentId=&EbinderPageNumber=&EbinderLibraryId=&EbinderOpenPdf=0&EbinderEnd=",-1);
    document.cookie = "UserEbinderInformation=EbinderAutoNumber="+autoNumber+"&EbinderDocumentName="+encodeURIComponent(documentName)+"&EbinderDocumentId="+documentId+"&EbinderPageNumber="+cookiePageNumber+"&EbinderLibraryId="+libraryId+"&EbinderOpenPdf=" + ebinderOpenPdf + "&EbinderEnd=yes;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";
    documentName = placeSpecialCharacters(documentName);
    var eBinderPageMsdsText = document.getElementById('EbinderEditNameText').innerHTML = "Edit <label id=MsdsProductName class=ts8>"+documentName+"</label>";
    document.getElementById('EbinderEditNameText').innerHTML = eBinderPageMsdsText;
    if ((autoNumber == 1) && (cookiePageNumber == 1)){
        document.getElementById('PreviousLink').innerHTML = "<label class='ts16'>&lt;Previous MSDS</label>";
    }else{
        document.getElementById('PreviousLink').innerHTML = '<A class=ls4 id=PreviousNextText1 href="javascript:movePreviousNextMsds(\'Previous\');">&lt;Previous MSDS</A>'
    }
    
    if (ebinderTotalResultsCount == autoNumber){
        document.getElementById('NextLink').innerHTML = "<label class='ts16'>Next MSDS&gt;</label>";
    }else{
        document.getElementById('NextLink').innerHTML = '<A class=ls4 id=PreviousNextText2 href="javascript:movePreviousNextMsds(\'Next\');">Next MSDS&gt;</A>';
    } 
        
    libraryId = libraryId.toString();
    libraryFolder = libraryId.substring(0,3);
    var ebinderLibraryPathValue = libraryFolder + "/" + libraryId + ".pdf";
    var beginningDeclaration = "";
    if ((hQCall == 'True' && hqClientType == '0') || hQCall == ''){
        if (hQCall == 'True'){
            beginningDeclaration = 'parent.';
        }
        if ((window.location.pathname).toLowerCase() == "/ebinder/default.aspx") {
            document.getElementById('ViewPdf').innerHTML = '<a href="javascript:updateOpenPdfCookie(1);'+beginningDeclaration+'openPDF(\'10\',\'10\',\'960\',\'140\',\'260\',\''+libraryId+'\',\''+documentId+'\',\'informationDiv\',true,\'\',\'\',\'\',\''+customerAdministratorId+'\',\''+customerUserId+'\',\'10\',\''+ebinderSelectedProductName+'\',\'\',\''+browserName+'\',\''+browserVersion+'\');"><img class=tabsHeaderImages alt="" src="'+projectPath()+'/Images/PdfIcon2.gif"></a>';
            //if (hQCall != 'True') { openPDF('10','10','960','140','260',''+libraryId+'',''+documentId+'','informationDiv',true,'','','',''+customerAdministratorId+'',''+customerUserId+'','10',''+ebinderSelectedProductName+'','',''+browserName+'',''+browserVersion+''); }
            if (ebinderOpenPdf == '1') { parent.openPDF('10','10','960','140','260',''+libraryId+'',''+documentId+'','informationDiv',true,'','','',''+customerAdministratorId+'',''+customerUserId+'','10',''+ebinderSelectedProductName+'','',''+browserName+'',''+browserVersion+''); }
        } else {
            document.getElementById('ViewPdf').innerHTML = '<a href="javascript:updateOpenPdfCookie(1);'+beginningDeclaration+'openPDF(\'10\',\'10\',\'960\',\'140\',\'260\',\''+libraryId+'\',\''+documentId+'\',\'informationDiv\',true,\'\',\'\',\'\',\''+customerAdministratorId+'\',\''+customerUserId+'\',\'10\',\''+ebinderSelectedProductName+'\',\'\',\''+browserName+'\',\''+browserVersion+'\');"><img class=tabsHeaderImages alt="" src="'+projectPath()+'/Images/PdfIcon2.gif"></a>';
            //if (hQCall != 'True') { openPDF('10','10','960','140','260',''+libraryId+'',''+documentId+'','informationDiv',true,'','','',''+customerAdministratorId+'',''+customerUserId+'','10',''+ebinderSelectedProductName+'','',''+browserName+'',''+browserVersion+''); }
            if (ebinderOpenPdf == '1') { parent.openPDF('10','10','960','140','260',''+libraryId+'',''+documentId+'','informationDiv',true,'','','',''+customerAdministratorId+'',''+customerUserId+'','10',''+ebinderSelectedProductName+'','',''+browserName+'',''+browserVersion+''); }
        }
        
        
        if (document.getElementById('PrintLabelLink')) {
            document.getElementById('PrintLabelLink').href = 'javascript:' + beginningDeclaration + 'ebinderPrintLabel(' + documentId + ');';
        }
    }else{
        document.getElementById('ViewPdf').innerHTML = '<A href="javascript:loadwindow(\''+httpPath+libraryPath+ebinderLibraryPathValue+'\',796,508,\''+ebinderUserDocumentId+'\')"><IMG class=tabsHeaderImages alt="" src="'+projectPath()+'/Images/PdfIcon.gif"></A>';
    }
}
//-----------------------------------------------------------

//-----------------------------------------------------------
function checkIfFirstOrLastRow(previousOrNextValue,tabPages,customerAdministratorId,customerUserId){
    if (typeof(window['ebinderProductNameValue']) != 'undefined'){
        if (ebinderProductNameValue != ""){
            ebinderProductNameValue = '';
            ebinderUserDocumentIdValue = '';
            ebinderAutoNumberValue = '';
            ebinderPageNumberValue = '';
            ebinderLibraryId = '';
        }
    }
    var rowNumber = readCookie(0);
    var sessionPageSize = pageSize;
    var requestPageNumber = getRequestPageNumber();
    requestPageNumber = requestPageNumber.toString();
    if (requestPageNumber.indexOf(';') != -1){
        var requestPageArray = new Array();
        requestPageArray = requestPageNumber.split(';');
        requestPageNumber = requestPageArray[0];
    }
    requestPageNumber = parseInt(requestPageNumber);

    var cookiePageNumber = readCookie(3);
    cookiePageNumber = parseInt(cookiePageNumber);
    
    var requestQueryPageNumber = window.location.href;
    if ((requestPageNumber != cookiePageNumber) && (requestPageNumber == 1) && ((requestQueryPageNumber.indexOf('PageNumber') == -1))){
        requestPageNumber = cookiePageNumber;
    }

    var startNumber;
    var endNumber;
    if (requestPageNumber == 1){
        startNumber = 1;
        endNumber = sessionPageSize;
    }else{
        startNumber = ((requestPageNumber-1)*sessionPageSize) + 1;
        endNumber = startNumber + (sessionPageSize - 1);
    }
    
    var redirectPage = projectPath() + '/eBinder/Default.aspx?PageNumber=';
        
    if ((previousOrNextValue == 'Previous') && (tabPages == false)){
        if (rowNumber == startNumber){
            if (rowNumber == 1){
                document.form1.submit();
            }else{
                getPreviousNextDocumentInformation(rowNumber,(requestPageNumber - 1),'-1');
            }
        }else{
            checkRowColor(1,'Previous',customerAdministratorId,customerUserId);
        }
    }else if((previousOrNextValue == 'Previous') && (tabPages)){
        if ((rowNumber == 1)){
            document.form1.submit();
        }else if ((startNumber + 1) < rowNumber){
            getPreviousNextDocumentInformation(rowNumber,(requestPageNumber),'-1');
        }else{
            getPreviousNextDocumentInformation(rowNumber,(requestPageNumber - 1),'-1');
        }
    }
    
    if ((previousOrNextValue == 'Next') && (tabPages == false)){
        if (rowNumber == endNumber){
            getPreviousNextDocumentInformation(rowNumber,(requestPageNumber + 1),1);
        }else{
            checkRowColor(1,'Next',customerAdministratorId,customerUserId);            
        }
    }else if((previousOrNextValue == 'Next') && (tabPages)){
        if((startNumber <= rowNumber) && (rowNumber <= (endNumber - 1))){
            getPreviousNextDocumentInformation(rowNumber,(requestPageNumber),1);
        }else{
            getPreviousNextDocumentInformation(rowNumber,(requestPageNumber + 1),1);
        }
    }
    
}

function getPreviousNextDocumentInformation(autoNumber,pageNumber,previousOrNextDocument){
    var projectPathVariable = projectPath()
    var shortProjectPath = projectPathVariable.split("/")
    var fullProjectPath = cometBaseUrl + '/GetPreviousNextMsds';

    sendCometRequest('processPreviousNextDocumentInformation',shortProjectPath[2],fullProjectPath,'CustomerAdministratorId,'+customerAdministratorId+';CustomerUserId,' + customerUserId + ';SessionId,' + sessionId + ';ProductNameDescriptor,' + ebinderSearchProductName + ';CompanyNameDescriptor,' + ebinderSearchManufacturer + ';GenericDescriptor,' + ebinderSearchIdentifier + ';GenericDescriptorSearchField,' + ebinderSearchIdentifierSearchType + ';InventoryType,'+ebinderSearchInventoryType+';InventoryID,' + ebinderSearchInventory + ';LanguageID,' + ebinderSearchLanguage + ';ApprovalID,' + ebinderSearchApproval + ';CustomGroupID,' + ebinderSearchCustomGroup + ';SourceID,' + ebinderSearchSource + ';RegulatoryGroupID,' + ebinderSearchRegulatoryGroup + ';Status,'+ebinderSearchStatus+';SortID,' + ebinderSearchQuickSort + ';SortHow,'+ebinderSearchSortHow+';ProductNameSearchLogic,' + ebinderSearchProductNameSearchType + ';CompanyNameSearchLogic,' + ebinderSearchManufacturerSearchType + ';PageNumber,' + pageNumber + ';PageSize,' + pageSize + ';PreviousOrNext,' + previousOrNextDocument + ';AutoNumber,' + autoNumber);
}

function processPreviousNextDocumentInformation(){
    if (comet.readyState == 4) {
        if (comet.status == 200) {
            if (comet.responseText.indexOf('No Record Found') < 0){
                var suggestions = getRootElementInformation(comet).split('~~M~A~Y~A~~');
                
                var newAutoNumber = suggestions[3];
                var newDocumentName = suggestions[2];
                var newDocumentId = suggestions[4];
                var newPageNumber = suggestions[0]; 
                var newLibraryId = suggestions[5];       
                var redirectPage = projectPath() + '/eBinder/Default.aspx?PageNumber=';
                newDocumentName = trimString(newDocumentName);
                newDocumentName = replaceSpecialCharacters(newDocumentName);
                ebinderSelectedProductName = newDocumentName.replace("'","\'");
                var ebinderOpenPdf = 0;
                var pageName = (window.location.toString()).toLowerCase();
                if (pageName.indexOf('ebinder') != -1) {
                    if (pageName.indexOf('default') == -1) {
                        ebinderOpenPdf = readCookie(5);
                    }
                }
                resetCookie("UserEbinderInformation=EbinderAutoNumber=&EbinderDocumentName=&EbinderDocumentId=&EbinderPageNumber=&EbinderLibraryId=&EbinderOpenPdf=0&EbinderEnd=",-1);
                document.cookie = "UserEbinderInformation=EbinderAutoNumber="+newAutoNumber+"&EbinderDocumentName="+encodeURIComponent(newDocumentName)+"&EbinderDocumentId="+newDocumentId+"&EbinderPageNumber="+newPageNumber+"&EbinderLibraryId="+newLibraryId+"&EbinderOpenPdf=" + ebinderOpenPdf + "&EbinderEnd=yes;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";
                                
                document.form1.submit();             
            }            
        } else {
            updateMessageBox(true,'',5);
        }
    }
}

function checkPreviousNextLinkDisplay(ebinderTotalResultsCount){    
    //this function is needed on the page load of every tab in the ebinder section
    //in order to turn the previous/next link on/off
    var rowNumber = readCookie(0);
    var pageNumber = readCookie(3);
    pageNumber = parseInt(pageNumber);    
    if ((rowNumber == 1) && ((pageNumber == 1) || (pageNumber == 0))){
        document.getElementById('PreviousLink').innerHTML = "<label class='ts16'>&lt;Previous MSDS</label>";
        var cookiePageNumber = 1;
        var cookieDocumentName = readCookie(1);
        cookieDocumentName = placeSpecialCharacters(cookieDocumentName);
        var cookieDocumentId = readCookie(2);
        var cookieLibraryId = readCookie(4);
        var ebinderOpenPdf = 0;
        var pageName = (window.location.toString()).toLowerCase();
        if (pageName.indexOf('ebinder') != -1) {
            if (pageName.indexOf('default') == -1) {
                ebinderOpenPdf = readCookie(5);
            }
        }
        cookieDocumentName = replaceSpecialCharacters(cookieDocumentName);
        resetCookie("UserEbinderInformation=EbinderAutoNumber=&EbinderDocumentName=&EbinderDocumentId=&EbinderPageNumber=&EbinderLibraryId=&EbinderOpenPdf=0&EbinderEnd=", -1);
        document.cookie = "UserEbinderInformation=EbinderAutoNumber="+rowNumber+"&EbinderDocumentName="+encodeURIComponent(cookieDocumentName)+"&EbinderDocumentId="+cookieDocumentId+"&EbinderPageNumber="+cookiePageNumber+"&EbinderLibraryId="+cookieLibraryId+"&EbinderOpenPdf=" + ebinderOpenPdf + "&EbinderEnd=yes;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";  
    }else{
        document.getElementById('PreviousLink').innerHTML = '<A class=ls4 id=PreviousNextText1 href="javascript:movePreviousNextMsds(\'Previous\');">&lt;Previous MSDS</A>'
    }    
    if (ebinderTotalResultsCount == rowNumber){
        document.getElementById('NextLink').innerHTML = "<label class='ts16'>Next MSDS&gt;</label>";
    }else{
        document.getElementById('NextLink').innerHTML = '<A class=ls4 id=PreviousNextText2 href="javascript:movePreviousNextMsds(\'Next\');">Next MSDS&gt;</A>';
    } 
    
}

function getCookieExpirationDate(numberOfDays){
    var dateString;
    Today = new Date();
    parseTodayDate = Date.parse(Today);
    Today.setTime(parseTodayDate+numberOfDays*24*60*60*1000);
    dateString = Today.toUTCString();
    return dateString;
}
function getCookie(cookieName) {
    var cookieValue = "" + document.cookie;
    var index1 = cookieValue.indexOf(cookieName);
    if (index1==-1 || cookieName=="") return ""; 
    var index2=cookieValue.indexOf(';',index1);
    if (index2==-1) index2=cookieValue.length; 
    return cookieValue.substring(index1+cookieName.length+1,index2);
}
function resetCookie(name,duration){
    fullCookie = name + ";EXPIRES=" + getCookieExpirationDate(duration);
    document.cookie = fullCookie;
    if(!getCookie(name)){
        return false;
    }else{
        return true;
    }
}


//------------------------------------------------//
//   End Previous/Next and Row Change Functions   //
//------------------------------------------------//

//------------------------------------------------//
//        Edit and Delete Drop Down Divs          //
//------------------------------------------------//
    function populateEditDeleteDivs(innerHtml,editDeleteFlag,itemId,itemText,populateDiv,itemDesc,itemDocCount)
    {
        var temp = "";
        //itemText = itemText.replace("\"", "&quot;");
        itemText = convertSpecialCharacters(itemText);
        itemText = reverseConvertCharacters(itemText);
        //itemText = itemText.replace("\\\'", "'");
        
        if (editDeleteFlag.toUpperCase() == "EDIT")
        {
            temp = innerHtml.replace(/\+itemId\+/g, itemId);
            temp = temp.replace(/\+itemText\+/g, itemText);
            
            temp = temp.replace(/\+itemDesc\+/g, itemDesc);
            temp = temp.replace(/\+itemDocCount\+/g, itemDocCount);
            
            document.getElementById(populateDiv).innerHTML = temp;
        } else {
            temp = innerHtml.replace(/\+itemId\+/g, itemId);
            temp = temp.replace(/\+itemText\+/g, itemText);
            
            temp = temp.replace(/\+itemDesc\+/g, itemDesc);
            temp = temp.replace(/\+itemDocCount\+/g, itemDocCount);
            
            document.getElementById(populateDiv).innerHTML = temp;
        }
    }
    
    function deleteListItem(RowId,EditRowId,XmlOutputLabel){
        document.getElementById(XmlOutputLabel).removeChild(document.getElementById(RowId));
        document.getElementById(XmlOutputLabel).removeChild(document.getElementById(EditRowId));
        openedDiv = 'false';
        movingRowId = '';
        initialLink = '';
    }

    function convertCharacters(textToConvert)
    {
        while (textToConvert.indexOf('"') > -1) {textToConvert = textToConvert.replace('"','^q^u^o^t^e^');}
        while (textToConvert.indexOf('&quot;') > -1) {textToConvert = textToConvert.replace('&quot;','^q^u^o^t^e^');}
        while (textToConvert.indexOf(';') > -1) {textToConvert = textToConvert.replace(';','^s^e^m^i^c^o^l^o^n^');}
        while (textToConvert.indexOf('&') > -1) {textToConvert = textToConvert.replace('&','^a^m^p^');}
        while (textToConvert.indexOf(',') > -1) {textToConvert = textToConvert.replace(',','^c^o^m^m^a^');}
        while (textToConvert.indexOf('\'') > -1) {textToConvert = textToConvert.replace('\'','^a^p^o^s^');}
        return textToConvert;
    }
//------------------------------------------------//
//     End Edit and Delete Drop Down Divs         //
//------------------------------------------------//

//------------------------------------------------//
//       Pick List Web Method Variables           //
//------------------------------------------------//

var itemId;
var callingGrid;
var itemDocumentId;
var hasNoItemsId;
var itemName;
var regulatoryDescription;
var rowContainerDiv;
var removeItemId;
var addNewTextBoxId;
var deleteRow;
var addWebMethodCall;
var addWebMethodVariable;
var removeWebMethodCall;
var removeWebMethodVariable;
var defaultAddNewText;
var checkHQCall = 'false';

//------------------------------------------------//
//       End Pick List Web Method Variables       //
//------------------------------------------------//

//------------------------------------------------//
//         Add/Remove Pick List Items             //
//------------------------------------------------//

function processPickListDelete(){
    if (comet.readyState == 4) {
        if (comet.status == 200) {
            removeListItem();
            sortHazardDivs('EncapsHealthHazardsRowsCurrent','Current');
            sortHazardDivs('EncapsHealthHazardsRowsAvailable');
            //updateMessageBox(false,'',6);
        } else {
            //updateMessageBox(true,'',5);
        }
    }
}

function processPickListAdd(){
    if (comet.readyState == 4) {
        if (comet.status == 200) {
            var urlPath = (window.location.toString()).toLowerCase();
            if (urlPath.indexOf('regulatory.aspx') != -1 || urlPath.indexOf('groups.aspx') != -1) {
                var itemDocumentId = getRootElementInformation(comet);
                addListItem(itemDocumentId);
            }else{
                addListItem("");
            }
            sortHazardDivs('EncapsHealthHazardsRowsCurrent','Current');
            sortHazardDivs('EncapsHealthHazardsRowsAvailable');
            //updateMessageBox(false,'',7);
            //Update the "Last Date Changed" value
            updateLastDateChangedToToday();
        } else {
            //updateMessageBox(true,'',5);
        }
    }
}

function removePickListRow(outerDivName,rowId) {
    //remove row from the 'current' grid
    var d = document.getElementById(outerDivName);
    var olddiv = document.getElementById(rowId);
    d.removeChild(olddiv);
    movingRowId = "";
    openedDiv = false;
}

function removeListItem() {
    var urlPath = (window.location.toString()).toLowerCase();
    
    //make sure that the edit grid is showing
    showHazardsEditDiv('HealthHazardsHidingDiv','HealthHazardsEditLink');

    //remove row from the 'current' grid
    removePickListRow('EncapsHealthHazardsRowsCurrent',itemId + 'Current');
    
    //add the 'No items assigned' row if no rows are in Current
    addNoItemsRowIfNeeded();
    
    //remove the grayed row from the 'available' grid
    removePickListRow('EncapsHealthHazardsRowsAvailable',itemId + 'Available');
    
    //add row to the 'Available' grid
    var d = document.getElementById('EncapsHealthHazardsRowsAvailable');
    var newdiv = document.createElement('div');
    newdiv.className = 'hazardRow';
    newdiv.id = itemId + 'Available';
    d.appendChild(newdiv);
    
    itemName = itemName.replace('<','&lt;');
    if (urlPath.indexOf('regulatory.aspx') != -1) {
        regulatoryDescription = regulatoryDescription.replace('<','&lt;');
        var shortenedItemName = itemName;
        if (shortenedItemName.length > 47) {
            shortenedItemName = itemName.substring(0,45) + "...";
        }
        newdiv.innerHTML = '<div class="draggable" id="' + itemId + 'DraggableAvailable"><img src="' + projectPath() + '/Images/PlusIcon.gif" class="hazardsPlusImage" alt="" onclick="javascript:lockPickListImage(this);addRegulatoryPickListItem(\'' + itemId + '\',\'' + itemName + '\',\'' + regulatoryDescription + '\',\'Available\')" /><div class="pickListGrayContainer"><img src="' + projectPath() + '/Images/InformationIcon.gif" class="informationButton" alt="" id="' + itemId + 'InfoIconAvailable" onclick="showRegulatoryDescription(\'' + itemId + '\',this.id)" /><div class="ts5 availableElement" id="' + itemId + 'AvailableText">' + shortenedItemName + '</div></div><input type="hidden" id="' + itemId + 'InfoPopupDesc" value="' + regulatoryDescription + '" /><input type="hidden" /></div>';
      
    } else if (urlPath.indexOf('ebinder/groups.aspx') != -1) {
        newdiv.innerHTML = '<div class="draggable" id="' + itemId + 'DraggableAvailable"><img src="' + projectPath() + '/Images/PlusIcon.gif" class="hazardsPlusImage" alt="" onclick="javascript:lockPickListImage(this);addGroupsPickListItem(\'' + itemId + '\',\'' + itemDocumentId + '\',\'' + itemName + '\',\'Available\')" /><div class="ts5 availableElement" id="' + itemId + 'AvailableText">' + itemName + '</div><input type="hidden" /></div>';
    }
}

function addNoItemsRowIfNeeded() {

    //Get the number of rows in the grid
    var numberChildren = document.getElementById('EncapsHealthHazardsRowsCurrent').childNodes.length;
    
    //White space is counted as children (arg)
    //If no rows, add a row stating that there are no children
    if (numberChildren == 0) {
        var d = document.getElementById('EncapsHealthHazardsRowsCurrent');
        var newdiv = document.createElement('div');
        newdiv.className = 'ts5 hazardRow hazardNoItemAssignedRow';
        newdiv.id = callingGrid + 'NoCurrentItems';
        d.appendChild(newdiv);
        newdiv.innerHTML = 'No items currently assigned';
        hasNoItemsId = newdiv.id;
    }
}

function addListItem(itemDocumentId) {
    var urlPath = (window.location.toString()).toLowerCase();
    var d = document.getElementById('EncapsHealthHazardsRowsCurrent');
    
    //remove the no items message row if present
    var noItems = document.getElementById('CurrentNoCurrentItems')
    if (noItems != null){
        d.removeChild(noItems);
    }
    
    //add row to the 'current' grid
    var newdiv = document.createElement('div');
    newdiv.className = 'hazardRow';
    newdiv.id = itemId + 'Current';
    d.appendChild(newdiv);
    
    itemName = itemName.replace('<','&lt;');
    if (urlPath.indexOf('regulatory.aspx') != -1) {
        regulatoryDescription = regulatoryDescription.replace('<','&lt;');
        regulatoryDescription = regulatoryDescription.replace('\'','&amp;rsquo;');
        var shortenedItemName = itemName;
        if (shortenedItemName.length > 47) {
            shortenedItemName = itemName.substring(0,45) + "...";
        }
        newdiv.innerHTML = '<div class="hazardRow" id="' + itemId + 'Current"><div class="draggable" id="' + itemId + 'DraggableCurrent"><img src="' + projectPath() + '/Images/MinusIcon.gif" class="hazardsMinusImage" alt="" onclick="javascript:lockPickListImage(this);deleteRegulatoryPickListItem(\'' + itemId + '\',\'' + itemName + '\',\'' + regulatoryDescription + '\',\'Current\')" /><div class="pickListContainer"><img src="' + projectPath() + '/Images/InformationIcon.gif" class="informationButton" alt="" id="' + itemId + 'InfoIconCurrent" onclick="showRegulatoryDescription(\'' + itemId + '\',this.id)" /><div class="ts5 gridText" id="' + itemId + 'CurrentText">' + shortenedItemName + '</div></div><input type="hidden" id="' + itemId + 'InfoPopupDesc" value="' + regulatoryDescription + '" /><input type="hidden" id="' + itemId + 'UserDocumentRegulatoryCategoryId" value="' + itemDocumentId + '" /></div>';
    } else if (urlPath.indexOf('ebinder/groups.aspx') != -1) {
        newdiv.innerHTML = '<div class="hazardRow" id="' + itemId + 'Current"><div class="draggable" id="' + itemId + 'DraggableCurrent"><img src="' + projectPath() + '/Images/MinusIcon.gif" class="hazardsMinusImage" alt="" onclick="javascript:lockPickListImage(this);deleteGroupsPickListItem(\'' + itemId + '\',\'' + itemDocumentId + '\',\'' +  itemName + '\',\'Current\');showHazardsEditDiv(\'HealthHazardsHidingDiv\',\'HealthHazardsEditLink\');" /><div class="ts5 gridText" id="' + itemId + 'CurrentText">' + itemName + '</div><input type="hidden" id="' + itemDocumentId + '" /></div>';
    }

    //remove the active row from the 'available' grid
    removePickListRow('EncapsHealthHazardsRowsAvailable',itemId + 'Available');
    
    //add a grayed out row to the 'available' grid
    var d = document.getElementById('EncapsHealthHazardsRowsAvailable');
    var newdiv = document.createElement('div');
    newdiv.className = 'ts5 hazardRow';
    newdiv.id = itemId + 'Available';
    d.appendChild(newdiv);
    
    itemName = itemName.replace('<','&lt;');
    if (urlPath.indexOf('regulatory.aspx') != -1) {
        regulatoryDescription = regulatoryDescription.replace('<','&lt;');
        var shortenedItemName = itemName;
        if (shortenedItemName.length > 47) {
            shortenedItemName = itemName.substring(0,45) + "...";
        }
        newdiv.innerHTML = '<div id="' + itemId + 'NonDraggableAvailable"><img src="' + projectPath() + '/Images/Spacer.gif" class="hazardsSpacerImage" alt="" /><div class="pickListGrayContainer"><img src="' + projectPath() + '/Images/InformationIcon.gif" class="informationButton" alt="" id="' + itemId + 'InfoIconAvailable" onclick="showRegulatoryDescription(\'' + itemId + '\',this.id)" /><div class="ts5 availableElementGrayed" id="' + itemId + 'AvailableText">' + shortenedItemName + '</div></div><input type="hidden" id="' + itemId + 'InfoPopupDesc" value="' + regulatoryDescription + '" />';
    } else if (urlPath.indexOf('ebinder/groups.aspx') != -1) {
        newdiv.innerHTML = '<div id="' + itemId + 'NonDraggableAvailable"><img src="' + projectPath() + '/Images/Spacer.gif" class="hazardsSpacerImage" alt="" /><div class="ts5 availableElementGrayed" id="' + itemId + 'AvailableText">' + itemName + '</div></div>';
    }
}

function resetBackgroundColors(addOrDelete,outerDivId,newdiv,innerContent) {

    var currDivs = [];
    var index = 0;
    var theParentNode = document.getElementById(outerDivId);
    
    for(var i = 0; i < theParentNode.childNodes.length; i++) {
        if(theParentNode.childNodes[i].nodeType == 1) {
            currDivs.push(theParentNode.childNodes[i].id);
        }
    }

    for (var i = 0; i < currDivs.length; i++) {
        if ((Math.round(i/2)) == (i/2)) {
            if (addOrDelete.toLowerCase() == 'add') {
                document.getElementById(currDivs[i]).style.backgroundColor = '#F7F7F7';
            } else {
                document.getElementById(currDivs[i]).style.backgroundColor = '#FFFFFF';
            }
        } else {
            if (addOrDelete.toLowerCase() == 'add') {
                document.getElementById(currDivs[i]).style.backgroundColor = '#FFFFFF';
            } else {
                document.getElementById(currDivs[i]).style.backgroundColor = '#F7F7F7';
            }
        }
    }
    
    //add new div first
    if (addOrDelete.toLowerCase() == 'add') {
        //while (innerContent.indexOf('&#39;') > -1) {innerContent = innerContent.replace('&#39;','&rsquo;');}
        var d = document.getElementById(outerDivId);
        d.appendChild(newdiv);
        newdiv.innerHTML = innerContent;
    }
    
    //add sorted rows back into the grids
    for (var i = 0; i < currDivs.length; i++) {
        theParentNode.appendChild(document.getElementById(currDivs[i]));
    }
}

//------------------------------------------------//
//       End Add/Remove Pick List Items           //
//------------------------------------------------//

//------------------------------------------------//
//     Start Confirmation/Error Message Box       //
//------------------------------------------------//
var errorArray = new Array;
errorArray[1] = "The item has been added.";
errorArray[2] = "The item has been updated.";
errorArray[3] = "The item has been deleted.";
errorArray[4] = "An item with the same name already exists in the database.";
errorArray[5] = "An internal error occurred. Please contact MSDSonline regarding this problem.";
errorArray[6] = "The item has been removed from current.";
errorArray[7] = "The item has been added to current.";
errorArray[8] = "The item has been hidden.";
errorArray[9] = "The item already exists.";
errorArray[10] = "The item can not be blank.";
errorArray[11] = "Your changes have been saved.";
errorArray[12] = "The selected MSDS(s) have been added to your eBinder";
errorArray[13] = "The selected MSDS(s) have been deleted from your Queue";

function updateMessageBox(isError, messageText, errorNumber)
{
    if (errorNumber != ""){
        if (isError) {
    	    document.getElementById("ConfirmationErrorMessageBox").className = "headerMessageBox headerErrorBox ts4";
            document.getElementById("ConfirmationErrorMessageBox").innerHTML = "<img src='../Images/AlertIcon.gif' style='padding: 0px 8px 0px 8px;float:left;' alt='' /><div style='float:left;padding-top:7px;'>" + errorArray[errorNumber] + "</div>";
        } else {
            document.getElementById("ConfirmationErrorMessageBox").className = "headerMessageBox headerConfirmationBox ts4";
            document.getElementById("ConfirmationErrorMessageBox").innerHTML = "<img src='../Images/GreenSavedIcon.gif' style='padding: 3px 8px 0px 8px;float:left;' alt='' /><div style='float:left;padding-top:7px;'>" + errorArray[errorNumber] + "</div>";
        }
    } else {
        if (isError) {
    	    document.getElementById("ConfirmationErrorMessageBox").className = "headerMessageBox headerErrorBox ts4";
            document.getElementById("ConfirmationErrorMessageBox").innerHTML = "<img src='../Images/AlertIcon.gif' style='padding: 0px 8px 0px 8px;float:left;' alt='' /><div style='float:left;padding-top:7px;'>" + messageText + "</div>";
        } else {
            document.getElementById("ConfirmationErrorMessageBox").className = "headerMessageBox headerConfirmationBox ts4";
            document.getElementById("ConfirmationErrorMessageBox").innerHTML = "<img src='../Images/GreenSavedIcon.gif' style='padding: 3px 8px 0px 8px;float:left;' alt='' /><div style='float:left;padding-top:7px;'>" + messageText + "</div>";
        }
    }
    scroll(0,0);
    setTimeout('removeMessageBox()', 5000)
}

function removeMessageBox()
{
    document.getElementById("ConfirmationErrorMessageBox").className = "headerMessageBox";
    document.getElementById("ConfirmationErrorMessageBox").innerHTML = "";
}
//------------------------------------------------//
//       End Confirmation/Error Message Box       //
//------------------------------------------------//

//------------------------------------------------//
//         Hazards Pick List Web Method Calls     //
//------------------------------------------------//
function getRootElement(comet) { //comet.responseXML doesn't work in the embeded GM pages
    var rootElement=null;
    try {
        rootElement = comet.responseXML.documentElement;
    } catch(e) {
        try {
        
        
        var text = comet.responseText;
        var parser = new DOMParser();
        try {
            if (text != undefined && text != "")
                var parsed = parser.parseFromString(text, "text/xml");
        } catch (e) {}
        if (parsed)
            rootElement = parsed.documentElement;
        } catch (e2) {
        
        
        }
    }
    return rootElement;
}

function getRootElementInformation(comet) { //comet.responseXML doesn't work in the embeded GM pages
    var returnInformation;
    try {
    var rootElement = getRootElement(comet);
    } catch (e) {
    
    }
    if (rootElement != null)
    try {
        if (browserName == 'IE'){
            returnInformation = rootElement.text;
        }else if (browserName == 'Safari'){
            returnInformation = rootElement.childNodes[0].nodeValue;
        }else{
            returnInformation = rootElement.textContent;
        }
    } catch(e) {
    
    }
    return returnInformation;
}


function addUserDocumentHazard(id, gridName, outerDiv, rowText, addWebMethod, addIdTitle, removeWebMethod, removeIdTitle,checkHQCallValue,sessionId){
    callingGrid = gridName;
    rowContainerDiv = outerDiv;
    removeItemId = id;
    itemName = rowText;    
    addWebMethodCall = addWebMethod;
    addWebMethodVariable = addIdTitle;
    removeWebMethodCall = removeWebMethod;
    removeWebMethodVariable = removeIdTitle;
    checkHQCall = checkHQCallValue

    if(hQCall){
        var productType = 2
    }else{
        var productType = 1
    } 
    
    var projectPathVariable = projectPath()
    var shortProjectPath = projectPathVariable.split("/")
    var fullProjectPath = cometBaseUrl + '/' + addWebMethod;
    
    sendCometRequest('processHazardCurrentPickListAdd',shortProjectPath[2],fullProjectPath,'CustomerAdministratorId,' + customerAdministratorId + ';CustomerUserId,' + customerUserId + ';' + addIdTitle + ',' + id + ';UserDocumentId,' + ebinderUserDocumentID + ';SessionId,' + sessionId + ';ProductType,' + productType);
}

function deleteUserDocumentHazard(id, gridName, outerDiv, rowText, removeWebMethod, removeIdTitle, addWebMethod, addIdTitle){
    callingGrid = gridName;
    rowContainerDiv = outerDiv;
    removeItemId = id;
    itemName = rowText;  
    //itemName = convertCharacters(itemName);
    addWebMethodCall = addWebMethod;
    addWebMethodVariable = addIdTitle;
    removeWebMethodCall = removeWebMethod;
    removeWebMethodVariable = removeIdTitle;  
    
    var projectPathVariable = projectPath()
    var shortProjectPath = projectPathVariable.split("/")
    var fullProjectPath = cometBaseUrl + '/' + removeWebMethod;
    sendCometRequest('processHazardCurrentPickListDelete',shortProjectPath[2],fullProjectPath,'CustomerAdministratorId,' + customerAdministratorId + ';' + removeIdTitle + ',' + id);
}

function addEditHazardsFunction(textboxId, addEditFlag, outerDiv, id, gridName, webMethod, textVariable, idVariable, defaultText, addWebMethod, addIdTitle, removeWebMethod, removeIdTitle) {
    //set global variables for processing function
    callingGrid = gridName;
    rowContainerDiv = outerDiv;
    AddEditFlagValue = addEditFlag;
    itemName = document.getElementById(textboxId).value;
    //itemName = convertCharacters(itemName);
    addNewTextBoxId = textboxId
    defaultAddNewText = defaultText;
    addWebMethodCall = addWebMethod;
    addWebMethodVariable = addIdTitle;
    removeWebMethodCall = removeWebMethod;
    removeWebMethodVariable = removeIdTitle; 
    
    if(hQCall){
        var productType = 2
    }else{
        var productType = 1
    } 
    
    //set local variables
    TextboxValue = document.getElementById(textboxId).value;
    XmlDiv = outerDiv;
    
    var projectPathVariable = projectPath()
    var shortProjectPath = projectPathVariable.split("/")
    var fullProjectPath = cometBaseUrl + '/' + webMethod;
    
    if(addEditFlag == 0) {
        if (document.getElementById(textboxId).value != defaultText) {
            if (document.getElementById(outerDiv + 'Available').lastChild) {
                NextToLastChild = document.getElementById(outerDiv + 'Available').lastChild.previousSibling;
            }
            id = 0;
            itemName = convertCharactersForDatabase(itemName);
            sendCometRequest('processNewHazard',shortProjectPath[2],fullProjectPath,'CustomerAdministratorId,'+customerAdministratorId+';'+'CustomerUserId,'+customerUserId+';'+textVariable+','+itemName+';'+idVariable+','+id+';AddEditFlag,0'+';SessionId,'+sessionId+';ProductType,'+productType);
        }
    } else {
        if (document.getElementById(textboxId).value != defaultText) {
            if (document.getElementById(outerDiv + 'Available').lastChild) {
                NextToLastChild = document.getElementById(outerDiv + 'Available').lastChild.previousSibling;
            }
            itemName = convertCharactersForDatabase(itemName);
            sendCometRequest('processEditHazard',shortProjectPath[2],fullProjectPath,'CustomerAdministratorId,'+customerAdministratorId+';'+'CustomerUserId,'+customerUserId+';'+textVariable+','+itemName+';'+idVariable+','+id+';AddEditFlag,1'+';SessionId,'+sessionId+';ProductType,'+productType);
        }
    }
}

function deleteHazardsFunction(id, outerDiv, rowId, webMethod, idVariable) {
    rowContainerDiv = outerDiv;
    deleteRow = rowId;
    removeItemId = id;
           
    if (webMethod.indexOf('UserDocument') >= 0) {
        alert('Please remove the item from your Current picklist before deleting.');   
    } else {
        var projectPathVariable = projectPath()
        var shortProjectPath = projectPathVariable.split("/")
        var fullProjectPath = cometBaseUrl + '/' + webMethod;
        
        sendCometRequest('processDeleteHazards',shortProjectPath[2],fullProjectPath,'CustomerAdministratorId,'+customerAdministratorId+';' + idVariable + ',' + id);
    }
}

//------------------------------------------------//
//      Add/Remove Hazard Pick List Items         //
//------------------------------------------------//

function processHazardCurrentPickListAdd(){
     if (comet.readyState == 4) {
        if (comet.status == 200) {
            var returnId = getRootElementInformation(comet);
            
            itemName = convertSpecialCharacters(itemName);
            
            if (callingGrid == 'DOTHazards' || callingGrid == 'SafetyPhrases' || callingGrid == 'RiskPhrases') {
                displayOrder = document.getElementById(removeItemId + 'DisplayOrder').value;
            }
            
           if ( addWebMethodCall == null) {
                addWebMethodCall = 'AddUserDocument' + gridName;
            }
            if ( addWebMethodVariable == null) {
                addWebMethodVariable = 'User' + callingGrid + 'Id';
            }
            if ( removeWebMethodCall == null) {
                removeWebMethodCall = 'DeleteUserDocument' + gridName;
            }
            if ( removeWebMethodVariable == null) {
                removeWebMethodVariable = 'UserDocument' + callingGrid + 'Id';
            }
            
            addToCurrent(callingGrid, rowContainerDiv, returnId, itemName, removeItemId, addWebMethodCall, addWebMethodVariable, removeWebMethodCall, removeWebMethodVariable)
            //Update the "Last Date Changed" value
            updateLastDateChangedToToday();
        }
    }
}

function processHazardCurrentPickListDelete(){
     if (comet.readyState == 4) {
        if (comet.status == 200) {
            var returnId = getRootElementInformation(comet);
           
            itemName = convertSpecialCharacters(itemName);
            itemName = reverseConvertCharacters(itemName);
            
            if (callingGrid == 'DOTHazards' || callingGrid == 'SafetyPhrases' || callingGrid == 'RiskPhrases') {
                displayOrder = document.getElementById(removeItemId + 'DisplayOrder').value;
            }
            removeFromCurrent(callingGrid, rowContainerDiv, returnId, itemName, removeItemId, addWebMethodCall, addWebMethodVariable, removeWebMethodCall, removeWebMethodVariable)
        }
    }
}

function processNewHazard(){
    if (comet.readyState == 4) {
        if (comet.status == 200) {
            var returnId = getRootElementInformation(comet);
            
            if (returnId > 0){
                var d = document.getElementById(rowContainerDiv + 'Available');
                var newdiv = document.createElement('div');
                newdiv.className = 'ts5 hazardRow';
                newdiv.id = callingGrid + returnId + 'Plus';
                
                itemName = convertSpecialCharacters(itemName);
                itemName = reverseConvertCharacters(itemName);
                displayItemName = itemName;
                while (itemName.indexOf('&rsquo;') > -1) {itemName = itemName.replace('&rsquo;','&amp;rsquo;');}
                
                newdiv.innerHTML = '<div id="' + callingGrid + 'Draggable' + returnId + '" class="draggable"><div id="' + callingGrid + returnId + 'MainRow"><img src="../Images/PlusIcon.gif" class="hazardsPlusImage" alt="" onclick="javascript:lockPickListImage(this);addUserDocumentHazard(\'' + returnId + '\',\'' + callingGrid + '\',\'' + rowContainerDiv + '\',\'' + itemName + '\',\'' + addWebMethodCall + '\',\'' + addWebMethodVariable + '\',\'' + removeWebMethodCall + '\',\'' + removeWebMethodVariable + '\',\'\',sessionId);" /><div class="pickListGrayContainer"><a class="ls4 availableEditLink" id="' + callingGrid + returnId + 'EditLink" href="javascript: showHideSlideDown(\'Edit' + callingGrid + returnId + 'SlideDownDiv\',\'' + callingGrid + returnId + 'EditLink\',\'\');populateEditDeleteDivs(edit' + callingGrid + 'InnerHtml,\'Edit\',\'' + returnId + '\',\'' + itemName + '\',\'Edit' + callingGrid + returnId + 'SlideDownDiv\');">Edit</a><div class="ts5 availableElement" id="' + newdiv.id + 'Text">' + displayItemName + '</div></div></div><div class="editSlideDownDiv" id="Edit' + callingGrid + returnId + 'SlideDownDiv"></div></div>';
                d.appendChild(newdiv);
                
                showHideSlideDown('AddNew' + callingGrid + 'SlideDownDiv');
                sortHazardDivs(rowContainerDiv + 'Available');
                document.getElementById(addNewTextBoxId).value = defaultAddNewText;
                
            }
        }
    }
}

function processEditHazard(){
    if (comet.readyState == 4) {
        if (comet.status == 200) {
            var returnId = getRootElementInformation(comet);
            
            if (returnId > 0){
                textboxId = callingGrid + returnId + 'TextBox';
                textboxValue = document.getElementById(textboxId).value;
                
                var currentContainer = document.getElementById(rowContainerDiv + "Current");
                var documentId;
                if (getElementsByAttribute(clean(currentContainer), "div","userid",returnId).length > 0) {
                    documentId = getElementsByAttribute(clean(currentContainer), "div","userid",returnId)[0].id;
                }
                
                availableTextRowId = callingGrid + returnId + 'PlusText';
                currentTextRowId = documentId + 'Text';
                grayedTextRowId = callingGrid + returnId + 'GrayedText';
                                
                textboxValue = convertSpecialCharacters(textboxValue);
                textboxValue = reverseConvertCharacters(textboxValue);
                
                showHideSlideDown('Edit' + callingGrid + returnId + 'SlideDownDiv', '', 'true');
                
                //Rebuild the row with the correct text
                itemName = textboxValue;
                displayItemName = textboxValue;
                while (itemName.indexOf('&rsquo;') > -1) {itemName = itemName.replace('&rsquo;','&amp;rsquo;');}
                var gridName = callingGrid.substring(0,callingGrid.length - 1);
                if ( addWebMethodCall == null) {
                    addWebMethodCall = 'AddUserDocument' + gridName;
                }
                if ( addWebMethodVariable == null) {
                    addWebMethodVariable = 'User' + callingGrid + 'Id';
                }
                if ( removeWebMethodCall == null) {
                    removeWebMethodCall = 'DeleteUserDocument' + gridName;
                }
                if ( removeWebMethodVariable == null) {
                    removeWebMethodVariable = 'UserDocument' + callingGrid + 'Id';
                }
                                
                if (document.getElementById(callingGrid + returnId + 'Plus')) {
                    document.getElementById(callingGrid + returnId + 'Plus').innerHTML = '<div id="' + callingGrid + 'Draggable' + returnId + '" class="draggable"><div id="' + callingGrid + returnId + 'MainRow"><img src="../Images/PlusIcon.gif" class="hazardsPlusImage" alt="" onclick="javascript:lockPickListImage(this);addUserDocumentHazard(\'' + returnId + '\',\'' + callingGrid + '\',\'' + rowContainerDiv + '\',\'' + itemName + '\',\'' + addWebMethodCall + '\',\'' + addWebMethodVariable + '\',\'' + removeWebMethodCall + '\',\'' + removeWebMethodVariable + '\',\'False\');" /><div class="pickListGrayContainer"><a class="ls4 availableEditLink" id="' + callingGrid + returnId + 'EditLink" href="javascript: showHideSlideDown(\'Edit' + callingGrid + returnId + 'SlideDownDiv\',\'' + callingGrid + returnId + 'EditLink\',\'\');populateEditDeleteDivs(edit' + callingGrid + 'InnerHtml,\'Edit\',\'' + returnId + '\',\'' + itemName + '\',\'Edit' + callingGrid + returnId + 'SlideDownDiv\');">Edit</a><div class="ts5 availableElement" id="' + callingGrid + returnId + 'PlusText">' + displayItemName + '</div></div></div></div><div class="editSlideDownDiv" id="Edit' + callingGrid + returnId + 'SlideDownDiv"></div>';
                }
                
                if (document.getElementById(callingGrid + returnId + 'Grayed')) {
                    document.getElementById(callingGrid + returnId + 'Grayed').innerHTML = '<div id="' + callingGrid + 'NonDraggable' + returnId + '"><img src="../Images/Spacer.gif" class="hazardsSpacerImage" alt="" /><div class="pickListGrayContainer"><a class="ls4 availableEditLink" id="' + callingGrid + returnId + 'EditLink" href="javascript: showHideSlideDown(\'Edit' + callingGrid + returnId + 'SlideDownDiv\',\'' + callingGrid + returnId + 'EditLink\',\'\');populateEditDeleteDivs(edit' + callingGrid + 'InnerHtml,\'Edit\',\'' + returnId + '\',\'' + itemName + '\',\'Edit' + callingGrid + returnId + 'SlideDownDiv\');">Edit</a><div class="ts5 availableElementGrayed" id="' + callingGrid + returnId + 'GrayedText">' + displayItemName + '</div></div></div><div class="editSlideDownDiv" id="Edit' + callingGrid + returnId + 'SlideDownDiv"></div></div>';
                }
                
                //update the text in the grayed out row and/or available row
                if(document.getElementById(availableTextRowId)){
                    document.getElementById(availableTextRowId).innerHTML = textboxValue;
                }
                if(document.getElementById(grayedTextRowId)){
                    document.getElementById(grayedTextRowId).innerHTML = textboxValue;
                }
                
                if(document.getElementById(currentTextRowId)){
                    document.getElementById(currentTextRowId).innerHTML = textboxValue;
                }
                
                sortHazardDivs(rowContainerDiv + 'Available');
                
                //check if this is a selected row and update the entry in the current drop down
                if(document.getElementById(currentTextRowId)){
                     eval('document.getElementById(currentTextRowId).parentNode.innerHTML = document.getElementById(currentTextRowId).parentNode.innerHTML.replace(/' + document.getElementById(currentTextRowId).innerHTML + '/,textboxValue);');
                }
                
            }
        }
    }
}

function processDeleteHazards() {
    if (comet.readyState == 4) {
        if (comet.status == 200) {
        try {
        
            try {
                document.getElementById(rowContainerDiv + 'Available').removeChild(document.getElementById(deleteRow));
            } catch (e) {
                document.getElementById(rowContainerDiv + 'Available').removeChild(document.getElementById(deleteRow.replace('Plus','Grayed')));
            }
            try {
                document.getElementById(rowContainerDiv + 'Current').removeChild(document.getElementById(deleteRow));
            } catch (e) {
                document.getElementById(rowContainerDiv + 'Current').removeChild(document.getElementById(deleteRow.replace('Plus','Grayed')));
            }
        } catch (e) {}
        sortHazardDivs(rowContainerDiv + 'Available');
        }
    }
}

//------------------------------------------------//
//    End Add/Remove Hazard Pick List Items       //
//------------------------------------------------//


//------------------------------------------------------------//
//    PDF Summary Information & Information Div functions     //
//------------------------------------------------------------//

function getSearchProductInformation(div,id){ //Used on the MSDSonline Search page
    informationElements[0] = 'ProductName';
    informationElements[1] = 'CompanyName';
    informationElements[2] = 'RevisionDate';
    informationElements[3] = 'Cas';
    informationElements[4] = 'Supplier';
    informationElements[5] = 'Synonyms';
    informationElements[6] = 'ProductCode';
    informationElements[7] = 'Language';
    informationElements[8] = 'LastVerified';
    informationElements[9] = 'VerifiedDateDisplayType';
    
    divInformationElements[0] = 'ProductNamePopup';
    divInformationElements[1] = 'CompanyNamePopup';
    divInformationElements[2] = 'RevisionDatePopup';
    divInformationElements[3] = 'CasPopup';
    divInformationElements[4] = 'SupplierPopup';
    divInformationElements[5] = 'SynonymsPopup';
    divInformationElements[6] = 'ProductCodePopup';
    divInformationElements[7] = 'LanguagePopup';
    divInformationElements[8] = 'LastVerifiedPopup';
    divInformationElements[9] = 'LastVerifiedPopup';
    
    clearHTMLElements(divInformationElements);
    searchSpecial = true;

    var projectPathVariable = projectPath()
    var shortProjectPath = projectPathVariable.split("/")
    var fullProjectPath = cometBaseUrl + '/GetMSDSOnlineDocumentExtendedDetails';

    sendCometRequest('processSearchProductInformation',shortProjectPath[2],fullProjectPath,'MSDSOnlineDocumentId,' + id);
    getShowProductMouseOver(div,id);
}

function getEbinderProductInformation(div,id,CustomerAdministratorId,isApprovalManagerPage){ //Used on the inventory pages and approval manager
    informationElements.length = 0;
    divInformationElements.length = 0;

    informationElements[0] = 'ProductName';
    informationElements[1] = 'ManufacturerName';
    informationElements[2] = 'SupplierDistributorName';
    informationElements[3] = 'SupplierCode';
    informationElements[4] = 'Custom1';
    informationElements[5] = 'Custom2';
    informationElements[6] = 'RevisionDate';
    informationElements[7] = 'UNNA';
    informationElements[8] = 'Cas';
    informationElements[9] = 'UserDocumentID';
    informationElements[10] = 'Status';
    informationElements[11] = 'PrivateOrPublic';
    informationElements[12] = 'Approval';
    informationElements[13] = 'ApprovedBy';
    informationElements[14] = 'DateCreated';
    informationElements[15] = 'AddedBy';
    informationElements[16] = 'LastChanged';
    informationElements[17] = 'LastVerified';
    informationElements[18] = 'ApprovalDate';
    informationElements[19] = 'AddedToQueueBy';
    informationElements[20] = 'LanguageDescription';
    informationElements[21] = 'LastChangedBy';
    informationElements[22] = 'DateAddedToQueue';
    informationElements[23] = 'AddedToQueueLocation'; //DB isn't passing this back yet
    informationElements[24] = 'VerifiedDateDisplayType'; 
    if (isApprovalManagerPage) {informationElements[25] = 'DocumentAddReason';}
    
    divInformationElements[0] = 'ProductNamePopup';
    divInformationElements[1] = 'ManufacturerNamePopup';
    divInformationElements[2] = 'SupplierDistributorNamePopup';
    divInformationElements[3] = 'SupplierCodePopup';
    divInformationElements[4] = 'Custom1Popup';
    divInformationElements[5] = 'Custom2Popup';
    divInformationElements[6] = 'RevisionDatePopup';
    divInformationElements[7] = 'UNNAPopup';
    divInformationElements[8] = 'CasPopup';
    divInformationElements[9] = 'UserDocumentIDPopup';
    divInformationElements[10] = 'StatusPopup';
    divInformationElements[11] = 'PrivateOrPublicPopup';
    divInformationElements[12] = 'ApprovalPopup';
    divInformationElements[13] = 'ApprovedByPopup';
    divInformationElements[14] = 'DateCreatedPopup';
    divInformationElements[15] = 'AddedByPopup';
    divInformationElements[16] = 'LastChangedPopup';
    divInformationElements[17] = 'LastVerifiedPopup';
    divInformationElements[18] = 'ApprovalDatePopup';
    divInformationElements[19] = 'AddedToQueueByPopup';
    divInformationElements[20] = 'LanguageDescriptionPopup';
    divInformationElements[21] = 'LastChangedByPopup';
    divInformationElements[22] = 'AddedToQueueDatePopup';
    divInformationElements[23] = 'AddedToQueueLocationPopup'; //DB isn't passing this back yet
    divInformationElements[24] = 'VerifiedDateDisplayType'; 
    if (isApprovalManagerPage) {divInformationElements[25] = 'DocumentAddReasonPopup';}
    
    clearHTMLElements(divInformationElements);
    searchSpecial = true;

    //Insert NA when the output includes commas so that there's still fill if there's no data
    document.getElementById(divInformationElements[12]).innerHTML = 'N/A'; //ApprovalPopup
    document.getElementById(divInformationElements[13]).innerHTML = 'N/A'; //ApprovedByPopup
    document.getElementById(divInformationElements[18]).innerHTML = 'N/A'; //DateLastReviewedPopup
    document.getElementById(divInformationElements[16]).innerHTML = 'N/A'; //LastChangedPopup
    document.getElementById(divInformationElements[21]).innerHTML = 'N/A'; //LastChangedByPopup
    document.getElementById(divInformationElements[19]).innerHTML = 'N/A'; //AddedToQueueByPopup
    document.getElementById(divInformationElements[22]).innerHTML = 'N/A'; //AddedToQueueDatePopup
    document.getElementById(divInformationElements[23]).innerHTML = 'N/A'; //AddedToQueueLocationPopup
    
    var projectPathVariable = projectPath()
    var shortProjectPath = projectPathVariable.split("/")
    var fullProjectPath = cometBaseUrl + '/GetEbinderDocumentExtendedDetails';
    
    sendCometRequest('processSearchProductInformation',shortProjectPath[2],fullProjectPath,'UserDocumentId,' + id + ';CustomerAdministratorId,' + CustomerAdministratorId);
    getShowProductMouseOver(div,id);
}

function getQueueProductInformation(div,id,MsdsDocumentId,SourceId){
    informationElements[0] = 'ProductName';
    informationElements[1] = 'UserCreatedName';
    informationElements[2] = 'PrivateOrPublic';
    informationElements[3] = 'ApprovalType';
    informationElements[4] = 'RevisionDate';
    informationElements[5] = 'CompanyName';
    informationElements[6] = 'Supplier';
    informationElements[7] = 'ProductCode';
    informationElements[8] = 'Custom1';
    informationElements[9] = 'Custom2';
    informationElements[10] = 'Cas';
    informationElements[11] = 'Language';
    informationElements[12] = 'LastVerified';
    informationElements[13] = 'AddedToQueueDate';
    informationElements[14] = 'AddedToQueueBy';
    informationElements[15] = 'AddedToQueueLocation';
    informationElements[16] = 'DocumentAddReason';
    informationElements[17] = 'Synonyms';

    clearHTMLElements(informationElements);
    
    document.getElementById(informationElements[2]).innerHTML = 'N/A'; //Private
    document.getElementById(informationElements[13]).innerHTML = 'N/A'; //DateCreated
    document.getElementById(informationElements[14]).innerHTML = 'N/A'; //AddedBy
    document.getElementById(informationElements[15]).innerHTML = 'N/A'; //Location
    
    document.getElementById('UserCreatedNameText').innerHTML = "";
    document.getElementById('UserCreatedName').style.display = "none";
    document.getElementById('Custom1Row').style.display = "none";
    document.getElementById('Custom2Row').style.display = "none";
    document.getElementById('SynonymsRow').style.display = "none";
    document.getElementById('PrivateRow').style.display = "none";
    document.getElementById('ReasonAddedRow').style.display = "none";
        
    if(SourceId == 4) { //Employee Added
        document.getElementById('SynonymsRow').style.display = "inline";
        document.getElementById('ReasonAddedRow').style.display = "inline";
    } else if (SourceId == 1) { //AUTO Update
        document.getElementById('SynonymsRow').style.display = "inline";
    } else if (SourceId == 2) { //2 = Request
        document.getElementById('UserCreatedNameText').innerHTML = "Requested Name";
        document.getElementById('UserCreatedName').style.display = "inline";
        document.getElementById('Custom1Row').style.display = "inline";
        document.getElementById('Custom2Row').style.display = "inline";
    } else if (SourceId == 3) { //3 = Local Upload
        document.getElementById('UserCreatedNameText').innerHTML = "Uploaded Name";
        document.getElementById('UserCreatedName').style.display = "inline";
        document.getElementById('Custom1Row').style.display = "inline";
        document.getElementById('Custom2Row').style.display = "inline";
        document.getElementById('PrivateRow').style.display = "inline";
   }

    if (MsdsDocumentId == '') { MsdsDocumentId = 0; }
    
    var projectPathVariable = projectPath()
    var shortProjectPath = projectPathVariable.split("/")
    var fullProjectPath = cometBaseUrl + '/GetMSDSOnlineQueueExtendedDetails';

    sendCometRequest('processSearchProductInformation',shortProjectPath[2],fullProjectPath,'MSDSOnlineDocumentId,' + MsdsDocumentId + ';UserDocumentQueueId,' + id);
    getShowProductMouseOver(div,id);
}

function processSearchProductInformation(){
    if (comet.readyState == 4) {
        if (comet.status == 200) {
            var rootElement = getRootElement(comet);
            
            if (document.getElementById("QueueByRow") != null) {
                document.getElementById("QueueByRow").style.display = "none";
            }
                
            var i;
            var currentXML;
            var currentHTML;
            var nextElement = false;
            var LastVerifiedValue;
            for (i in informationElements){
                nextElement = false;
                
                if (informationElements[i] == 'AddedBy') {
                    if (rootElement.getElementsByTagName('AddedByIDText')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('AddedByIDText');
                    } else if (rootElement.getElementsByTagName('AddedBy')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('AddedBy');
                    } else {
                        nextElement = true;
                    }
                } else if (informationElements[i] == 'AddedToQueueBy') {
                    if (rootElement.getElementsByTagName('AddedToQueueByIDText')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('AddedToQueueByIDText')
                    } else if (rootElement.getElementsByTagName('AddedToQueueBy')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('AddedToQueueBy')
                    } else if (rootElement.getElementsByTagName('AddedByIDText')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('AddedByIDText');
                    } else {
                        nextElement = true;
                    }
                } else if (informationElements[i] == 'AddedToQueueDate') {
                    if (rootElement.getElementsByTagName('DateAddedToQueue')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('DateAddedToQueue');
                    } else if (rootElement.getElementsByTagName('AddedToQueueDate')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('AddedToQueueDate');
                    } else {
                        nextElement = true;
                    }
                } else {
                    currentXML = rootElement.getElementsByTagName(informationElements[i]);
                }
                
                if (!nextElement) {
                    if (currentXML.length > 0){
                        if (searchSpecial) {
                            currentHTML = document.getElementById(divInformationElements[i]);    
                        } else {
                            currentHTML = document.getElementById(informationElements[i]);    
                        }
                        if (browserName == 'IE'){
                            if (informationElements[i] == 'AddedToQueueDate' || informationElements[i] == 'DateAddedToQueue' || pdfInformationElements[i] == 'PdfRevisionDate' || informationElements[i] == 'RevisionDate' || informationElements[i] == 'DateLastReviewed' || informationElements[i] == 'ApprovalDate' || informationElements[i] == 'DateUpdated' || informationElements[i] == 'DateCreated' || informationElements[i] == 'LastVerified' || informationElements[i] == 'LastChanged') {
                                var tempTimeArray1 = "";
                                var tempTimeArray2 = "";
                                tempTimeArray1 = currentXML[0].text.split("T");
                                tempTimeArray2 = tempTimeArray1[0].split("-");
                                if (tempTimeArray2[0].toString() != '1955') {
                                    currentHTML.innerHTML = tempTimeArray2[1] + "/" +  tempTimeArray2[2] + "/" + tempTimeArray2[0];
                                     if (informationElements[i] == 'LastVerified'){
                                        LastVerifiedValue = tempTimeArray2[1] + "/" +  tempTimeArray2[2] + "/" + tempTimeArray2[0];
                                    }
                                }
                                if (informationElements[i] == 'AddedToQueueDate' || informationElements[i] == 'DateAddedToQueue') {
                                    document.getElementById("QueueByRow").style.display = "inline";
                                }
                            } else if (informationElements[i] == 'AddedToQueueBy' || informationElements[i] == 'AddedByIDText') {
                                if (informationElements[i] != '') {
                                    currentHTML.innerHTML = currentXML[0].text.toUpperCase();
                                    document.getElementById("QueueByRow").style.display = "inline";
                                }
                            } else if (informationElements[i] == 'PrivateOrPublic' || pdfInformationElements[i] == 'PdfPrivateOrPublic') {
                                //0=Private (Yes), 1=Public (No) --> Via Marcus
                                if (currentXML[0].text.toUpperCase() == 'TRUE') {
                                    currentHTML.innerHTML = 'No';
                                } else if (currentXML[0].text.toUpperCase() == 'FALSE') {
                                    currentHTML.innerHTML = 'Yes';
                                }
                            } else if (informationElements[i] == 'Status') {
                                if (currentXML[0].text.toUpperCase() == 'A') {
                                    currentHTML.innerHTML = 'No';
                                } else if(currentXML[0].text.toUpperCase() == 'R') {
                                    currentHTML.innerHTML = 'Yes';
                                }
                            } else {
                                if (informationElements[i] == 'AddedToQueueLocation' && currentXML[0].text == '') {
                                    currentHTML.innerHTML = 'N/A';
                                } else {
                                    currentHTML.innerHTML = currentXML[0].text.toUpperCase();
                                }
                            }
                            if (informationElements[i] == 'VerifiedDateDisplayType') {
                                switch (currentXML[0].text){
                                    case '0':
                                        if (LastVerifiedValue == "") LastVerifiedValue = "N/A";
                                        document.getElementById("LastVerifiedPopup").innerHTML = LastVerifiedValue;
                                        break;
                                    case '1':
                                        document.getElementById("LastVerifiedPopup").innerHTML = 'N/A';
                                        break;
                                    case '2':
                                        document.getElementById("LastVerifiedPopup").innerHTML = 'VERSION';
                                        break;
                                    default:
                                        //do nothing
                                        break;
                                }
                            }
                            if (informationElements[i] == 'ProductName'){
                                if (currentXML[0].text.length > 44) {
                                    if (document.getElementById("ProductNamePopup") != null){
                                        document.getElementById("ProductNamePopup").innerHTML = currentXML[0].text.substring(0,41) + '...';
                                    }else{
                                        document.getElementById("ProductName").innerHTML = currentXML[0].text.substring(0,41) + '...';
                                    }
                                }
                            }

                        }else if (browserName == 'Safari'){
                            if (informationElements[i] == 'AddedToQueueDate' || informationElements[i] == 'DateAddedToQueue' || pdfInformationElements[i] == 'PdfRevisionDate' || informationElements[i] == 'RevisionDate' || informationElements[i] == 'DateLastReviewed' || informationElements[i] == 'ApprovalDate' || informationElements[i] == 'DateUpdated' || informationElements[i] == 'DateCreated' || informationElements[i] == 'LastVerified' || informationElements[i] == 'LastChanged') {
                                var tempTimeArray1 = "";
                                var tempTimeArray2 = "";
                                tempTimeArray1 = currentXML[0].childNodes[0].nodeValue.split("T");
                                tempTimeArray2 = tempTimeArray1[0].split("-");
                                if (tempTimeArray2[0].toString() != '1955') {
                                    currentHTML.innerHTML = tempTimeArray2[1] + "/" +  tempTimeArray2[2] + "/" + tempTimeArray2[0];
                                    if (informationElements[i] == 'LastVerified'){
                                        LastVerifiedValue = tempTimeArray2[1] + "/" +  tempTimeArray2[2] + "/" + tempTimeArray2[0];
                                    }
                                }
                                if (informationElements[i] == 'AddedToQueueDate' || informationElements[i] == 'DateAddedToQueue') {
                                    document.getElementById("QueueByRow").style.display = "inline";
                                }
                            } else if (informationElements[i] == 'AddedToQueueBy' || informationElements[i] == 'AddedByIDText') {
                                if (informationElements[i] != '') {
                                    currentHTML.innerHTML = currentXML[0].childNodes[0].nodeValue.toUpperCase();
                                }
                            } else if (informationElements[i] == 'PrivateOrPublic' || pdfInformationElements[i] == 'PdfPrivateOrPublic') {
                                //0=Private (Yes), 1=Public (No) --> Via Marcus
                                if (currentXML[0].childNodes[0].nodeValue.toUpperCase() == 'TRUE') {
                                    currentHTML.innerHTML = 'No';
                                } else if (currentXML[0].childNodes[0].nodeValue.toUpperCase() == 'FALSE') {
                                    currentHTML.innerHTML = 'Yes';
                                }
                            } else if (informationElements[i] == 'Status') {
                                if (currentXML[0].childNodes[0].nodeValue.toUpperCase() == 'A') {
                                    currentHTML.innerHTML = 'No';
                                } else if(currentXML[0].childNodes[0].nodeValue.toUpperCase() == 'R') {
                                    currentHTML.innerHTML = 'Yes';
                                }
                            } else {
                                if (informationElements[i] == 'AddedToQueueLocation' && currentXML[0].childNodes[0].nodeValue == '') {
                                    currentHTML.innerHTML = 'N/A';
                                } else {
                                    currentHTML.innerHTML = currentXML[0].childNodes[0].nodeValue.toUpperCase();
                                }
                            }
                            if (informationElements[i] == 'VerifiedDateDisplayType') {
                                switch (currentXML[0].childNodes[0].nodeValue){
                                    case '0':
                                        if (LastVerifiedValue == "" ) LastVerifiedValue = "N/A";
                                        document.getElementById("LastVerifiedPopup").innerHTML = LastVerifiedValue;
                                        break;
                                    case '1':
                                        document.getElementById("LastVerifiedPopup").innerHTML = 'N/A';
                                        break;
                                    case '2':
                                        document.getElementById("LastVerifiedPopup").innerHTML = 'VERSION';
                                        break;
                                    default:
                                        //do nothing
                                        break;
                                }
                            }
                            if (informationElements[i] == 'ProductName'){
                                if (currentXML[0].childNodes[0].nodeValue.length > 44) {
                                    if (document.getElementById("ProductNamePopup") != null){
                                        document.getElementById("ProductNamePopup").innerHTML = currentXML[0].childNodes[0].nodeValue.substring(0,41) + '...';
                                    }else{
                                        document.getElementById("ProductName").innerHTML = currentXML[0].childNodes[0].nodeValue.substring(0,41) + '...';
                                    }
                                }
                            }
                        }else{
                            if (informationElements[i] == 'AddedToQueueDate' || informationElements[i] == 'DateAddedToQueue' || pdfInformationElements[i] == 'PdfRevisionDate' || informationElements[i] == 'RevisionDate' || informationElements[i] == 'DateLastReviewed' || informationElements[i] == 'ApprovalDate' || informationElements[i] == 'DateUpdated' || informationElements[i] == 'DateCreated' || informationElements[i] == 'LastVerified' || informationElements[i] == 'LastChanged') {
                                var tempTimeArray1 = "";
                                var tempTimeArray2 = "";
                                tempTimeArray1 = currentXML[0].textContent.split("T");
                                tempTimeArray2 = tempTimeArray1[0].split("-");
                                if (tempTimeArray2[0].toString() != '1955') {
                                    currentHTML.innerHTML = tempTimeArray2[1] + "/" +  tempTimeArray2[2] + "/" + tempTimeArray2[0];
                                    if (informationElements[i] == 'LastVerified'){
                                        LastVerifiedValue = tempTimeArray2[1] + "/" +  tempTimeArray2[2] + "/" + tempTimeArray2[0];
                                    }
                                }
                                if (informationElements[i] == 'AddedToQueueDate' || informationElements[i] == 'DateAddedToQueue') {
                                    document.getElementById("QueueByRow").style.display = "inline";
                                }
                            } else if (informationElements[i] == 'AddedToQueueBy' || informationElements[i] == 'AddedByIDText') {
                                if (informationElements[i] != '') {
                                    currentHTML.innerHTML = currentXML[0].textContent.toUpperCase();
                                }
                            } else if (informationElements[i] == 'PrivateOrPublic' || pdfInformationElements[i] == 'PdfPrivateOrPublic') {
                                //0=Private (Yes), 1=Public (No) --> Via Marcus
                                if (currentXML[0].textContent.toUpperCase() == 'TRUE') {
                                    currentHTML.innerHTML = 'No';
                                } else if (currentXML[0].textContent.toUpperCase() == 'FALSE') {
                                    currentHTML.innerHTML = 'Yes';
                                }
                            } else if (informationElements[i] == 'Status') {
                                if (currentXML[0].textContent.toUpperCase() == 'A') {
                                    currentHTML.innerHTML = 'No';
                                } else if(currentXML[0].textContent.toUpperCase() == 'R') {
                                    currentHTML.innerHTML = 'Yes';
                                }
                            } else {
                                if (informationElements[i] == 'AddedToQueueLocation' && currentXML[0].textContent == '') {
                                    currentHTML.innerHTML = 'N/A';
                                } else {
                                    currentHTML.innerHTML = currentXML[0].textContent.toUpperCase();
                                }
                            }
                            if (informationElements[i] == 'VerifiedDateDisplayType') {
                                switch (currentXML[0].textContent){
                                    case '0':
                                        if (LastVerifiedValue == "") LastVerifiedValue = "N/A";
                                        document.getElementById("LastVerifiedPopup").innerHTML = LastVerifiedValue;
                                        break;
                                    case '1':
                                        document.getElementById("LastVerifiedPopup").innerHTML = 'N/A';
                                        break;
                                    case '2':
                                        document.getElementById("LastVerifiedPopup").innerHTML = 'VERSION';
                                        break;
                                    default:
                                        //do nothing
                                        break;
                                }
                            }
                            if (informationElements[i] == 'ProductName'){
                                if (currentXML[0].textContent.length > 44) {
                                    if (document.getElementById("ProductNamePopup") != null){
                                        document.getElementById("ProductNamePopup").innerHTML = currentXML[0].textContent.substring(0,41) + '...';
                                    }else{
                                        document.getElementById("ProductName").innerHTML = currentXML[0].textContent.substring(0,41) + '...';
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else {
            updateMessageBox(true,'',5);
        }
    }
}

function getEbinderSearchProductInformation(div,id){ //Ebinder default page
    informationElements[0] = 'ProductName';
    informationElements[1] = 'ManufacturerName';
    informationElements[2] = 'SupplierDistributorName';
    informationElements[3] = 'SupplierCode';
    informationElements[4] = 'Custom1';
    informationElements[5] = 'Custom2';
    informationElements[6] = 'RevisionDate';
    informationElements[7] = 'UNNA';
    informationElements[8] = 'Cas';
    informationElements[9] = 'UserDocumentID';
    informationElements[10] = 'Status';
    informationElements[11] = 'PrivateOrPublic';
    informationElements[12] = 'Approval';
    informationElements[13] = 'ApprovedBy';
    informationElements[14] = 'DateCreated';
    informationElements[15] = 'AddedBy';
    informationElements[16] = 'LastChanged';
    informationElements[17] = 'LastChangedBy';
    informationElements[18] = 'LastVerified';
    informationElements[19] = 'ApprovalDate'; //DateLastReviewed
    informationElements[20] = 'AddedToQueueBy';
    informationElements[21] = 'AddedToQueueDate';
    informationElements[22] = 'AddedToQueueLocation';
    informationElements[23] = 'LanguageDescription';
    informationElements[24] = 'VerifiedDateDisplayType';
    
    clearHTMLElements(informationElements);

    //Insert NA when the output includes commas so that there's still fill if there's no data
    document.getElementById(informationElements[12]).innerHTML = 'N/A'; //Approval
    document.getElementById(informationElements[13]).innerHTML = 'N/A'; //ApprovedBy
    document.getElementById(informationElements[19]).innerHTML = 'N/A'; //DateLastReviewed
    document.getElementById(informationElements[16]).innerHTML = 'N/A'; //LastChanged
    document.getElementById(informationElements[17]).innerHTML = 'N/A'; //LastChangedBy
    document.getElementById(informationElements[20]).innerHTML = 'N/A'; //AddedToQueueBy
    document.getElementById(informationElements[21]).innerHTML = 'N/A'; //AddedToQueueDate
    document.getElementById(informationElements[22]).innerHTML = 'N/A'; //AddedToQueueLocation
    
    var projectPathVariable = projectPath()
    var shortProjectPath = projectPathVariable.split("/")
    var fullProjectPath = cometBaseUrl + '/GetMSDSOnlineEbinderExtendedDetails';
    
    sendCometRequest('processEbinderProductInformation',shortProjectPath[2],fullProjectPath,'UserDocumentId,' + id + ';CustomerAdministratorId,' + customerAdministratorId);
    getShowProductMouseOver(div,id);
}

function processEbinderProductInformation(){
    if (comet.readyState == 4) {
        if (comet.status == 200) {
            var rootElement = getRootElement(comet);
            
            if (document.getElementById("QueueByRow") != null) {
                document.getElementById("QueueByRow").style.display = "none";
            }
            var i;
            var currentXML;
            var currentHTML;
            var nextElement = false;
            var LastVerifiedValue;
            for (i in informationElements){
                nextElement = false;
                if (informationElements[i] == 'AddedBy') {
                    if (rootElement.getElementsByTagName('AddedByIDText')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('AddedByIDText');
                    } else if (rootElement.getElementsByTagName('AddedBy')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('AddedBy');
                    } else {
                        nextElement = true;
                    }
                } else if (informationElements[i] == 'AddedToQueueBy') {
                    if (rootElement.getElementsByTagName('AddedToQueueByIDText')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('AddedToQueueByIDText');
                    } else if (rootElement.getElementsByTagName('AddedToQueueBy')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('AddedToQueueBy');
                    } else {
                        nextElement = true;
                    }
                } else if (informationElements[i] == 'AddedToQueueDate') {
                    if (rootElement.getElementsByTagName('DateAddedToQueue')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('DateAddedToQueue');
                    } else if (rootElement.getElementsByTagName('AddedToQueueDate')[0] != null) {
                        currentXML = rootElement.getElementsByTagName('AddedToQueueDate');
                    } else {
                        nextElement = true;
                    }
                } else {
                    currentXML = rootElement.getElementsByTagName(informationElements[i]);
                }
                if (!nextElement) {
                    if (currentXML.length > 0){
                        currentHTML = document.getElementById(informationElements[i]);  
                        if (browserName == 'IE'){
                            if (pdfInformationElements[i] == 'PdfRevisionDate' || pdfInformationElements[i] == 'PdfDateCreated' || pdfInformationElements[i] == 'PdfDateUpdated' || pdfInformationElements[i] == 'PdfDateLastReviewed' || informationElements[i] == 'RevisionDate' || informationElements[i] == 'DateCreated' || informationElements[i] == 'DateUpdated' || informationElements[i] == 'DateLastReviewed' || informationElements[i] == 'ApprovalDate' || informationElements[i] == 'LastChanged' || informationElements[i] == 'LastVerified' || informationElements[i] == 'AddedToQueueDate') {
                                if (informationElements[i] == 'DateLastReviewed' || informationElements[i] == 'ApprovalDate'){
                                    var displayType = rootElement.getElementsByTagName("VerifiedDateDisplayType");
                                    switch (displayType[0].text){
                                        case '0':
                                            currentHTML.innerHTML = 'N/A';
                                            break;
                                        case '1':
                                            currentHTML.innerHTML = 'N/A';
                                            break;
                                        case '2':
                                            currentHTML.innerHTML = 'VERSION';
                                            break;
                                        default:
                                            var tempTimeArray1 = "";
                                            var tempTimeArray2 = "";
                                            tempTimeArray1 = currentXML[0].text.split("T");
                                            tempTimeArray2 = tempTimeArray1[0].split("-");
                                            if (tempTimeArray2[0] != '1955') {
                                                currentHTML.innerHTML = tempTimeArray2[1] + "/" +  tempTimeArray2[2] + "/" + tempTimeArray2[0];            
                                            }
                                            break;
                                    }
                                }else{
                                    var tempTimeArray1 = "";
                                    var tempTimeArray2 = "";
                                    tempTimeArray1 = currentXML[0].text.split("T");
                                    tempTimeArray2 = tempTimeArray1[0].split("-");
                                    if (tempTimeArray2[0] != '1955') {
                                        currentHTML.innerHTML = tempTimeArray2[1] + "/" +  tempTimeArray2[2] + "/" + tempTimeArray2[0];            
                                        if (informationElements[i] == 'LastVerified'){
                                            LastVerifiedValue = tempTimeArray2[1] + "/" +  tempTimeArray2[2] + "/" + tempTimeArray2[0];   
                                        }
                                    }
                                    if (informationElements[i] == 'AddedToQueueDate') {
                                        document.getElementById("QueueByRow").style.display = "block";
                                    }
                                }
                            } else if (informationElements[i] == 'AddedBy' || informationElements[i] == 'AddedByIDText' || pdfInformationElements[i] == 'PdfAddedBy' || pdfInformationElements[i] == 'PdfAddedByIDText') {
                                if (informationElements[i] != '' && !pdfPopUp) {
                                    currentHTML.innerHTML = currentXML[0].text.toUpperCase();
                                } else {
                                    currentHTML.innerHTML = 'N/A';
                                }
                            } else if (informationElements[i] == 'AddedToQueueBy' || informationElements[i] == 'AddedToQueueLocation' || informationElements[i] == 'AddedToQueueByIDText' || pdfInformationElements[i] == 'PdfAddedToQueueBy' || pdfInformationElements[i] == 'PdfAddedToQueueByIDText') {
                                if (informationElements[i] != '' && !pdfPopUp) {
                                    currentHTML.innerHTML = currentXML[0].text.toUpperCase();
                                    document.getElementById("QueueByRow").style.display = "block";
                                } else {
                                    currentHTML.innerHTML = 'N/A';
                                }
                            } else if (informationElements[i] == 'Status' || pdfInformationElements[i] == 'PdfStatus') {
                                if (currentXML[0].text.toUpperCase() == 'A') {
                                    currentHTML.innerHTML = 'No';
                                } else if (currentXML[0].text.toUpperCase() == 'R') {
                                    currentHTML.innerHTML = 'Yes';
                                }
                            } else if (informationElements[i] == 'PrivateOrPublic' || pdfInformationElements[i] == 'PdfPrivateOrPublic') {
                                //0=Private (Yes), 1=Public (No) --> Via Marcus
                                if (currentXML[0].text.toUpperCase() == 'TRUE') {
                                    currentHTML.innerHTML = 'No';
                                } else if (currentXML[0].text.toUpperCase() == 'FALSE') {
                                    currentHTML.innerHTML = 'Yes';
                                }
                            } else {
                                currentHTML.innerHTML = currentXML[0].text.toUpperCase();
                            }
                            if (informationElements[i] == 'VerifiedDateDisplayType') {
                                switch (currentXML[0].text){
                                    case '0':
                                        document.getElementById("LastVerified").innerHTML = LastVerifiedValue;
                                        break;
                                    case '1':
                                        document.getElementById("LastVerified").innerHTML = 'N/A';
                                        break;
                                    case '2':
                                        document.getElementById("LastVerified").innerHTML = 'VERSION';
                                        break;
                                    default:
                                        //do nothing
                                        break;
                                }
                            }
                        }else{
                            if (pdfInformationElements[i] == 'PdfRevisionDate' || pdfInformationElements[i] == 'PdfDateCreated' || pdfInformationElements[i] == 'PdfDateUpdated' || pdfInformationElements[i] == 'PdfDateLastReviewed' || informationElements[i] == 'RevisionDate' || informationElements[i] == 'DateCreated' || informationElements[i] == 'DateUpdated' || informationElements[i] == 'DateLastReviewed' || informationElements[i] == 'ApprovalDate' || informationElements[i] == 'LastChanged' || informationElements[i] == 'LastVerified' || informationElements[i] == 'AddedToQueueDate') {
                                if (informationElements[i] == 'DateLastReviewed' || informationElements[i] == 'ApprovalDate'){
                                    var displayType = rootElement.getElementsByTagName("VerifiedDateDisplayType");
                                    switch (displayType[0].textContent){
                                        case '0':
                                            currentHTML.innerHTML = 'N/A';
                                            break;
                                        case '1':
                                            currentHTML.innerHTML = 'N/A';
                                            break;
                                        case '2':
                                            currentHTML.innerHTML = 'VERSION';
                                            break;
                                        default:
                                            var tempTimeArray1 = "";
                                            var tempTimeArray2 = "";
                                            tempTimeArray1 = currentXML[0].textContent.split("T");
                                            tempTimeArray2 = tempTimeArray1[0].split("-");
                                            if (tempTimeArray2[0] != '1955') {
                                                currentHTML.innerHTML = tempTimeArray2[1] + "/" +  tempTimeArray2[2] + "/" + tempTimeArray2[0];
                                            }
                                            break;
                                    }
                                }else{
                                    var tempTimeArray1 = "";
                                    var tempTimeArray2 = "";
                                    tempTimeArray1 = currentXML[0].textContent.split("T");
                                    tempTimeArray2 = tempTimeArray1[0].split("-");
                                    if (tempTimeArray2[0] != '1955') {
                                        currentHTML.innerHTML = tempTimeArray2[1] + "/" +  tempTimeArray2[2] + "/" + tempTimeArray2[0];
                                        if (informationElements[i] == 'LastVerified'){
                                            LastVerifiedValue = tempTimeArray2[1] + "/" +  tempTimeArray2[2] + "/" + tempTimeArray2[0]; 
                                        }
                                    }
                                    if (informationElements[i] == 'AddedToQueueDate') {
                                        document.getElementById("QueueByRow").style.display = "block";
                                    }
                                }
                            } else if (informationElements[i] == 'AddedBy' || informationElements[i] == 'AddedByIDText' || pdfInformationElements[i] == 'PdfAddedBy' || pdfInformationElements[i] == 'PdfAddedByIDText') {
                                if (informationElements[i] != '' && !pdfPopUp) {
                                    currentHTML.innerHTML = currentXML[0].textContent.toUpperCase();
                                } else {
                                    currentHTML.innerHTML = 'N/A';
                                }
                            } else if (informationElements[i] == 'AddedToQueueBy' || informationElements[i] == 'AddedToQueueLocation' || informationElements[i] == 'AddedToQueueByIDText' || pdfInformationElements[i] == 'PdfAddedToQueueBy' || pdfInformationElements[i] == 'PdfAddedToQueueByIDText') {
                                if (informationElements[i] != '' && !pdfPopUp) {
                                    currentHTML.innerHTML = currentXML[0].textContent.toUpperCase();
                                    document.getElementById("QueueByRow").style.display = "block";
                                } else {
                                    currentHTML.innerHTML = 'N/A';
                                }
                            } else if (informationElements[i] == 'Status' || pdfInformationElements[i] == 'PdfStatus') {
                                if (currentXML[0].textContent.toUpperCase() == 'A') {
                                    currentHTML.innerHTML = 'No';
                                } else if (currentXML[0].textContent.toUpperCase() == 'R') {
                                    currentHTML.innerHTML = 'Yes';
                                }
                            } else if (informationElements[i] == 'PrivateOrPublic' || pdfInformationElements[i] == 'PdfPrivateOrPublic') {
                                //0=Private (Yes), 1=Public (No) --> Via Marcus
                                if (currentXML[0].textContent.toUpperCase() == 'TRUE') {
                                    currentHTML.innerHTML = 'No';
                                } else if (currentXML[0].textContent.toUpperCase() == 'FALSE') {
                                    currentHTML.innerHTML = 'Yes';
                                }
                            } else {
                                currentHTML.innerHTML = currentXML[0].textContent.toUpperCase();
                            }
                            
                            if (informationElements[i] == 'VerifiedDateDisplayType') {
                                switch (currentXML[0].textContent){
                                    case '0':
                                        document.getElementById("LastVerified").innerHTML = LastVerifiedValue;
                                        break;
                                    case '1':
                                        document.getElementById("LastVerified").innerHTML = 'N/A';
                                        break;
                                    case '2':
                                        document.getElementById("LastVerified").innerHTML = 'VERSION';
                                        break;
                                    default:
                                        //do nothing
                                        break;
                                }
                            }
                        }                    }
                }
            }
        } else {
            alert("There was a problem retrieving the XML data:\n" + comet.statusText);
        }
    }
}

function recordPDFOpenEventRegistrant(customerAdministratorId, customerUserId, documentId, searchSourceId) {
    var projectPathVariable = projectPath()
    var shortProjectPath = projectPathVariable.split("/")
    var fullProjectPath = cometBaseUrl + '/InsertDocumentOpenEventRegistrant';
    
    sendCometRequest('processInsertDocumentOpenEvent',shortProjectPath[2],fullProjectPath,'CustomerAdministratorId,' + customerAdministratorId + ';CustomerUserId,' + customerUserId + ';DocumentId,' + documentId + ';SearchSourceId,' + searchSourceId);
}

function updateCookie(ebinderProductNameValue) {
        var cookieInformation = document.cookie.toString();
        var ebinderAutoNumberValue = cookieInformation.substring(cookieInformation.indexOf('EbinderAutoNumber=') + 18, cookieInformation.indexOf('&EbinderDocumentName'));
        var ebinderUserDocumentIdValue = cookieInformation.substring(cookieInformation.indexOf('EbinderDocumentId=') + 18, cookieInformation.indexOf('&EbinderPageNumber'));
        var ebinderPageNumberValue = cookieInformation.substring(cookieInformation.indexOf('EbinderPageNumber=') + 18, cookieInformation.indexOf('&EbinderLibraryId'));
        var ebinderLibraryId = cookieInformation.substring(cookieInformation.indexOf('EbinderLibraryId=') + 17, cookieInformation.indexOf('&EbinderOpenPdf'));
        var ebinderOpenPdf = cookieInformation.substring(cookieInformation.indexOf('EbinderOpenPdf=') + 15, cookieInformation.indexOf('&EbinderEnd'));
        ebinderProductNameValue = replaceSpecialCharacters(ebinderProductNameValue);
        resetCookie("UserEbinderInformation=EbinderAutoNumber=&EbinderDocumentName=&EbinderDocumentId=&EbinderPageNumber=&EbinderLibraryId=&EbinderOpenPdf=0&EbinderEnd=",-1);
        document.cookie = "UserEbinderInformation=EbinderAutoNumber=" + ebinderAutoNumberValue + "&EbinderDocumentName="+encodeURIComponent(ebinderProductNameValue)+"&EbinderDocumentId=" + ebinderUserDocumentIdValue + "&EbinderPageNumber=" + ebinderPageNumberValue + "&EbinderLibraryId=" + ebinderLibraryId + "&EbinderOpenPdf=" + ebinderOpenPdf + "&EbinderEnd=yes;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";
}
function updateEntireEbinderCookie(ebinderProductNameValue,ebinderUserDocumentIdValue,ebinderLibraryId) {
        var cookieInformation = document.cookie.toString();
        var ebinderOpenPdf = cookieInformation.substring(cookieInformation.indexOf('EbinderOpenPdf=') + 15, cookieInformation.indexOf('&EbinderEnd'));
        ebinderProductNameValue = replaceSpecialCharacters(ebinderProductNameValue);
        resetCookie("UserEbinderInformation=EbinderAutoNumber=&EbinderDocumentName=&EbinderDocumentId=&EbinderPageNumber=&EbinderLibraryId=&EbinderOpenPdf=0&EbinderEnd=",-1);
        document.cookie = "UserEbinderInformation=EbinderAutoNumber=1&EbinderDocumentName="+encodeURIComponent(ebinderProductNameValue)+"&EbinderDocumentId=" + ebinderUserDocumentIdValue + "&EbinderPageNumber=1&EbinderLibraryId=" + ebinderLibraryId + "&EbinderOpenPdf=" + ebinderOpenPdf + "&EbinderEnd=yes;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";
}

function recentActivityEbinderSearch(newDocumentName,newDocumentId,newLibraryId,recentActivitySummaryTab){
        resetCookie("UserEbinderInformation=EbinderAutoNumber=&EbinderDocumentName=&EbinderDocumentId=&EbinderPageNumber=&EbinderLibraryId=&EbinderOpenPdf=0&EbinderEnd=",-1);
        newDocumentName = trimString(newDocumentName);
        newDocumentName = replaceSpecialCharacters(newDocumentName);
        document.cookie = "UserEbinderInformation=EbinderAutoNumber=1&EbinderDocumentName="+encodeURIComponent(newDocumentName)+"&EbinderDocumentId="+newDocumentId+"&EbinderPageNumber=1&EbinderLibraryId="+newLibraryId+"&EbinderOpenPdf=0&EbinderEnd=yes;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";
        document.location.href = projectPath() + '/Ebinder/' + recentActivitySummaryTab + '.aspx?RecentActivity=yes';                     
}

function openWindow(redirectAddress,windowWidth,windowHeight,isFullUrlPath)
{
    var fullRedirectAddress = currentServerUrl + redirectAddress;
    if (isFullUrlPath == 'true') { fullRedirectAddress = redirectAddress; }
    window.open(fullRedirectAddress, 'messageCenter', 'toolbar=no,width='+windowWidth+',height='+windowHeight);
}

function marketingPageHeight(pageId, totalPageHeight, leftNavId, leftNavHeight, contentId, contentHeight)
{
    document.getElementById(leftNavId).style.height = leftNavHeight + 'px';
    document.getElementById(pageId).style.height = totalPageHeight + 'px';
    document.getElementById(contentId).style.height = contentHeight + 'px';
    
}

/************************************************************/
/* Special Character Conversion for Locations & Groups - LP */
/************************************************************/

function convertSpecialCharacters(stringText) {
    //handle '";<> etc...  (!@#$%^&*() are fine without alteration)
    //while (stringText.indexOf('&') > -1) {stringText = stringText.replace('&','');}
    //while (stringText.indexOf(';') > -1) {stringText = stringText.replace(';','');}
    while (stringText.indexOf(';') > -1) {stringText = stringText.replace(';','^s^e^m^i^c^o^l^o^n^');}
    //while (stringText.indexOf('\\') > -1) {stringText = stringText.replace('\\','^b^a^c^k^s^l^a^s^h^');}
    while (stringText.indexOf('\'') > -1) {stringText = stringText.replace('\'','&rsquo;');}
    while (stringText.indexOf('<') > -1) {stringText = stringText.replace('<','&lt;');}
    while (stringText.indexOf('>') > -1) {stringText = stringText.replace('>','&gt;');}
    while (stringText.indexOf('"') > -1) {stringText = stringText.replace('"','&quot;');}
    return stringText;
}
function convertCharactersForDatabase(stringText) {
    while (stringText.indexOf(';') > -1) {stringText = stringText.replace(';','^s^e^m^i^c^o^l^o^n^');}
    return stringText;
}

function updateOpenPdfCookie(ebinderOpenPdfValue) {
        var cookieInformation = document.cookie.toString();
        var ebinderAutoNumberValue = readCookie(0);
        var ebinderProductNameValue = readCookie(1);
        var ebinderUserDocumentIdValue = readCookie(2);
        var ebinderPageNumberValue = readCookie(3);
        var ebinderLibraryId = readCookie(4);
        resetCookie("UserEbinderInformation=EbinderAutoNumber=&EbinderDocumentName=&EbinderDocumentId=&EbinderPageNumber=&EbinderLibraryId=&EbinderOpenPdf=0&EbinderEnd=",-1);
        document.cookie = "UserEbinderInformation=EbinderAutoNumber=" + ebinderAutoNumberValue + "&EbinderDocumentName="+encodeURIComponent(ebinderProductNameValue)+"&EbinderDocumentId=" + ebinderUserDocumentIdValue + "&EbinderPageNumber=" + ebinderPageNumberValue + "&EbinderLibraryId=" + ebinderLibraryId + "&EbinderOpenPdf=" + ebinderOpenPdfValue.toString() + "&EbinderEnd=yes;EXPIRES=" + getCookieExpirationDate(30) + ";Path=/";
}

/************************************************************/
/*                Searching 'Thinking' Popup                */
/************************************************************/

function disableSearchButton(buttonId,additionalButtonIds,showProcessText) {
    //Take any additional buttons off the page while processing
    if (additionalButtonIds != null) {
        for (var i = 0; i < additionalButtonIds.length; i++) {
            if (document.getElementById(additionalButtonIds[i]) != null) {
                document.getElementById(additionalButtonIds[i]).style.display = 'none';
            }
        }
    }

    searchingIframe = document.getElementById('SearchingIframe');
    searchingOuterDiv = document.getElementById('SearchingOuterDiv');
       
    // make current button invisible, if applicable
    if (document.getElementById(buttonId)) {
        document.getElementById(buttonId).style.display = 'none';
    }
    var url = new String(window.location);
    url = url.toLowerCase();
    if (document.getElementById('SearchTop') || document.getElementById('SingleUploadUploadButton') || url.search("search/newmsdsqueue.aspx") != -1 || url.search("reports/creation.aspx") != -1) {
        if (document.getElementById('SearchTop')){
            searchTop = document.getElementById('SearchTop');
            searchTop.style.display = 'none';
            searchingOuterDiv.style.top = elementGetTop(searchTop) + 'px';
            searchingOuterDiv.style.left = elementGetLeft(searchTop) - 250 + 'px';
            searchingIframe.style.top = elementGetTop(searchTop) + 'px';
            searchingIframe.style.left = elementGetLeft(searchTop) - 250 + 'px';
        }else if (document.getElementById('SingleUploadUploadButton')){
            searchTop = document.getElementById('SingleUploadUploadButton');
            searchTop.style.display = 'none';
            searchingOuterDiv.style.top = elementGetTop(searchTop) + 'px';
            searchingOuterDiv.style.left = elementGetLeft(searchTop) - 45 + 'px';
            searchingIframe.style.top = elementGetTop(searchTop) + 'px';
            searchingIframe.style.left = elementGetLeft(searchTop) - 45 + 'px';
        }else if (url.search("search/newmsdsqueue.aspx") != -1){
            if (document.getElementById('AddToEbinder')){
                searchTop = document.getElementById('AddToEbinder');
            }else if (document.getElementById('DeleteFromQueue')){
                searchTop = document.getElementById('DeleteFromQueue');
            }
            searchTop.style.display = 'none';
            searchingOuterDiv.style.top = elementGetTop(searchTop) + 'px';
            searchingOuterDiv.style.left = elementGetLeft(searchTop) + 270 + 'px';
            searchingIframe.style.top = elementGetTop(searchTop) + 'px';
            searchingIframe.style.left = elementGetLeft(searchTop) + 270 + 'px';
        }else if (url.search("reports/creation.aspx") != -1){
            if (document.getElementById('ReportsCriteriaControl_MoveOn')){
                searchTop = document.getElementById('ReportsCriteriaControl_MoveOn');
            }else if (document.getElementById('ReportsCriteriaControl_Cancel')){
                searchTop = document.getElementById('ReportsCriteriaControl_Cancel');
            }
            searchTop.style.display = 'none';            
            if (hQCall == 'True') {            
                searchingOuterDiv.style.top = elementGetTop(searchTop) - 150 + 'px';
                searchingOuterDiv.style.left = elementGetLeft(searchTop) - 80  + 'px';
                searchingIframe.style.top = elementGetTop(searchTop) - 150 + 'px';
                searchingIframe.style.left = elementGetLeft(searchTop) - 80 + 'px';
            }else{
                searchingOuterDiv.style.top = elementGetTop(searchTop) - 100 + 'px';
                searchingOuterDiv.style.left = elementGetLeft(searchTop) - 70 + 'px';
                searchingIframe.style.top = elementGetTop(searchTop) - 100 + 'px';
                searchingIframe.style.left = elementGetLeft(searchTop) - 70 + 'px';
            }
        }
    }
    searchingOuterDiv.style.display = 'inline';
    searchingIframe.style.display = 'inline';
    searchingOuterDiv.style.visibility = 'visible';
    searchingIframe.style.visibility = 'visible';
    
    // Modify for browser differences
    if (browserName != 'IE' ) {
        if (url.search("ebinder") != -1 ) {
            if (hQCall == 'True') {
                searchingOuterDiv.style.marginTop = '70px';
                searchingIframe.style.marginTop = '70px';
            } else {
                searchingOuterDiv.style.marginTop = '163px';
                searchingIframe.style.marginTop = '163px';
            }
            searchingOuterDiv.style.marginLeft = '440px';
            searchingIframe.style.marginLeft = '440px';
        } else if (url.search("search/default.aspx") != -1) {
            if (hQCall == 'True') {
                searchingOuterDiv.style.marginLeft = '510px';
                searchingIframe.style.marginLeft = '510px';
                searchingOuterDiv.style.marginTop = '100px';
                searchingIframe.style.marginTop = '100px';
            } else {
                searchingOuterDiv.style.marginLeft = '710px';
                searchingIframe.style.marginLeft = '710px';
                searchingOuterDiv.style.marginTop = '167px';
                searchingIframe.style.marginTop = '167px';
            }
        } else if (url.search("search/addlocalmsds.aspx") != -1) {
            if (hQCall == 'True') {
                searchingOuterDiv.style.marginLeft = '300px';
                searchingIframe.style.marginLeft = '300px';
                searchingOuterDiv.style.marginTop = '120px';
                searchingIframe.style.marginTop = '120px';
            } else {
                searchingOuterDiv.style.marginLeft = '520px';
                searchingIframe.style.marginLeft = '520px';
                searchingOuterDiv.style.marginTop = '220px';
                searchingIframe.style.marginTop = '220px';
            }
        } else if (url.search("search/newmsdsqueue.aspx") != -1) {
            if (hQCall == 'True') {
                searchingOuterDiv.style.marginLeft = '40px';
                searchingIframe.style.marginLeft = '40px';
                searchingOuterDiv.style.marginTop = '200px';
                searchingIframe.style.marginTop = '200px';
            } else {
                searchingOuterDiv.style.marginLeft = '210px';
                searchingIframe.style.marginLeft = '210px';
                searchingOuterDiv.style.marginTop = '267px';
                searchingIframe.style.marginTop = '267px';
            }
        } else if (url.search("reports/creation.aspx") != -1) {
            if (hQCall == 'True') {
                searchingOuterDiv.style.marginLeft = '380px';
                searchingIframe.style.marginLeft = '380px';
                searchingOuterDiv.style.marginTop = '220px';
                searchingIframe.style.marginTop = '220px';
            } else {
                searchingOuterDiv.style.marginLeft = '530px';
                searchingIframe.style.marginLeft = '530px';
                searchingOuterDiv.style.marginTop = '280px';
                searchingIframe.style.marginTop = '280px';
            }
        }
    } 

}


function lockPickListImage(plusImage) {
    plusImage.onclick = '';
}

function showHideCourseDescription(description,courseTitleDivId,showHideFlag) {
    if (showHideFlag == 1) {
        document.getElementById('CourseDescriptionPopup').innerHTML = description;
        document.getElementById('CourseDescriptionPopup').style.top = elementGetTop(document.getElementById(courseTitleDivId)) + 12 + 'px';
        document.getElementById('CourseDescriptionPopup').style.left = elementGetLeft(document.getElementById(courseTitleDivId)) + 20  + 'px';
        document.getElementById('CourseDescriptionPopup').style.display = 'inline';
    } else {
        document.getElementById('CourseDescriptionPopup').innerHTML = '';
        document.getElementById('CourseDescriptionPopup').style.display = 'none';
    }
}

/* PRELOAD IMAGES */

function preloadImages(ImageSource){
    var preloadImageInformation = new Image();
    preloadImageInformation.src = ImageSource;
}


/****************************************************************/
/*                Start GrayOut Background                      */
/****************************************************************/
function grayOutPage(visible, options) {
    // Pass true to gray out screen, false to ungray
    // options are optional.  This is a JSON object with the following (optional) properties
    // opacity:0-100         // Lower number = less grayout higher = more of a blackout
    // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
    // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
    // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
    // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
    // in any order.  Pass only the properties you need to set.
    var options = options || {};
    var zindex = options.zindex || 50;
    var opacity = options.opacity || 70;
    var opaque = (opacity / 100);
    var bgcolor = options.bgcolor || '#000000';
       
    var darkObjects = [];
    darkObjects[0] = document.getElementById('darkenScreenObject');
        
    if (!darkObjects[0]) {
        // The dark layer doesn't exist (apply some basic styles)
        var pageBody = document.getElementsByTagName("body")[0];
        var divNode = document.createElement('div');
        divNode.style.position = 'absolute';
        divNode.style.top = '0px';
        divNode.style.left = '0px';
        divNode.style.overflow = 'hidden';
        divNode.style.display = 'none';
        divNode.id = 'darkenScreenObject';
        pageBody.appendChild(divNode);
        darkObjects[0] = document.getElementById('darkenScreenObject');
    }
        
    if (location.href != parent.location.href) {
        darkObjects[1] = parent.document.getElementById('darkenScreenObject1');
        darkObjects[2] = parent.document.getElementById('darkenScreenObject2');
        darkObjects[3] = parent.document.getElementById('darkenScreenObject3');
        darkObjects[4] = parent.document.getElementById('darkenScreenObject4');
        
        // Grab iframe properties
        var iframe = parent.document.getElementById(parent.top.frames[0].name);
        var iframeOffsets = findPos(iframe);
        var iframeOffsetLeft = iframeOffsets[0];
        var iframeOffsetTop = iframeOffsets[1];
        
        var divTop = 0;
        var divLeft = 0;
        var pageBody = parent.document.getElementsByTagName("body")[0];
        var divNode;
        
        // Calculate the left and top positions
        for (var i = 1; i < darkObjects.length; i++) {
            switch (i) {
                case 1:
                    divTop = 0;
                    divLeft = 0;
                    break;
                case 2:
                    divTop = iframeOffsetTop;
                    divLeft = 0;
                    break;
                case 3:
                    divTop = iframeOffsetTop;
                    divLeft = iframeOffsetLeft + iframe.offsetWidth;
                    break;
                case 4:
                    divTop = iframeOffsetTop + iframe.offsetHeight;
                    divLeft = 0;
                    break;
            }
            
            // The dark layer doesn't exist (apply some basic styles)
            if (!darkObjects[i]) {
                divNode = parent.document.createElement('div');
            } else {
                divNode = parent.document.getElementById('darkenScreenObject' + i);
            }
            divNode.style.position = 'absolute';
            divNode.style.top = divTop + 'px';
            divNode.style.left = divLeft + 'px';
            divNode.style.overflow = 'hidden';
            divNode.style.display = 'none';
            divNode.id = 'darkenScreenObject' + i;
            if (!darkObjects[i]) {
                pageBody.appendChild(divNode);
            }
            darkObjects[i] = parent.document.getElementById('darkenScreenObject' + i);
        }
    }
   
    if (visible) {
        var divWidth = 0;
        var divHeight = 0;

        // Calculate the div widths and heights
        for (var i = 0; i < darkObjects.length; i++) {
            switch (i) {
                case 0:
                    divWidth = document.documentElement.clientWidth;
                    divHeight = Math.max(document.documentElement.clientHeight, document.documentElement.scrollHeight);
                    break;
                case 1:
                    divWidth = parent.document.documentElement.clientWidth;
                    divHeight = iframeOffsetTop;
                    break;
                case 2:
                    divWidth = iframeOffsetLeft;
                    divHeight = iframe.offsetHeight;
                    break;
                case 3:
                    divWidth = parent.document.documentElement.clientWidth - (iframeOffsetLeft + iframe.offsetWidth);
                    if (divWidth < 0) {
                        divWidth = 0;
                    }
                    divHeight = iframe.offsetHeight;
                    break;
                case 4:
                    divWidth = parent.document.documentElement.clientWidth;
                    divHeight = Math.max(parent.document.documentElement.clientHeight, parent.document.documentElement.scrollHeight) - iframe.offsetHeight - iframeOffsetTop;
                    break;
            }
        
            // Set the shader to cover the entire div and make it visible.
            darkObjects[i].style.opacity = opaque;
            darkObjects[i].style.MozOpacity = opaque;
            darkObjects[i].style.filter = 'alpha(opacity='+opacity+')';
            darkObjects[i].style.zIndex = zindex;
            darkObjects[i].style.backgroundColor = bgcolor;
            darkObjects[i].style.display = 'block';
            darkObjects[i].style.width = divWidth + 'px';
            darkObjects[i].style.height = divHeight + 'px';
        }
    } else {
        for (var i = 0; i < darkObjects.length; i++) {
            darkObjects[i].style.display = 'none';
        }
    }
}
function hideFlash(){  /* hide all flash in the page */
    flash = document.getElementsByTagName('object')
    for (var i = 0; i < flash.length; i++) { 
            flash[i].style.visibility = 'hidden';
    }
}
function showFlash(){ /* show all flash */
    flash = document.getElementsByTagName('object')
    for (var i = 0; i < flash.length; i++) { 
            flash[i].style.visibility = 'visible';
    }
}

/************************************************************/
/*            General string formatting                     */
/************************************************************/
function ellipse(transformString, maxWordLength, maxStringLength, useHtmlEllipseCode ) {
    // Check for initial parameter errors
    if (typeof useHtmlEllipseCode == "undefined") {
        useHtmlEllipseCode = false;
    }
    if (transformString == null) {
        throw("transformString cannot be null.");
    }
    if (maxWordLength < 1) {
        throw("maxWordLength cannot be less than 1. maxWordLength was " + maxWordLength);
    }
    if (maxStringLength < 1) {
        throw("maxStringLength cannot be less than 1. maxStringLength was " + maxStringLength);
    }
    if (maxWordLength > maxStringLength) {
        throw("maxWordLength cannot be greater than maxStringLength. maxWordLength was " + maxWordLength + ", maxStringLength was " + maxStringLength);
    }
    
    // No ellipsing will happen if the string isn't even long enough for the max word length
    if (transformString.length <= maxWordLength) {
        return transformString;
    }

    // Setup the Ellipse type to use
    if (useHtmlEllipseCode) {
        ellipseCode = "&hellip;";
    } else {
        ellipseCode = "…";
    }

    // Initialize strings and separate words within the string
    
    transformStringWords = transformString.split(" ");
    tempString = "";
    
    for (i=0;i<transformString.length;i+=1) {
    
        // Check that there aren't any too-long words
        if (transformStringWords[i].length > maxWordLength) {
            transformStringWords[i] = transformStringWords[i].substr(0, maxWordLength - 1) + ellipseCode;
        }

        if (i == 0) {
            tempString = transformStringWords[i];
        } else {
            tempString += " " + transformStringWords[i];
        }
        if (tempString.length > maxStringLength) {
            tempString = tempString.substr(0,maxStringLength - ellipseCode.length);
            tempString += ellipseCode;
            break;
        } else if ( tempString.substr(tempString.length - ellipseCode.length, ellipseCode.length) == ellipseCode ) {
            break;
        }
    }
    return tempString;
}

function htmlEncode (str) {
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
};

function htmlDecode (html) {
   var htmlNode = document.createElement("DIV");
   htmlNode.innerHTML = html;
   if(htmlNode.innerText)
      return htmlNode.innerText; // IE
   return htmlNode.textContent; // FF
}

function urlEncode( str ) {
    // use like .NET's Server.UrlEncode                                    
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    ret = encodeURIComponent(ret);
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }   
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) { return "%"+m2.toUpperCase();});
    return ret;
}

function urlDecode( str ) {
    // use like .NET's Server.UrlDecode   
    var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
    var ret = str.toString();
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    return decodeURIComponent(ret);
}

function clean (element) {
// see http://developer.mozilla.org/en/firstChild#Notes on why we need to clean whitespace
    if (browserName != "IE" && element.childNodes) {
        for (var i = 0; i < element.childNodes.length; i++) {
            var node = element.childNodes[i];
            if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) {
                element.removeChild(node);
            }
        }
    }
    return element;
}

function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
    //http://snipplr.com/view.php?codeview&id=1853
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)", "i") : null;
    var oCurrent;
    var oAttribute;
    for(var i=0; i<arrElements.length; i++){
        oCurrent = arrElements[i];
        oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
        if(typeof oAttribute == "string" && oAttribute.length > 0){
            if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
                arrReturnElements.push(oCurrent);
            }
        }
    }
    return arrReturnElements;
}
function hideTab() {
    document.getElementById('AdvancedSearchCustomers').style.display = 'none';
    document.getElementById('AdvancedSearchLink').style.display = 'inline';
    document.getElementById('AdvancedSearchOpen').value = 'False';
}
function currentTab() {
    document.getElementById('AdvancedSearchCustomers').style.display = 'block';
    document.getElementById('AdvancedSearchLink').style.display = 'none';
    document.getElementById('AdvancedSearchOpen').value = 'True';
}

// new marketing tabs for product pages - Benefits, Options, etc. //
  var tabsClass = {
  tabSetArray: new Array(),
  classOn: "tabsOn",
  classOff: "tabsOff",
  addTabs: function (tabsContainer) {
      tabs = document.getElementById(tabsContainer).getElementsByTagName("div");
  for (x in tabs) {
      if (typeof(tabs[x].id) != "undefined") {
      this.tabSetArray.push(tabs[x].id);
  } else {}
}
      },
      switchTab: function (element) {
      for (x in this.tabSetArray) {
      tabItem = this.tabSetArray[x];
      dataElement = document.getElementById(tabItem + "Data");
      if (dataElement) {
      if (dataElement.style.display != "none") {
      dataElement.style.display = "none";
      } else {}
      } else {}
      tabElement = document.getElementById(tabItem);
      if (tabElement) {
      if (tabElement.className != this.classOff) {
      tabElement.className = this.classOff;
      } else {}
      } else {}
      }
      document.getElementById(element.id + "Data").style.display = "";
      element.className = this.classOn;
      }
      };