﻿//-------------------------------------------------------------------------------
// <copyright file="SelectionUtilities.cs" company="BioCentury Publications Inc."> 
// All contents Copyright © 2005-2009 BioCentury Publications, Inc. ALL RIGHTS RESERVED
// 
// http://www.biocentury.com 
// </copyright>
//-------------------------------------------------------------------------------

//-------------------------------------------------------------------------------
// GLOBAL VARIABLES
//-------------------------------------------------------------------------------
var m_strMessageUnselection = "Please select at least one item.";
var m_strMessagePositiveDecimal = "Please enter a positive number up to 2 decimal points.";
var m_strMessageInteger = "Please enter integer numbers.";
//var m_strMessageInteger = "Please enter integer numbers.";

var m_Array = []; // used for Charts when the Filter is moved from Series or Categories to RESTRICT DATA BY;

var m_SelectionSet = "";
var m_SummarySet = [];
var m_SelectionArray = [];

var m_SelectionColor = "#0066FF"; //"#339999"; //"#676534";
var m_UnSelectionColor = "#000000";

setTimeout('clear()', 1);
function clear() {
    if (window.status != null) {
        window.status = "";
        setTimeout('clear()', 1);
    }
}

//-------------------------------------------------------------------------------
// String trim
//-------------------------------------------------------------------------------

/// <summary locid="M:J#String.trim" />
/// <returns type="String"></returns>
function trim(str) 
{
    if (str == "") 
        return "";
    return str.replace(/^\s+|\s+$/g, '');
}

/// <summary locid="M:J#String.trimEnd" />
/// <returns type="String"></returns>
function trimEnd(str) 
{
    if (str == "") 
        return "";
    return str.replace(/\s+$/, '');
}

/// <summary locid="M:J#String.trimStart" />
/// <returns type="String"></returns>
function trimStart(str) 
{
    if (str == "") 
        return "";
    return str.replace(/^\s+/, '');
}


//-------------------------------------------------------------------------------
// Variables used in Tables.aspx
//-------------------------------------------------------------------------------
//not used
//var totalSummary = ""; //used for export and print
var companyListName = "";
var companyListType = ""; //CompanyList,CompanyName

// bug #410 - partial fix
function closeArchiveSectionCon()
{
    if(lastExecutor != null)
    {
        if(lastExecutor.get_started())
        {
            lastExecutor.abort();
        }
    }
}

//company profile area
function getCompanyProfileData(IsPublicCompanyProfile, GUID) 
{
    // used for public company profilefor 
    if (GUID == undefined)
        GUID = '';    
    
    //TODO: Eugen  - when opened in popup
    retFS = BCIQ.AJAX.Utilities.getFinancingSummarySection(IsPublicCompanyProfile, OnCompleteFS, OnTimeOutFS, OnErrorFS);
    retFD = BCIQ.AJAX.Utilities.getFinancingDetailedSection(IsPublicCompanyProfile, OnCompleteFD, OnTimeOutFD, OnErrorFD);

    retFPS = BCIQ.AJAX.Utilities.getFinancialPerformanceSummarySection(IsPublicCompanyProfile, GUID, OnCompleteFPS, OnTimeOutFPS, OnErrorFPS);
    retPS = BCIQ.AJAX.Utilities.getPipelineSummarySection(IsPublicCompanyProfile, OnCompletePS, OnTimeOutPS, OnErrorPS);
    retPD1 = BCIQ.AJAX.Utilities.getPipelineDetailed1Section(IsPublicCompanyProfile, GUID, OnCompletePD1, OnTimeOutPD1, OnErrorPD1);
    retPD2 = BCIQ.AJAX.Utilities.getPipelineDetailed2Section(IsPublicCompanyProfile, OnCompletePD2, OnTimeOutPD2, OnErrorPD2);

    if (IsPublicCompanyProfile)
    {
        // bug #410 - partial fix
        retA = Sys.Net.WebServiceProxy.invoke('Utilities.asmx', 'getArchivesSection', false, {"IsPublicCompanyProfile":IsPublicCompanyProfile}, OnCompleteArchives, OnErrorArchives, '', -1);
        lastExecutor = retA.get_executor();
    }
    {
        retA = BCIQ.AJAX.Utilities.getArchivesSection(IsPublicCompanyProfile, OnCompleteArchives, OnTimeOutArchives, OnErrorArchives);
    }
}

function OnCompleteArchives(result) {
    if (result == "no data") {
        document.getElementById("divArchivesItems").className = "DivHidden";
//        document.getElementById("divArchivesItemsInfo").className = "DivHidden";
        return;
    }
    if (result != null) {
        document.getElementById('divArchivesItems').innerHTML = result;
        CollapseExpandTree('companynewsall');
        CollapseExpandTree('clinicalnewsall');
        CollapseExpandTree('financialnewsall');
        CollapseExpandTree('biocx');
    }
    else
        OnErrorArchives(result);
}
function OnTimeOutArchives(result) {
    document.getElementById('divArchivesItems').innerHTML = '<label>Archives items could not be retrieved</label>';
}
function OnErrorArchives(result) {
    document.getElementById('divArchivesItems').innerHTML = '<label>Archives items could not be retrieved</label>';
}
function OnCompleteFS(result) {
    if (result == "no data") {
        document.getElementById(divFinancingSummaryId).className = "DivHidden";
        document.getElementById(divFinancingSummaryInfoId).className = "DivHidden";
        return;
    }
    if (result != null) {
        document.getElementById('FinancingHeaderDiv').className = "DivVisible";
        document.getElementById(divFinancingSummaryId).innerHTML = result;
        if (!hasFRight && !isPublicCompanyProfile) 
        {
            document.getElementById('aFinancingSummary').href = ""; //"javascript:createFinancingsReportFromProfile();";
        }        
    }
    else
        OnErrorFS(result);
}
function OnTimeOutFS(result) {
    document.getElementById('FinancingHeaderDiv').className = "DivVisible";
    document.getElementById(divFinancingSummaryId).innerHTML = '<label>Financing summary could not be retrieved</label>';
}
function OnErrorFS(result) {
    document.getElementById('FinancingHeaderDiv').className = "DivVisible";
    document.getElementById(divFinancingSummaryId).innerHTML = '<label>Financing summary could not be retrieved</label>';
}
function OnCompleteFD(result) {
    if (result == "no data") {
        document.getElementById(divFinancingDetailedId).className = "DivHidden";
        document.getElementById(divFinancingDetailedInfoId).className = "DivHidden";
        return;
    }
    if (result != null) {
        document.getElementById('FinancingHeaderDiv').className = "DivVisible";
        document.getElementById(divFinancingDetailedId).innerHTML = result;
        // Public Financig Detailed label
        if (document.getElementById('lblPublicFinancingDetails') != null)
            document.getElementById('lblFinancingDetails').innerHTML = document.getElementById('lblPublicFinancingDetails').innerHTML;
    }
    else
        OnErrorFD(result);
}
function OnTimeOutFD(result) {
    document.getElementById('FinancingHeaderDiv').className = "DivVisible";
    document.getElementById(divFinancingDetailedId).innerHTML = '<label>Financing details could not be retrieved</label>';
}
function OnErrorFD(result) {
    document.getElementById('FinancingHeaderDiv').className = "DivVisible";
    document.getElementById(divFinancingDetailedId).innerHTML = '<label>Financing details could not be retrieved</label>';
}
function OnCompleteFPS(result) {
    if (result == "no data") {
        document.getElementById(divFinancialPerformanceSummaryId).className = "DivHidden";
        document.getElementById(divFinancialPerformanceSummaryInfoId).className = "DivHidden";
        return;
    }
    if (result != null) {
        document.getElementById('FinancingHeaderDiv').className = "DivVisible";
        document.getElementById(divFinancialPerformanceSummaryId).innerHTML = result;
    }
    else
        OnErrorFPS(result);
}
function OnTimeOutFPS(result) {
    document.getElementById('FinancingHeaderDiv').className = "DivVisible";
    document.getElementById(divFinancialPerformanceSummaryId).innerHTML = '<label>Financial Performance summary could not be retrieved</label>';
}
function OnErrorFPS(result) {
    document.getElementById('FinancingHeaderDiv').className = "DivVisible";
    document.getElementById(divFinancialPerformanceSummaryId).innerHTML = '<label>Financing Performance summary could not be retrieved</label>';
}
function OnCompletePS(result) {
    if (result == "no data") {
        document.getElementById(divPipelineSummaryId).className = "DivHidden";
        document.getElementById(divPipelineSummaryInfoId).className = "DivHidden";
        return;
    }
    if (result != null) {
        document.getElementById('PipelineHeaderDiv').className = "DivVisible";
        document.getElementById(divPipelineSummaryId).innerHTML = result;
        if (!hasPRight && !isPublicCompanyProfile) 
        {
            document.getElementById('aPipelineSummary').href = ""; //"javascript:createPipelineReportFromProfile();";
        }        
    }
    else
        OnErrorPS(result);
}
function OnTimeOutPS(result) {
    document.getElementById('PipelineHeaderDiv').className = "DivVisible";
    document.getElementById(divPipelineSummaryId).innerHTML = '<label>Pipeline summary could not be retrieved</label>';
}
function OnErrorPS(result) {
    document.getElementById('PipelineHeaderDiv').className = "DivVisible";
    document.getElementById(divPipelineSummaryId).innerHTML = '<label>Pipeline summary could not be retrieved</label>';
}
function OnCompletePD1(result) {
    if (result == "no data") {
        document.getElementById(divPipelineDetailed1Id).className = "DivHidden";
        document.getElementById(divPipelineDetailed1InfoId).className = "DivHidden";
        return;
    }
    if (result != null) 
    {
        document.getElementById('PipelineHeaderDiv').className = "DivVisible";
        document.getElementById(divPipelineDetailed1Id).innerHTML = result;
        // Public Pipeline Detail1 label
        if (document.getElementById('lblPublicPipelineDetail1') != null)
            document.getElementById('lblPipelineDetail1').innerHTML = document.getElementById('lblPublicPipelineDetail1').innerHTML;
    }
    else
        OnErrorPD1(result);
}
function OnTimeOutPD1(result) {
    document.getElementById('PipelineHeaderDiv').className = "DivVisible";
    document.getElementById(divPipelineDetailed1Id).innerHTML = '<label>Originated and out-licensed products could not be retrieved</label>';
}
function OnErrorPD1(result) {
    document.getElementById('PipelineHeaderDiv').className = "DivVisible";
    document.getElementById(divPipelineDetailed1Id).innerHTML = '<label>Originated and out-licensed products could not be retrieved</label>';
}
function OnCompletePD2(result) {
    if (result == "no data") {
        document.getElementById(divPipelineDetailed2Id).className = "DivHidden";
        document.getElementById(divPipelineDetailed2InfoId).className = "DivHidden";
        return;
    }
    if (result != null) 
    {
        document.getElementById('PipelineHeaderDiv').className = "DivVisible";
        document.getElementById(divPipelineDetailed2Id).innerHTML = result;

        // Public Pipeline Detail2 label
        if (document.getElementById('lblPublicPipelineDetail2') != null)
            document.getElementById('lblPipelineDetail2').innerHTML = document.getElementById('lblPublicPipelineDetail2').innerHTML;
    }
    else
        OnErrorPD2(result);
}
function OnTimeOutPD2(result) {
    document.getElementById('PipelineHeaderDiv').className = "DivVisible";
    document.getElementById(divPipelineDetailed2Id).innerHTML = '<label>In-licensed products could not be retrieved</label>';
}
function OnErrorPD2(result) {
    document.getElementById('PipelineHeaderDiv').className = "DivVisible";
    document.getElementById(divPipelineDetailed2Id).innerHTML = '<label>In-licensed products could not be retrieved</label>';
}


//end company profile area

//-------------------------------------------------------------------------------
// ADD - Bela Gaspar - 09/12/2008
// Ajax - WebService (Utilities.asmx)
// Start
//-------------------------------------------------------------------------------
//Sets the session state value.
function SetSessionValue(key, value)
{
    BCIQ.AJAX.Utilities.SetSessionValue(key, value,
        OnSucceeded, OnFailed);
}

// Callback function invoked on successful 
// completion of the page method.
function OnSucceeded(result, userContext, methodName) 
{

}

// Callback function invoked on failure 
// of the page method.
function OnFailed(error, userContext, methodName) 
{
    if (error !== null) {
        //displayElement.innerHTML = "An error occurred: " + 
        //    error.get_message();
    }
}

//-------------------------------------------------------------------------------
//used for Ajax dropdown hidding
//-------------------------------------------------------------------------------
function MouseDown(e) {
    var id = '';
    if (e == null) {
        e = window.event;
        id = e.srcElement.id;
    }
    else
        id = e.explicitOriginalTarget.id;
    //alert(id);
    if (globalDiv && globalDiv.className != 'DivHidden' && id != 'querydiv')
        hideDiv();
}


//-------------------------------------------------------------------------------
// ADD - Eugen Popa - 12/02/2005
// Modified by Bela Gaspar - 12/15/2006 - theParam
// used in Financings/Pipeline, Company: Table/Charts to reset the checkboxes to initial state "All ..."
// basically is called from XSL files
//-------------------------------------------------------------------------------
function DoReset(theParam) {
    switch (theParam) {
        case 1: // Charts
            for (var x = 0; x < document.getElementsByTagName("input").length; x++) {
                if (document.getElementsByTagName("input")[x].type &&
					document.getElementsByTagName("input")[x].type == 'checkbox') {
                    //all uncheched bug 206
                    //if (document.getElementsByTagName("input")[x].id == 'UniverseID=901')
                    //	document.getElementsByTagName("input")[x].checked = true;
                    //else
                    document.getElementsByTagName("input")[x].checked = false;
                }
            }

            if (document.getElementById('hasChanged') != null)
                document.getElementById('hasChanged').value = 'false';
            break;

        case 0: // Reports
            for (var x = 0; x < document.getElementsByTagName("input").length; x++) {
                if (document.getElementsByTagName("input")[x].type &&
					document.getElementsByTagName("input")[x].type == 'checkbox') {
                    document.getElementsByTagName("input")[x].checked = false;
                }
            }

            if (document.getElementById('hasChanged') != null)
                document.getElementById('hasChanged').value = 'false';

            break;
        //all uncheched bug 206          
        /*document.getElementById('hasChanged').value = 'false';
        if (document.getElementById('UniverseID=901').checked == false)
        document.getElementById('UniverseID=901').click();
        break;*/ 

    }
}


//-------------------------------------------------------------------------------
// ADD - Marius Paltanea - 01/19/2009
// Descr: Reset buttons on the Disease Class Main Page, MT and MOA
//-------------------------------------------------------------------------------
function DoResetWithSummary() {

    for (var x = 0; x < document.getElementsByTagName("input").length; x++) {
        if (document.getElementsByTagName("input")[x].type &&
					document.getElementsByTagName("input")[x].type == 'checkbox' &&
					document.getElementsByTagName("input")[x].checked == true) {
            //all uncheched bug 206
            //if (document.getElementsByTagName("input")[x].id == 'UniverseID=901')
            //	document.getElementsByTagName("input")[x].checked = true;
            //else
            document.getElementsByTagName("input")[x].click();
        }
        else {
            if (document.getElementsByTagName("input")[x].type &&
					document.getElementsByTagName("input")[x].type == 'checkbox' &&
					document.getElementsByTagName("input")[x].getAttribute("with")!=null) {
                document.getElementsByTagName("input")[x].click();
                document.getElementsByTagName("input")[x].click();
            }
        }
    }

    if (document.getElementById('hasChanged') != null)
        document.getElementById('hasChanged').value = 'false';

}

//-------------------------------------------------------------------------------
// "Save Company List"
// used in all modules
//-------------------------------------------------------------------------------
function ComputeFinancingsSelections(css) {
    if (document.aspnetForm.CompanyListSelections.value == '') {
        alert('You must select at least one company.');
        return false;
    }
    if (saveWindow == null) {
        leftVal = (screen.width - 500) / 2;
        topVal = (screen.height - 150) / 2;
        saveWindow = window.open("../Common/SaveCompanyList.aspx?css=" + css, "_blank", 'width=500,height=150,left=' + leftVal + ',top=' + topVal + ',toolbar=0,resizable=0');
        return false;
    }
    else {
        saveWindow.close();
        if (document.getElementById('btnSaveSelectionsClicked').value == "1") {
            return true;
        }
        else {
            saveWindow = window.open("../Common/SaveCompanyList.aspx?css=" + css, "_blank", 'width=500,height=150,left=' + leftVal + ',top=' + topVal + ',toolbar=0,resizable=0');
            return false;
        }
    }
}
function CheckIfCompaniesSelected(firstIdsHiddenID, companyIdsHiddenID, modalPopupExtenderID) {
    if (document.getElementById(companyIdsHiddenID) != null && document.getElementById(companyIdsHiddenID).value != "") {
        SaveInSession('selectedFirstIDs', document.getElementById(firstIdsHiddenID).value);
        SaveInSession('selectedSecondIDs', document.getElementById(companyIdsHiddenID).value);
        $find(modalPopupExtenderID).show();
        return false;
    }
    else {
        alert('You must select at least one company.');
        return false;
    }
}

function CheckIfCriteriasSelected(modalPopupExtenderID) {
    $find(modalPopupExtenderID).show();
    return false;
}

function CheckAvailableAlerts(productID, modalPopupExtenderID) {
    result = CheckAvailableAlertsSync(productID);
    if (result != null && result != "") {
        available = parseInt(result.split(',')[1]);
        if (available > 0) {
            return true;
        }
        else {
            used = parseInt(result.split(',')[0]);
            result = "<br/>You already reached <b>" + used + "</b> email alerts, the maximum number you can set.<br/>To delete an email alert go to <a class=\"company_link\" href=\"../../mybiocentury/mybcAlertsBCIQ.aspx\" onclick=\"$find('" + modalPopupExtenderID + "').hide();\" title=\"MyBioCentury Tools\">MyBioCentury Tools</a>.<br/><br/>";
            document.getElementById('divAvailableAlerts').innerHTML = result;
            $find(modalPopupExtenderID).show();
            return false;
        }
    }
}

//-------------------------------------------------------------------------------
// Added by Marius 4/1/2009
// Gets the number of available alerts
//-------------------------------------------------------------------------------
function CheckAvailableAlertsSync(productID) {
    try {
        var httpRequest = GetXmlHttpObject();

        var xmlSOAP = '<?xml version="1.0" encoding="utf-8"?>' +
         '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
         'xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> ' +
          '<soap:Body>' +
           '<AvailableEmailAlerts xmlns="http://tempuri.org/">' +
            '<productID>' + productID + '</productID>' +
           '</AvailableEmailAlerts>' +
          '</soap:Body>' +
         '</soap:Envelope>';



        // send XML document to Web server
        httpRequest.onreadystatechange = new function() { };

        httpRequest.open("POST", UtilitiesWSUrl, false);

        httpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/AvailableEmailAlerts");
        httpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        httpRequest.send(xmlSOAP);


        if (httpRequest.status == 200) {
            text = httpRequest.responseText;
            try //Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(text);
                try {
                    return xmlDoc.getElementsByTagName("AvailableEmailAlertsResult")[0].text;
                }
                catch (e) {
                    alert(e.message);
                }
            }
            catch (ex) {
                try //Firefox, Mozilla, Opera, etc.
                {
                    parser = new DOMParser();
                    xmlDoc = parser.parseFromString(text, "text/xml");
                    try {
                        return xmlDoc.getElementsByTagName("AvailableEmailAlertsResult")[0].firstChild.nodeValue;
                    }
                    catch (e) {
                        alert(e.message);
                    }
                }
                catch (er) { alert(er.message) }
            }

        }
        else {
            alert("The available number of email alerts couldn't be accessed.");
        }
    }
    catch (err)
    { }
}

//-------------------------------------------------------------------------------
// Used In Setting the email alert for Financings, FP, Stocks
// ADD by Mihai on 29.01.2009
//-------------------------------------------------------------------------------
function ShowModalPopupSetEmailAlert(modalPopupExtenderID, EmailAlertCompanyList, CompanyList, EmailAlertCompanyDescription, CompanyDescription, EmailAlertCriteriaName, CriteriaList, EmailAlertCriteriaDescription, CriteriaDescription, CompanyListBool, CompanyDescriptionBool) {
    // decode names and descriptions
    CompanyList = trim (unescape(CompanyList));
    CompanyDescription = trim (unescape(CompanyDescription));
    CriteriaList = trim (unescape(CriteriaList));
    CriteriaDescription = trim (unescape(CriteriaDescription));
    
    if (CompanyList != "") 
    {
        if (EmailAlertCompanyList != "") 
        {
            if (CompanyList != "Temporary List") 
            {
                document.getElementById(EmailAlertCompanyList).value = CompanyList;
            }
            else 
            {
                document.getElementById(EmailAlertCompanyList).value = ""; 
            }
            if (EmailAlertCompanyDescription != "")
            {
                if (CompanyDescription != "") 
                {
                    document.getElementById(EmailAlertCompanyDescription).value = CompanyDescription;
                }
                else
                {
                    document.getElementById(EmailAlertCompanyDescription).value = "";
                }
            }
        }
        if (CompanyListBool == "false") {
            document.getElementById(EmailAlertCompanyList).disabled = false;
        }
        else {
            document.getElementById(EmailAlertCompanyList).disabled = true;
        }
        if (CompanyDescriptionBool == "false") {
            //document.getElementById(EmailAlertCompanyDescription).disabled = false;
        }
        else {
            //document.getElementById(EmailAlertCompanyDescription).disabled = true;
        }
    }
    else 
    {
        //document.getElementById(EmailAlertCompanyDescription).value = "";
    }

    
    if (CriteriaList != "") {
        if (EmailAlertCriteriaName != "") {
            document.getElementById(EmailAlertCriteriaName).value = CriteriaList;
            if (EmailAlertCriteriaDescription != "") {
                document.getElementById(EmailAlertCriteriaDescription).value = CriteriaDescription;
            }
        }
        document.getElementById(EmailAlertCriteriaName).disabled = "true";
        //document.getElementById(EmailAlertCriteriaDescription).disabled = "true";
   }     
    else {
        document.getElementById(EmailAlertCriteriaName).value = "";
        //document.getElementById(EmailAlertCriteriaDescription).value = "";
    }
    $find(modalPopupExtenderID).show();
    return false;
}

//-------------------------------------------------------------------------------
// Used In Setting the email alert for Financings, FP, Stocks
// ADD by Mihai on 30.01.2009
//-------------------------------------------------------------------------------
function ChangeCompanyDescriptionForSetEmailAlertPopUp(emailAlertCompanyListBox, hdnEmailAlertCompaniesListDescription, emailAlertCompanyDescription) 
{
    var emailAlertCompanyList = document.getElementById(emailAlertCompanyListBox);
    var hdnEmailAlertCompaniesDescription = document.getElementById(hdnEmailAlertCompaniesListDescription);

    var selectedValue = 0;
    var i=0;
    for (i = 0; i < emailAlertCompanyList.length; i++) 
    {
        if (emailAlertCompanyList[i].selected == true) 
        {
            selectedValue = emailAlertCompanyList[i].value;
            break;
        }
    }

    var listsOfCompanies = hdnEmailAlertCompaniesDescription.value.split(',');
    for (i = 0; i < listsOfCompanies.length - 1; i++) 
    {
        if (listsOfCompanies[i].split('_')[0] == selectedValue) 
        {
            document.getElementById(emailAlertCompanyDescription).value = listsOfCompanies[i].split('_')[1];
        }
    }
    
}


//-------------------------------------------------------------------------------
// "Save Criteria"
// used whereever is Saving criteria for a user
// ADD Bela Gaspar
//-------------------------------------------------------------------------------
function SaveCriteria(css) {
    // if there is no pop-up already opened
    if (saveWindow == null) {
        leftVal = (screen.width - 500) / 2;
        topVal = (screen.height - 150) / 2;
        saveWindow = window.open("../Common/SaveCriteria.aspx?css=" + css, "_blank", 'width=500,height=150,left=' + leftVal + ',top=' + topVal + ',toolbar=0,resizable=0');
        return false;
    }
    else {
        saveWindow.close();
        if (document.getElementById('btnSaveCriteriaClicked').value == "1") {
            return true;
        }
        else {
            saveWindow = window.open("../Common/SaveCriteria.aspx?css=" + css, "_blank", 'width=500,height=150,left=' + leftVal + ',top=' + topVal + ',toolbar=0,resizable=0');
            return false;
        }
    }
}

//-------------------------------------------------------------------------------
// Created by Marius 09/26/08		
// used in Save Criteria List modal popup
// The one bellow is the old one
//-------------------------------------------------------------------------------
function ValidateSaveCriteriaDialog(criteriaListNameID, criteriaListDropDownID, productID) {

    var listName = trim (document.getElementById(criteriaListNameID).value);
    if (listName == "") {
        alert("Please name your Criteria before saving it");
        return false;
    }

    nameList = document.getElementById(criteriaListDropDownID); //'ctl00_cphMain_UserListsCriteriaControl_UserCompanyLists');
    var sw = false;
    for (i = 0; i < nameList.length; i++) {
        if (trim (nameList[i].text.toLowerCase()) == listName.toLowerCase()) {
            sw = true;
            var isBCCriteria = ReservedCriteria(listName);

            if (isBCCriteria != "undefined" && isBCCriteria != null && isBCCriteria == "true") 
            {
                alert('This is a reserved criteria name. Please choose another one.');
                return false;
            }
                
            var isCriteriaUsedInEmailAlert = IsCriteriaUsedInEmailAlert(productID, listName)
            if (isCriteriaUsedInEmailAlert != "undefined" && isCriteriaUsedInEmailAlert != null && isCriteriaUsedInEmailAlert == "true") {
                if (confirm('This Criteria set already exists and it is involved in at least 1 email alert.\n' +
                    'Changing the criteria will delete any alert previously saved with this criteria set.\n' +
                    'Press OK if you want to go ahead and delete the existing alerts and change the criteria\n' +
                    'set, or press Cancel and then save the criteria set under another name by using the\n' +
                    'option Save Criteria List as.')) {
                    document.getElementById(selectedCriteriaID).value = nameList[i].value;
                    return true;
                }
                else {
                    document.getElementById(selectedCriteriaID).value = "";
                    return false;
                }
            }
            else {
                if (confirm('This Criteria Name already exists.\n Are you sure you want to owerwrite it?')) {
                    document.getElementById(selectedCriteriaID).value = nameList[i].value;
                    return true;
                }
                else {
                    document.getElementById(selectedCriteriaID).value = "";
                    return false;
                }
            }
        }
    }
    if (!sw) {
        document.getElementById(selectedCriteriaID).value = "";
        return true;
    }
    //document.getElementById('CompanyListName').value = document.getElementById('CompanyListName').value;
    //document.getElementById('CompanyListDescription').value = document.getElementById('CompanyListDescription').value;
}

//-------------------------------------------------------------------------------
// Createt by Mihai on 06 April 2009
// Used in ValidateSaveDialog
// The one bellow is the old one
//-------------------------------------------------------------------------------
function IsCriteriaUsedInEmailAlert(productID, criteriaName) {
    try {
        var httpRequest = GetXmlHttpObject();

        var xmlSOAP = '<?xml version="1.0" encoding="utf-8"?>' +
         '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
         'xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> ' +
          '<soap:Body>' +
           '<IsCriteriaUsedInEmailAlert xmlns="http://tempuri.org/">' +
            '<productID>' + productID + '</productID>' +
            '<criteriaName>' + htmlEncode(criteriaName) + '</criteriaName>' +
           '</IsCriteriaUsedInEmailAlert>' +
          '</soap:Body>' +
         '</soap:Envelope>';

        // send XML document to Web server
        //httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

        httpRequest.onreadystatechange = new function() { };
        //alert(UtilitiesWSUrl);
        httpRequest.open("POST", UtilitiesWSUrl, false);

        httpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/IsCriteriaUsedInEmailAlert");
        httpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        httpRequest.send(xmlSOAP);

        if (httpRequest.status == 200) {
            text = httpRequest.responseText;
            try //Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(text);
                try {
                    return xmlDoc.getElementsByTagName("IsCriteriaUsedInEmailAlertResult")[0].text;
                }
                catch (e) {
                    alert(e.message);
                }
            }
            catch (ex) {
                try //Firefox, Mozilla, Opera, etc.
                {
                    parser = new DOMParser();
                    xmlDoc = parser.parseFromString(text, "text/xml");
                    try {
                        return xmlDoc.getElementsByTagName("IsCriteriaUsedInEmailAlertResult")[0].firstChild.nodeValue;
                    }
                    catch (e) {
                        alert(e.message);
                    }
                }
                catch (er) { alert(er.message) }
            }

        }
        else {
            alert("List of email alerts couldn't be accessed.");
        }
    }
    catch (err)
    { }
}

//-------------------------------------------------------------------------------
// Createt by Marius 09/26/08	
// Modified by Mihai on 11/03/08	
// used in Save Company List modal popup
// The one bellow is the old one
//-------------------------------------------------------------------------------
function ValidateSaveDialog(companyListNameID, nameListDropDownID, isEmailList, isPopup) 
{
    var listName = trim (document.getElementById(companyListNameID).value);
    if (listName == "") 
    {
        alert("Please name your list before saving it");
        return false;
    }

    var isBCList = SynchronAJAX(listName);

    if (isBCList != "undefined" && isBCList != null && isBCList == "true") 
    {
        if (isEmailList != "undefined" && isEmailList != null && isEmailList == true && listName == "Temporary List") 
        {
            alert('Please rename your temporary company list to set your email alert.');
        }
        else
        {
            alert('This is a reserved list name. Please choose another one.');
        }
        return false;
    }
    if (isPopup) {
        nameList = window.opener.document.getElementById(nameListDropDownID);        
    }
    else {
        nameList = document.getElementById(nameListDropDownID); //'ctl00_cphMain_UserListsCriteriaControl_UserCompanyLists');
    }
    hdnSelected = document.getElementById(hdnSelectedCompanyListID);
    exists = false;
    for (i = 0; i < nameList.length; i++) 
    {
        if (nameList[i].text.toLowerCase() == listName.toLowerCase()) {
            exists = true;
        }
        if (nameList[i].selected) {
            hdnSelected.value = nameList[i].value;
        }
    }

    if (exists) 
    {
        var isListUsedInEmailAlert = IsListUsedInEmailAlert(listName)
        if (isListUsedInEmailAlert != "undefined" && isListUsedInEmailAlert != null && isListUsedInEmailAlert == "true")
        {
            if (isEmailList != "undefined" && isEmailList != null && isEmailList == true)
            {
                if (!confirm('This list is being used for another email alert.\n Do you want to use that list to set this email alert too?'))
                {
                    return false;
                }
                else 
                {
                    hdnSelected.value = "0";
                }
            }
            else
            {
                if (!confirm('This company list already exists and it is involved in at least 1 email alert.\n' +
                        'Changing the company list will delete any alert previously saved with this company list.\n' +
                        'Press OK if you want to go ahead and delete the existing alerts and change the company\n' +
                        'list, or press Cancel and then save the company list under another name by using the\n' +
                        'option Save List as.'))
                {
                    return false;
                }
                else 
                {
                    hdnSelected.value = "0";
                }
            }
        }
        else
        {
            if (!confirm('This list already exists.\n Are you sure you want to owerwrite it?')) 
            {
                return false;
            }
            else 
            {
                hdnSelected.value = "0";
            }
        }
    }
    
    return true;

    //document.getElementById('CompanyListName').value = document.getElementById('CompanyListName').value;
    //document.getElementById('CompanyListDescription').value = document.getElementById('CompanyListDescription').value;
}

//-------------------------------------------------------------------------------
// Created by Mihai on 06 April 2009
// Used in ValidateSaveDialog
// The one bellow is the old one
//-------------------------------------------------------------------------------
function IsListUsedInEmailAlert(listName) 
{
    try 
    {
        var httpRequest = GetXmlHttpObject();

        var xmlSOAP = '<?xml version="1.0" encoding="utf-8"?>' +
         '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
         'xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> ' +
          '<soap:Body>' +
           '<IsListUsedInEmailAlert xmlns="http://tempuri.org/">' +
            '<listName>' + htmlEncode(listName) + '</listName>' +
           '</IsListUsedInEmailAlert>' +
          '</soap:Body>' +
         '</soap:Envelope>';

        // send XML document to Web server
        //httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

        httpRequest.onreadystatechange = new function() { };
        //alert(UtilitiesWSUrl);
        httpRequest.open("POST", UtilitiesWSUrl, false);

        httpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/IsListUsedInEmailAlert");
        httpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        httpRequest.send(xmlSOAP);

        if (httpRequest.status == 200) 
        {
            text = httpRequest.responseText;
            try //Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(text);
                try 
                {
                    return xmlDoc.getElementsByTagName("IsListUsedInEmailAlertResult")[0].text;
                }
                catch (e) 
                {
                    alert(e.message);
                }
            }
            catch (ex) 
            {
                try //Firefox, Mozilla, Opera, etc.
                {
                    parser = new DOMParser();
                    xmlDoc = parser.parseFromString(text, "text/xml");
                    try 
                    {
                        return xmlDoc.getElementsByTagName("IsListUsedInEmailAlertResult")[0].firstChild.nodeValue;
                    }
                    catch (e) 
                    {
                        alert(e.message);
                    }
                }
                catch (er) { alert(er.message) }
            }

        }
        else 
        {
            alert("List of email alerts couldn't be accessed.");
        }
    }
    catch (err)
    { }
}

// This checks if an email alert can be set on this company
function ValidateCPEmailAlertDialog(listName, notUser, redirectUrl) {
    var isValidList = true;
    //check login
    if (notUser) {
        document.location.href = redirectUrl;
        //alert(IsPublicCompanyProfile);
        return false;
    }

    //check number of saved alerts
    if (isValidList)
        isValidList = CheckAvailableAlerts(5, 'ModalPopupExtenderAvailableAlerts');
    if (isValidList)
        isValidList = CheckAvailableAlerts(11, 'ModalPopupExtenderAvailableAlerts');

    if (!isValidList)
        return false;
    //Archives
    hasArchivesAlert = false;
    hasBCIQAlert = false;
    if (isValidList) {
        var existsCriteriaName = CriteriaAlreadyExists(listName, 5);
        if (existsCriteriaName != -1) {
            isValidList = false;
            hasArchivesAlert = true;
        }
    }
    //Financings//Pipeline
    if (isValidList) {
        var existsCriteriaName = CompanyListAlreadyExists(listName);
        if (existsCriteriaName != -1) {
            isValidList = false;
            hasBCIQAlert = true;
        }
    }

    if (!isValidList) {
        if (hasArchivesAlert) {
            return confirm(listName + ' already exists in your archives saved search terms. Setting this email alert will also overwrite that existing saved search. Continue?');
        }
        if (hasBCIQAlert) {
            return confirm('Overwrite criteria?');
        }
    }
    else
        return true;
    //return isValidList;
}

//-------------------------------------------------------------------------------
// Created by Mihai on 07 April 2009	
// Used in Set Email Alert modal popup
//-------------------------------------------------------------------------------
function ValidateSetEmailAlertDialog(EmailAlertCompanyList, EmailAlertCriteriaName) 
{
	var listName = trim (document.getElementById(EmailAlertCompanyList).value);
	var criteriaName = trim (document.getElementById(EmailAlertCriteriaName).value);

	var isEmailAlreadySet = IsEmailAlreadySet(listName, criteriaName);
    if (isEmailAlreadySet != "undefined" && isEmailAlreadySet != null && isEmailAlreadySet == "true")
    {
        alert("An email alert already exists for this list of companies filtered by this set of criteria."); 
		return false;
    }
    return true;
}

//-------------------------------------------------------------------------------
// Createt by Mihai on 07 April 2009
// Used in ValidateSetEmailAlertDialog function
//-------------------------------------------------------------------------------
function IsEmailAlreadySet(listName, criteriaName)
{
    try 
    {
        var httpRequest = GetXmlHttpObject();

        var xmlSOAP = '<?xml version="1.0" encoding="utf-8"?>' +
         '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
         'xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> ' +
          '<soap:Body>' +
           '<IsEmailAlreadySet xmlns="http://tempuri.org/">' +
            '<listName>' + htmlEncode(listName) + '</listName>' +
		    '<criteriaName>' + htmlEncode(criteriaName) + '</criteriaName>' +
           '</IsEmailAlreadySet>' +
          '</soap:Body>' +
         '</soap:Envelope>';

        // send XML document to Web server
        //httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

        httpRequest.onreadystatechange = new function() { };
        //alert(UtilitiesWSUrl);
        httpRequest.open("POST", UtilitiesWSUrl, false);

        httpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/IsEmailAlreadySet");
        httpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        httpRequest.send(xmlSOAP);

        if (httpRequest.status == 200) 
        {
            text = httpRequest.responseText;
            try //Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(text);
                try 
                {
                    return xmlDoc.getElementsByTagName("IsEmailAlreadySetResult")[0].text;
                }
                catch (e) 
                {
                    alert(e.message);
                }
            }
            catch (ex) 
            {
                try //Firefox, Mozilla, Opera, etc.
                {
                    parser = new DOMParser();
                    xmlDoc = parser.parseFromString(text, "text/xml");
                    try 
                    {
                        return xmlDoc.getElementsByTagName("IsEmailAlreadySetResult")[0].firstChild.nodeValue;
                    }
                    catch (e) 
                    {
                        alert(e.message);
                    }
                }
                catch (er) { alert(er.message) }
            }
        }
        else 
        {
            alert("List of email alerts couldn't be accessed.");
        }
    }
    catch (err)
    { }
}

function SaveNewCompanyInfo(txtCompanyListID, txtCompanyListDescriptionID) {

    newCompanyList = document.getElementById(hdnNewCompanyListID);
    newCompanyListDescription = document.getElementById(hdnNewCompanyListDescriptionID);

    txtCompanyList = document.getElementById(txtCompanyListID);
    txtCompanyListDescription = document.getElementById(txtCompanyListDescriptionID);

    if (newCompanyList != null) {
        newCompanyList.value = txtCompanyList.value;
    }
    if (newCompanyListDescription != null) {
        newCompanyListDescription.value = txtCompanyListDescription.value;
    }
    removeDiv();
}
//-------------------------------------------------------------------------------
// Added by Silvia 3/10/2009
// When the Submit button is clicked to save company list from myBiocentury
// we look if the name is reserved or it already exists
//-------------------------------------------------------------------------------
function ValidateSaveDialogMyBiocentury(txtListNameID) {
    var listName = trim (document.getElementById(txtListNameID).value);
    if (listName == "") {
        alert("Please name your list before saving it");
        return false;
    }

    var isReserved = CompanyListAlreadyExists(listName);

    if (isReserved != "undefined" && isReserved != null) {
        switch (isReserved) {
            case "0":
                alert('This is a reserved list name. Please choose another one.');
                return false;
            case "-1":
                document.getElementById(hdnSelectedCompanyListID).value = "";
                return true;
            default:
                if (confirm('This list already exists.\n Are you sure you want to owerwrite it?')) {
                    document.getElementById(hdnSelectedCompanyListID).value = isReserved;
                    return true;
                }
                else {
                    return false;
                }
        }
    }

    document.getElementById(selectedCriteriaID).value = "";
    return false;
}

// Returns if a company list with the same name
// already exists in the database
function CompanyListAlreadyExists(listName) {
    try {
        var httpRequest = GetXmlHttpObject();

        var xmlSOAP = '<?xml version="1.0" encoding="utf-8"?>' +
         '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
         'xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> ' +
          '<soap:Body>' +
           '<ExistsListName xmlns="http://tempuri.org/">' +
            '<listName>' + htmlEncode(listName) + '</listName>' +
           '</ExistsListName>' +
          '</soap:Body>' +
         '</soap:Envelope>';

        // send XML document to Web server
        httpRequest.onreadystatechange = new function() { };
        
        httpRequest.open("POST", UtilitiesWSUrl, false);

        httpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/ExistsListName");
        httpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        httpRequest.send(xmlSOAP);

        if (httpRequest.status == 200) {
            text = httpRequest.responseText;
            try //Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(text);
                try {
                    return xmlDoc.getElementsByTagName("ExistsListNameResult")[0].text;
                }
                catch (e) {
                    alert(e.message);
                }
            }
            catch (ex) {
                try //Firefox, Mozilla, Opera, etc.
                {
                    parser = new DOMParser();
                    xmlDoc = parser.parseFromString(text, "text/xml");
                    try {
                        return xmlDoc.getElementsByTagName("ExistsListNameResult")[0].firstChild.nodeValue;
                    }
                    catch (e) {
                        alert(e.message);
                    }
                }
                catch (er) { alert(er.message) }
            }

        }
        else {
            alert("The list name couldn't be accessed.");
        }
    }
    catch (err)
    { }
}

// Returns if a company list with the same name
// already exists in the database
function CriteriaAlreadyExists(criteriaName, productID) {
    try {
        var httpRequest = GetXmlHttpObject();

        var xmlSOAP = '<?xml version="1.0" encoding="utf-8"?>' +
         '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
         'xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> ' +
          '<soap:Body>' +
           '<ExistsCriteriaName xmlns="http://tempuri.org/">' +
            '<criteriaName>' + htmlEncode(criteriaName) + '</criteriaName>' +
            '<productID>' + productID + '</productID>' +
           '</ExistsCriteriaName>' +
          '</soap:Body>' +
         '</soap:Envelope>';

        // send XML document to Web server
        httpRequest.onreadystatechange = new function() { };

        httpRequest.open("POST", UtilitiesWSUrl, false);

        httpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/ExistsCriteriaName");
        httpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        httpRequest.send(xmlSOAP);

        if (httpRequest.status == 200) {
            text = httpRequest.responseText;
            try //Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(text);
                try {
                    return xmlDoc.getElementsByTagName("ExistsCriteriaNameResult")[0].text;
                }
                catch (e) {
                    alert(e.message);
                }
            }
            catch (ex) {
                try //Firefox, Mozilla, Opera, etc.
                {
                    parser = new DOMParser();
                    xmlDoc = parser.parseFromString(text, "text/xml");
                    try {
                        return xmlDoc.getElementsByTagName("ExistsCriteriaNameResult")[0].firstChild.nodeValue;
                    }
                    catch (e) {
                        alert(e.message);
                    }
                }
                catch (er) { alert(er.message) }
            }

        }
        else {
            alert("The criteria names couldn't be accessed.");
        }
    }
    catch (err)
    { }
}

function ReselectListName(listID, nameListDropDownID) {

    //window.opener.location.href = window.opener.location.href;
    var nameList = window.opener.document.getElementById(window.opener.window.nameListDropDownID); //window.opener.document.getElementById(nameListDropDownID);
    for (i = 0; i < nameList.options.length; i++) {      
        if (nameList.options[i].value == listID) {
            window.opener.ChangeSelectIndex(i);            
            break;
        }
    
         
    }
}

function closeOut() {
    var flag = false;
    try {
        flag = (screenTop > 9999);
    }
    catch (e) {      
        flag = (screenY > 9999);
    }

    if (flag) {
        var changedList = document.getElementById(hdnChangedListID).value;
        if (changedList == "true") {
            window.opener.location.href = window.opener.location.href;
        }
    }
}


function CloseWindow() {
    window.opener.location.href = window.opener.location.href; 
    window.close();
}

//-------------------------------------------------------------------------------
function SynchronAJAX(listName) 
{
    try 
    {
        var httpRequest = GetXmlHttpObject();

        var xmlSOAP = '<?xml version="1.0" encoding="utf-8"?>' +
         '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
         'xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> ' +
          '<soap:Body>' +
           '<IsReservedListName xmlns="http://tempuri.org/">' +
            '<listName>' + htmlEncode(listName) + '</listName>' +
           '</IsReservedListName>' +
          '</soap:Body>' +
         '</soap:Envelope>';



        // send XML document to Web server
        //httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

        httpRequest.onreadystatechange = new function() { };
        //alert(UtilitiesWSUrl);
        httpRequest.open("POST", UtilitiesWSUrl, false);

        httpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/IsReservedListName");
        httpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        httpRequest.send(xmlSOAP);

        if (httpRequest.status == 200) 
        {
            text = httpRequest.responseText;
            try //Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(text);
                try 
                {
                    return xmlDoc.getElementsByTagName("IsReservedListNameResult")[0].text;
                }
                catch (e) 
                {
                    alert(e.message);
                }
            }
            catch (ex) 
            {
                try //Firefox, Mozilla, Opera, etc.
                {
                    parser = new DOMParser();
                    xmlDoc = parser.parseFromString(text, "text/xml");
                    try 
                    {
                        return xmlDoc.getElementsByTagName("IsReservedListNameResult")[0].firstChild.nodeValue;
                    }
                    catch (e) 
                    {
                        alert(e.message);
                    }
                }
                catch (er) { alert(er.message) }
            }
        }
        else 
        {
            alert("BC List couldn't be accessed.");
        }
    }
    catch (err) 
    { }
}

//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
function ReservedCriteria(criteriaName) {
    try {
        var httpRequest = GetXmlHttpObject();

        var xmlSOAP = '<?xml version="1.0" encoding="utf-8"?>' +
         '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
         'xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> ' +
          '<soap:Body>' +
           '<IsReservedCriteriaSet xmlns="http://tempuri.org/">' +
            '<criteriaSet>' + htmlEncode(criteriaName) + '</criteriaSet>' +
            '<productID>' + productID + '</productID>' +
           '</IsReservedCriteriaSet>' +
          '</soap:Body>' +
         '</soap:Envelope>';



        // send XML document to Web server
        //httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

        httpRequest.onreadystatechange = new function() { };
        //alert(UtilitiesWSUrl);
        httpRequest.open("POST", UtilitiesWSUrl, false);

        httpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/IsReservedCriteriaSet");
        httpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        httpRequest.send(xmlSOAP);

        if (httpRequest.status == 200) {
            text = httpRequest.responseText;
            try //Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(text);
                try {
                    return xmlDoc.getElementsByTagName("IsReservedCriteriaSetResult")[0].text;
                }
                catch (e) {
                    alert(e.message);
                }
            }
            catch (ex) {
                try //Firefox, Mozilla, Opera, etc.
                {
                    parser = new DOMParser();
                    xmlDoc = parser.parseFromString(text, "text/xml");
                    try {
                        return xmlDoc.getElementsByTagName("IsReservedCriteriaSetResult")[0].firstChild.nodeValue;
                    }
                    catch (e) {
                        alert(e.message);
                    }
                }
                catch (er) { alert(er.message) }
            }

        }
        else {
            alert("BC criterion couldn't be accessed.");
        }
    }
    catch (err)
    { }
}


//-------------------------------------------------------------------------------
// OnTextBoxFocus
// Add by Bela Gaspar 11/14/2006
// Used in Market Cap/Tier page (MarketCapTierUniverse.xsl)
//-------------------------------------------------------------------------------
function OnTextBoxFocus(theChart) {
    if (theChart == 0 && document.getElementById('UniverseID=901').checked) {
        document.getElementById('UniverseID=901').checked = false;
        selectAll(document.getElementById('UniverseID=901'), 0);
    }
}

//-------------------------------------------------------------------------------
// SetForDisplay - returns a formatted string for use in displaying summary information about a widget
//changed by Eugen 08.02.2008 - does not display empty or null values (PriceVolume filter)
//-------------------------------------------------------------------------------
function SetForDisplay(anArray) {
    // if "anArray" is string, then make it an Array
    if (!(anArray instanceof Array))
        anArray = anArray.split('_');

    var retval = "";
    for (var i = 0; i < anArray.length; i++) {
        if (anArray[i] != "" && anArray[i] != null) {
            retval += (i > 0) ? "<br />" : "";
            retval += "&nbsp;&nbsp;&#149;&nbsp;" + anArray[i];

        }
    }
    return retval;
}

//-------------------------------------------------------------------------------
// selectAll(check, chart)
// MODIFIED - Bela Gaspar - 05/29/2006
// If a parent check-box is selected, then select ALL childs
// check	= checkbox element
// chart:	0 - Reports,
//			1 - Charts,
//			2 - Search pages
//-------------------------------------------------------------------------------
function selectAll(check, chart) {
    document.getElementById('hasChanged').value = 'true';

    // for Charts
    if (chart == "1")
        return;

    var theCheckBoxValue = check.id.split("=")[1];

    // for Reports
    if (chart != 2) {
        //for all checkboxes which belongs to table element with id = theCheckBoxValue
        if (document.getElementById(theCheckBoxValue) != null &&
			document.getElementById(theCheckBoxValue).getElementsByTagName("input") != null) {
            for (var i = 0; i < document.getElementById(theCheckBoxValue).getElementsByTagName("input").length; i++) {
                if (document.getElementById(theCheckBoxValue).getElementsByTagName("input")[i].type &&
					document.getElementById(theCheckBoxValue).getElementsByTagName("input")[i].type == 'checkbox' &&
					document.getElementById(theCheckBoxValue).getElementsByTagName("input")[i].style.display != 'none') {
                    document.getElementById(theCheckBoxValue).getElementsByTagName("input")[i].checked = check.checked;
                }
            }
        }
    }
    // for Search
    else {
        for (var i = 0; i < document.getElementsByName(check.id).length; i++) {
            if (document.getElementsByName(check.id)[i].type &&
				document.getElementsByName(check.id)[i].type == 'checkbox' &&
				document.getElementsByName(check.id)[i].style.display != 'none') {
                document.getElementsByName(check.id)[i].checked = check.checked;
            }
        }
    }
}

//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
function DigitGrouping(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

//-------------------------------------------------------------------------------
// ToggleParent(check, chart)
// MODIFIED - Bela Gaspar - 05/26/2006
// MODIFIED - ROST -10/02/06
// If a parent check-box is selected, then select its childs
// check	= checkbox element
// chart	= 0 - Reports, 1 - Charts
// message
//-------------------------------------------------------------------------------
function ToggleParent(check, chart) {
    document.getElementById('hasChanged').value = 'true';

    if (chart == "1") { ToggleImageInChart(check, arguments[2]); return; }

    if (check.name != "" && document.getElementById(check.name) != null) {
        document.getElementById(check.name).checked = checkChilds(check.name) && check.checked;
        ToggleParent(document.getElementById(check.name));
    }

}

//-------------------------------------------------------------------------------
// checkChilds(name, chart)
// MODIFIED - Bela Gaspar - 05/26/2006
// Check if all childs of a parent are selected
// name		= checkbox parent element name
// check	= checkbox element
//-------------------------------------------------------------------------------
function checkChilds(name) {
    var allChecked = true;
    for (var i = 0; i < document.getElementsByName(name).length; i++) {
        if (document.getElementsByName(name)[i] != document.getElementById(name) && !document.getElementsByName(name)[i].checked)
            allChecked = false;
    }
    return allChecked;
}

//-------------------------------------------------------------------------------
// Confirm changes for filters
// EDIT - Marius Paltanea - 01/08/2009
//-------------------------------------------------------------------------------
function confirmChanges(trigger) {
    var hid = document.getElementById('hasChanged');
    if (hid != null && hid.value == 'true') {
        if (confirm('Submit your changes?')) {
            if (saveChangesButtonID != null) {
                document.getElementById(originalTriggerHiddenID).value = trigger.id;
                clickButton(saveChangesButtonID);
                return true;
            }
        }
        else {
            return true;
        }
    }
    return true;
}
//-------------------------------------------------------------------------------
// Confirm changes for Select Company by Name and Select Company By Criteria used in FindCompanies.aspx in check(cb)
// and in CompanySelection.ascx on the btnCancel
// Silvia Tanase - 02/18/2009
//-------------------------------------------------------------------------------
function confirmChangesSelect(trigger) {
    var hid = document.getElementById('hasChanged');
    if (hid != null && hid.value == 'true') {
        if (confirm('Submit your changes?')) {
            if (saveChangesButtonID != null) {
                document.getElementById(originalTriggerHiddenID).value = trigger.id;
                clickButton(saveChangesButtonID);
                return true;
            }
        }
        else {
            return false;
        }
    }
    return false;
}


//-------------------------------------------------------------------------------
// Collapse - Expand Filters
// ADD - Bela Gaspar - 03/31/2006
// Used in Create List; Reports; Charts
//-------------------------------------------------------------------------------
function CollapseExpand(idDiv, param) {
    //param - optional - normal behavior
    //		is something - always visible
    //if present the div is made visible always
    var len = idDiv.split('_').length;
    var idEc = idDiv.split('_')[len - 1] + '_ec';
    if (document.getElementById(idDiv).className == "DivVisible") {
        if (param == null || param == false) {
            // make it hidden
            document.getElementById(idEc).src = document.getElementById(idEc).src.replace('collapse', 'expand');
            document.getElementById(idEc).title = document.getElementById(idEc).title.replace('Collapse', 'Expand');
            document.getElementById(idDiv).className = "DivHidden";
        }
        else {
            // make it visible
            document.getElementById(idEc).src = document.getElementById(idEc).src.replace('expand', 'collapse');
            document.getElementById(idEc).title = document.getElementById(idEc).title.replace('Expand', 'Collapse');
            document.getElementById(idDiv).className = "DivVisible";
        }
    }
    else {
        if (param == null || param == true) {
            // make it visible
            document.getElementById(idEc).src = document.getElementById(idEc).src.replace('expand', 'collapse');
            document.getElementById(idEc).title = document.getElementById(idEc).title.replace('Expand', 'Collapse');
            document.getElementById(idDiv).className = "DivVisible";
        }
        else {
            // make it hidden
            document.getElementById(idEc).src = document.getElementById(idEc).src.replace('collapse', 'expand');
            document.getElementById(idEc).title = document.getElementById(idEc).title.replace('Collapse', 'Expand');
            document.getElementById(idDiv).className = "DivHidden";
        }
    }
}


//-------------------------------------------------------------------------------
// CollapseExpandSection
// Done by Bela: 1/16/2009
// Changed by Bela (5/20/2009) - replace onclick with href; replace input param 'this' with the name of Section
//-------------------------------------------------------------------------------
function CollapseExpandSection(name) 
{
    //var name = a.id.split('_')[0];
    var As = document.getElementsByName(name);
    for (var i = 0; i < As.length; i++) 
    {
        if (document.getElementById(name + '_ec').attributes['name'].value == 'Collapse') 
        {
            if (document.getElementById('ctl00_cphMain_lbl' + As[i].id.split('_')[0] + 'Summary').style.color == '' ||
                document.getElementById('ctl00_cphMain_lbl' + As[i].id.split('_')[0] + 'Summary').style.color == '#000000') 
                {
                    eval(As[i].attributes["href"].value);                
                }
        }
        else
            eval(As[i].attributes["href"].value.replace(');', ',1);'));
    }

    if (document.getElementById(name + '_ec').attributes['name'].value == 'Collapse') {
        document.getElementById(name + '_ec').attributes['name'].value = 'Expand';
        document.getElementById(name + '_ec').title = 'Expand Section';
    }
    else {
        document.getElementById(name + '_ec').attributes['name'].value = 'Collapse';
        document.getElementById(name + '_ec').title = 'Collapse Section';
    }
}

//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
function CollapseExpandAll(a, labelName) {
    var name = a.id.split('_')[0];
    var As = document.getElementsByName(name);
    for (var i = 0; i < As.length; i++) {
        if (document.getElementById(name + '_ec').title == 'Collapse All')
            eval(As[i].attributes["onclick"].value);
        else
            eval(As[i].attributes["onclick"].value.replace(');', ',1);'));

    }
    if (document.getElementById(name + '_ec').title == 'Collapse All') {
        document.getElementById(name + '_ec').src = document.getElementById(name + '_ec').src.replace('collapse', 'expand');
        document.getElementById(name + '_ec').title = 'Expand All';
        if (labelName != null)
            document.getElementById(name + '_ec_a').innerHTML = labelName;
        else
            document.getElementById(name + '_ec_a').innerHTML = "Expand All";
    }
    else {
        document.getElementById(name + '_ec').src = document.getElementById(name + '_ec').src.replace('expand', 'collapse');
        document.getElementById(name + '_ec').title = 'Collapse All';
        if (labelName != null)
            document.getElementById(name + '_ec_a').innerHTML = labelName;
        else
            document.getElementById(name + '_ec_a').innerHTML = "Collapse All";
    }
}

//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
function ParentHasChilds(parentNode) {
    if (document.getElementsByName(parentNode).length > 1)
        return true;
    else
        return false;
}

//-------------------------------------------------------------------------------
// ReportCheckRecursiveChildsSelected(name)
// ADD - Bela Gaspar - 05/26/2006
// Recursive find parents node selection using input tag attribute: "name" 
// Build m_SelectionSet, m_SummarySet, m_SelectionArray
//-------------------------------------------------------------------------------
function ReportCheckRecursiveChildsSelected(name) {
    for (var i = 0; i < document.getElementsByName(name).length; i++) {
        if (document.getElementsByName(name)[i] != document.getElementById(name)) {
            if (!document.getElementsByName(name)[i].checked)
                ReportCheckRecursiveChildsSelected(document.getElementsByName(name)[i].id)
            else {
                m_SelectionSet += "<r " + document.getElementsByName(name)[i].id.split("=").join("=\"") + "\"\/>";
                m_SummarySet[m_SummarySet.length] = GetInnerText_IE_FireFox(document.getElementById("s_" + document.getElementsByName(name)[i].id));
                m_SelectionArray[m_SelectionArray.length] = document.getElementsByName(name)[i].id;
            }
        }
    }
}

//-------------------------------------------------------------------------------
// ChartShouldBeChecked(node)
// ADD - Bela Gaspar - 09/26/2006
// Recursive find parents node selection using input tag attribute: "name" 
// This method must be used with SetSelectionSummaryArray
//-------------------------------------------------------------------------------
function ChartShouldBeChecked(node) {
    if (document.getElementById(node).checked) {
        m_Array[m_Array.length] = node;
        return true;
    }

    if (document.getElementsByName(node).length == 1)
        return false;

    var thisNodeShouldBeChecked = true;

    // for every child of the parent
    for (var i = 0; i < document.getElementsByName(node).length; i++) {
        if (document.getElementsByName(node)[i] != document.getElementById(node)) {
            if (!ChartShouldBeChecked(document.getElementsByName(node)[i].id)) {
                thisNodeShouldBeChecked = false;
            }
        }
    }
    if (thisNodeShouldBeChecked) {
        // remove parent childrens from the list
        // convert array to string to remove items
        var aStr = "," + m_Array.join(',') + ",";

        for (var i = 0; i < document.getElementsByName(node).length; i++) {
            if (document.getElementsByName(node)[i] != document.getElementById(node)) {
                if (aStr.indexOf(document.getElementsByName(node)[i].id) > -1) {
                    var str = "," + document.getElementsByName(node)[i].id + ",";
                    var aStrTemp = aStr.split(str)[0] + "," + aStr.split(str)[1];
                    aStr = aStrTemp;
                }
            }
        }
        if (aStr == ",")
            aStr = "";
        else
            aStr = aStr.substring(1, aStr.length - 1);

        // convert string to array
        if (aStr == "")
            m_Array = [];
        else {
            m_Array = [];
            m_Array = aStr.split(',');
        }

        // add node to list
        m_Array[m_Array.length] = node;
    }
    return thisNodeShouldBeChecked;
}


//-------------------------------------------------------------------------------
// SetSelectionSummaryArray()
// ADD - Bela Gaspar - 09/26/2006
// Descr: Build m_SelectionSet, m_SummarySet, m_SelectionArray USING m_Array from ChartShouldBeChecked
// This method must be used with ChartShouldBeChecked
//-------------------------------------------------------------------------------
function SetSelectionSummaryArray() {
    if (m_Array.length == 1 && m_Array[0] == 'UniverseID=901') {
        m_SummarySet[m_SummarySet.length] = GetInnerText_IE_FireFox(document.getElementById("s_UniverseID=901"));
    }
    else
        for (var i = 0; i < m_Array.length; i++) {
        m_SelectionSet += "<r " + m_Array[i].split("=").join("=\"") + "\"\/>";
        m_SummarySet[m_SummarySet.length] = GetInnerText_IE_FireFox(document.getElementById("s_" + m_Array[i]));
        m_SelectionArray[m_SelectionArray.length] = m_Array[i];
    }
}


//-------------------------------------------------------------------------------
// ADD - Bela Gaspar - 07/25/2006
// Modified by Rostislav - 25/10/2006
// Descr: Reset the left pane on the Charts.aspx page
// Available in Financings\Charts.aspx, FinancialPerformance\Charts.aspx, Pipeline\Charts.aspx, Stocks\Charts.aspx
// Modified: Eugen - 07/28/2006
// Available in all Left Frames
// Arguments			type 0 - Reports
//							 1 - Charts
//							 2 - Company
//							 3 - Database
//-------------------------------------------------------------------------------
function resetAllLeftFrame(type) {
    if (confirm("This will reset all. Continue?")) {
        var _tempLocation = document.location;
        document.location.search = "";

        for (i = 0; i < document.forms.length; i++)
            document.forms[i].reset();

        var _content = "";
        switch (type) {
            case 0: _content = "ContentReports.aspx"; break;
            case 1: _content = "ContentCharts.aspx"; break;
            case 2: _content = "ContentCompanyProfile.aspx"; break;
            case 3:
                document.location.href = _tempLocation.href;
                _content = "ContentDatabase.aspx" + _tempLocation.search;
                break;
            default: _content = "ContentReports.aspx";
        }
        top.frames[2].document.location.href = _content;
    }

    return true;
}

//-------------------------------------------------------------------------------
// ADD - Marcu Paul - 07/25/2008
// Descr: Asks the user to confirm the update of the "left frames"
// Available in Financings\Charts.aspx, FinancialPerformance\Charts.aspx, Pipeline\Charts.aspx, Stocks\Charts.aspx
// invokeSetWidth - if true invokes the setWidth function
//-------------------------------------------------------------------------------
function confirmReset(invokeSetWidth, clearSelectList) {
    var result = confirm('This will reset all. Continue?');
    if (result) {
        //call the set width function
        //with the optional parameter set to true (actually it can be any value)
        if (invokeSetWidth) {
            setWidth(null, null, true);
        }
        
        ResetAllFilters();          

        //if we specified the second parameter we clear the
        //select 
//        if (clearSelectList != undefined) {
            //clear the series list
//            var seriesList = document.getElementById('Select_Series');
//            for (var idx = 0; idx < seriesList.length; idx++) {
//                seriesList.remove(idx);
//            }

//            //clear the categories list
//            var categoriesList = document.getElementById('Select_Categories');
//            for (var idx = 0; idx < categoriesList.length; idx++) {
//                categoriesList.remove(idx);
//            }

//            //clear the flip x axis checkbox
//            var cbFlipAxis = document.getElementById("cbTranspose");
//            cbFlipAxis.checked = false;
//        }
    }
    return result;
}
function ResetAllFilters() {   
    //reset the other filters like Regions BusinessCategory etc
    //first check is the give element exists
    if (document.getElementById("Region") != null) {
        HideFilterLabels("Region");
    }
    if (document.getElementById("BusinessCategory") != null) {
        HideFilterLabels("BusinessCategory");
    }
    if (document.getElementById("DevelopmentStatus") != null) {
        HideFilterLabels("DevelopmentStatus");
    }
    if (document.getElementById("ListingStatus") != null) {
        HideFilterLabels("ListingStatus");
    }
    if (document.getElementById("FinancingType") != null) {
        HideFilterLabels("FinancingType");
    }
    if (document.getElementById("FinancingDate") != null) {
        HideFilterLabels("FinancingDate");
    }
    if (document.getElementById("AmountRaised") != null) {
        HideFilterLabels("AmountRaised");
    }
    if (document.getElementById("MarketCapTier") != null) {
        HideFilterLabels("MarketCapTier");
    }

    if (document.getElementById("YearFounded") != null) {
        HideFilterLabels("YearFounded");
    }
    if (document.getElementById("PartnerStatus") != null) {
        HideFilterLabels("PartnerStatus");
    }    
    
    //applicable for financings
    if (document.getElementById("FinancingType") != null) {
        HideFilterLabels("FinancingType");
    }
    if (document.getElementById("AmountRaised") != null) {
        HideFilterLabels("AmountRaised");
    }
    if (document.getElementById("FinancingDate") != null) {
        HideFilterLabels("FinancingDate");
    }

    //applicable for pipeline
    if (document.getElementById("NumberofCompounds") != null) {
        HideFilterLabels("NumberofCompounds");
    }
    if (document.getElementById("LicensedUnlicensed") != null) {
        HideFilterLabels("LicensedUnlicensed");
    }
    if (document.getElementById("ProductName") != null) {
        HideFilterLabels("ProductName");
    }
    if (document.getElementById("ProductDescription") != null) {
        HideFilterLabels("ProductDescription");
    }
    if (document.getElementById("MolecularTarget") != null) {
        HideFilterLabels("MolecularTarget");
    }
    if (document.getElementById("MechanismofAction") != null) {
        HideFilterLabels("MechanismofAction");
    }
    if (document.getElementById("DiseaseClass") != null) {
        HideFilterLabels("DiseaseClass");
    }
    if (document.getElementById("PhaseofDevelopment") != null) {
        HideFilterLabels("PhaseofDevelopment");
    }
    if (document.getElementById("Milestone") != null) {
        HideFilterLabels("Milestone");
    }


    //for chart settings
    if (document.getElementById("ChartSettings") != null) {
        HideFilterLabels("ChartSettings");
    }

    //applicable for finanacing performance
    if (document.getElementById("StockExchange")) {
        HideFilterLabels("StockExchange");
    }
    if (document.getElementById("FinancialStatements")) {
        HideFilterLabels("FinancialStatements");
    }
    if (document.getElementById("CAGR")) {
        HideFilterLabels("CAGR");
    }
    if (document.getElementById("FinancialMetrics")) {
        HideFilterLabels("FinancialMetrics");
    }
    if (document.getElementById("FinancialPeriods")) {
        HideFilterLabels("FinancialPeriods");
    }

    //applicable for stocks
    if (document.getElementById("PriceVolume") != null) {
        HideFilterLabels("PriceVolume");
    }     
}
//-------------------------------------------------------------------------------
// ADD - Marcu Paul-Robert - 07/31/2008
// Descr: Hides all expanded filter nodes (Regions Business Category, Market cap Tier etc)
// Arguments			divID -the ID of the div
//-------------------------------------------------------------------------------
function HideFilterLabels(idDiv) {
    //if the div is visible the hide it.
    if (document.getElementById(idDiv).className == "DivVisible") {
        // make it hidden
        document.getElementById(idDiv + '_ec').src = document.getElementById(idDiv + '_ec').src.replace('collapse', 'expand');
        document.getElementById(idDiv + '_ec').title = document.getElementById(idDiv + '_ec').title.replace('Collapse', 'Expand');
        document.getElementById(idDiv).className = "DivHidden";
        if (document.getElementById('ctl00_cphMain_lbl' + idDiv + 'Summary') != null) {
            //change the color of the label with the summary: only in company analyst
            document.getElementById('ctl00_cphMain_lbl' + idDiv + 'Summary').style.color = ''
        }
    }
}
//-------------------------------------------------------------------------------
// ADD - Mihai Rotar - 01/09/2008
// Descr: Reset the right pane to the initial Content
// Used in Save Criteria Dropdown List when the item selected is changed
// Arguments			type 0 - Reports
//							 1 - Charts
//							 2 - Company
//							 3 - Database
//-------------------------------------------------------------------------------

function resetAllRightFrame(type) {
    var _content = "";
    switch (type) {
        case 0: _content = "ContentReports.aspx"; break;
        case 1: _content = "ContentCharts.aspx"; break;
        case 2: _content = "ContentCompanyProfile.aspx"; break;
        case 3:
            document.location.href = _tempLocation.href;
            _content = "ContentDatabase.aspx" + _tempLocation.search;
            break;
        default: _content = "ContentReports.aspx";
    }
    return true;
}

//-------------------------------------------------------------------------------
// ADD - Bela Gaspar - 09/21/2006
// Descr: set link Disable or Enable
//		theName			- element id;
//		the_href		- element href; by default this should be "#"
//		the_onclick		- element onclick, if exist, else ""
//		the_IsDisable	- if element should be Disabled
//-------------------------------------------------------------------------------
function SetLinkDisable(theName, the_href, the_onclick, the_IsDisable) {
    // if should be Disabled
    if (the_IsDisable == true) {
        document.getElementById(theName).disabled = true;
        document.getElementById(theName).removeAttribute('href');
        document.getElementById(theName).onclick = null;
    }
    // if should be Enabled
    else {
        document.getElementById(theName).disabled = false;
        document.getElementById(theName).setAttribute('href', the_href);
        if (the_onclick != '') {
            document.getElementById(theName).onclick = function() { eval(the_onclick); }
        }
    }
}





//-----------------------------------------------------------------------------
//ADD- Rost 29/09/06
//Desc: Togle checked and unchecked images
//Used in Financing, Charts, when Charts=0
//		img - imagine
//     elem -checkbox parent 
//-----------------------------------------------------------------------------
function ChangeChartImages(img, elem) {
    var imgValue = elem.id.split("=")[1];
    if (document.getElementById(imgValue) != null &&
			document.getElementById(imgValue).getElementsByTagName("input") != null) {
        for (var i = 0; i < document.getElementById(imgValue).getElementsByTagName("img").length; i++) {
            if (img.title == "Select All") {
                document.getElementById(imgValue).getElementsByTagName("img")[i].src = "../Images/icon_uncheck.gif";
                document.getElementById(imgValue).getElementsByTagName("img")[i].title = "Deselect All";
            }
            else {
                document.getElementById(imgValue).getElementsByTagName("img")[i].src = "../Images/icon_check.gif";
                document.getElementById(imgValue).getElementsByTagName("img")[i].title = "Select All";
            }
        }
    }
}


//-------------------------------------------------------------------------
//ADD- Rost 09/29/2006
//Desc: Togle image if all childs are selected or vice versa
//Used in Financing, Charts, when Charts=0
//     elem -checkbox parent 
//-------------------------------------------------------------------------
function ToggleImageInChart(elem) {
    document.getElementById('hasChanged').value = 'true';

    if (elem.attributes['name'].value != "" && document.getElementById(elem.attributes['name'].value) != null && document.getElementById("img_Select_" + elem.attributes['name'].value) != null) {
        if (checkChilds(elem.attributes['name'].value)) {
            document.getElementById("img_Select_" + elem.attributes['name'].value).src = "../Images/icon_uncheck.gif";
            document.getElementById("img_Select_" + elem.attributes['name'].value).title = (arguments[1] != null) ? "Deselect All " + arguments[1] : "Deselect All";
        }
        else {
            document.getElementById("img_Select_" + elem.attributes['name'].value).src = "../Images/icon_check.gif";
            document.getElementById("img_Select_" + elem.attributes['name'].value).title = (arguments[1] != null) ? "Select All " + arguments[1] : "Select All";
        }

    }
}


//-------------------------------------------------------------------------------
// ADD - Bela Gaspar - 10/06/2006
// Descr: return innerText of theObject for IE or
//		  textContent of theObject for FireFox
//-------------------------------------------------------------------------------
function GetInnerText_IE_FireFox(theObject) {
    aStr = "";
    if (document.all) {// IE
        aStr = theObject.innerText;
    }
    else {// FireFox
        aStr = theObject.textContent;
    }
    return aStr;
}


//-------------------------------------------------------------------------------
// ADD - Bela Gaspar - 10/06/2006
// Descr: set innerText of theObject for IE or
//		  textContent of theObject for FireFox
//-------------------------------------------------------------------------------
function SetInnerText_IE_FireFox(theObject, theText) {
    if (document.all) {// IE
        theObject.innerText = theText;
    }
    else {// FireFox
        theObject.textContent = theText;
    }
}

//-------------------------------------------------------------------------------------
// Add Rost 10/13/06
// Descr enable/disable links View Selected Item/ View All
// Used in Financing, Pipeline- Display Table
//		obj - link element
//		disable - true - disable link
//				  false - enable link
//------------------------------------------------------------------------------------ 	
function DisableEnableAnchor(obj, disable) {
    if (obj != null) {
        if (disable == "true") {
            obj.onclick = null;
            obj.removeAttribute('onclick');
            obj.disabled = true;
            obj.style.color = "gray";
        }
        else {
            if (document.all)
                eval(obj.id + '.onclick =function() {' + obj.onclick_back + ';}');
            else
                obj.setAttribute('onclick', obj.getAttribute("onclick_back"));

            obj.disabled = false;
            obj.style.color = "black";
        }
    }
}


//var counter = 0;


// Get the checkboxes inside the Gridview which is part of the template column
function GetChildCheckBoxCount(gridClientID) {
    if (checkBoxCount == 0) {
        //var targetBaseControl = document.getElementById(gridClientID);

        var elements = document.getElementsByName("cbAll");

//        for (i = 0; i < elements.length; i++) {
//            //            if (IsCheckBox(elements[i]) && IsMatch(elements[i].id, gridClientID)) 
//            checkBoxCount++;

        //}
        checkBoxCount = elements.length;
    }
    return parseInt(checkBoxCount);
}

function CheckChild(checkBox, checkAllCheckBoxID, gridClientID, firstId, secondId, firstIDsHiddenID, secondIDsHiddenID) {
    var checkBoxCount = GetChildCheckBoxCount(gridClientID);
    var isChecked = checkBox.checked;
    firstIDsSelected = document.getElementById(firstIDsHiddenID).value;
    if (secondIDsHiddenID != null) {
        secondIDsSelected = document.getElementById(secondIDsHiddenID).value;
    }

    if (isChecked) 
    {
        if (counter < checkBoxCount) 
        {
            counter++;
        }
        //add the id to first and second
        document.getElementById(firstIDsHiddenID).value = firstIDsSelected + firstId + ',';
        if (secondIDsHiddenID != null) {
            document.getElementById(secondIDsHiddenID).value = secondIDsSelected + secondId + ',';
        }
    }
    else 
    {
        if (counter > 0) 
        {
            counter--;
        }
        //remove the id from first and second
        document.getElementById(firstIDsHiddenID).value = firstIDsSelected.replace(firstId + ',', '');
        if (secondIDsHiddenID != null) {
            document.getElementById(secondIDsHiddenID).value = secondIDsSelected.replace(secondId + ',', '');
        }
    }
    if (counter == checkBoxCount) {
        if (counter == checkBoxCount) {
            document.getElementById(selectAllCheckBoxID).checked = true;
        }
    }
    else {
        if (counter < checkBoxCount) {
            document.getElementById(selectAllCheckBoxID).checked = false;
        }
    }
    if (counter == checkBoxCount || counter == 0) {
        if (counter == checkBoxCount) {
            
            document.getElementById(howManySelectedID).value = "all";
        }
        else
            if (counter < checkBoxCount) {            
            document.getElementById(howManySelectedID).value = "none";
        }
        document.getElementById(btnViewSelectedOnlyID).style["color"] = "gray";
        document.getElementById(btnViewSelectedOnlyID).onclick = function() { return false; };
    }
    else {
        document.getElementById(howManySelectedID).value = "some";

        document.getElementById(btnViewSelectedOnlyID).style["color"] = "#000";
        document.getElementById(btnViewSelectedOnlyID).onclick = function() {
            ViewOnlySelectedRows(firstIDsHiddenID, secondIDsHiddenID); removeGridViewDiv();
        };
    }

    if (document.getElementById(viewOnlySelectedID).value == "false") {
        document.getElementById(btnViewAllID).style["color"] = "gray";
        document.getElementById(btnViewAllID).onclick = function() { return false; };
    }
    else {
        document.getElementById(btnViewAllID).style["color"] = "#000";
        document.getElementById(btnViewAllID).onclick = function() {
        ViewAllRows(firstIDsHiddenID, secondIDsHiddenID); removeGridViewDiv();
        };
    }

}

function CheckTableCompanies(parentChk, gridClientID, firstIDsHiddenID, secondIDsHiddenID) {
    //var targetBaseControl = document.getElementById(gridClientID);
    var elements = document.getElementsByName("cbAll");
    var parentChecked = parentChk.checked;
    firstIDsSelected = "";
    secondIDsSelected = "";

    strSelected = "";
    
    for (i = 0; i < elements.length; i++) {
        if (parentChecked == true) 
        {
           elements[i].checked = true;
           if (elements[i].firstID != null) {
               theIds = elements[i].firstID;
               firstIDsSelected += theIds + ',';
               if (secondIDsHiddenID != null) {
                   secondIDsSelected += elements[i].secondID + ',';
               }
           }
        }
        else {
            elements[i].checked = false;
            // reset the counter 
            counter = 0;
        }
    }

    if (parentChecked == true) {
        document.getElementById(howManySelectedID).value = "all";
        counter = GetChildCheckBoxCount(gridClientID);
    }
    else {
        document.getElementById(howManySelectedID).value = "none";
    }

    document.getElementById(firstIDsHiddenID).value = firstIDsSelected;
    if (secondIDsHiddenID != null) {
        document.getElementById(secondIDsHiddenID).value = secondIDsSelected;
    }

    document.getElementById(btnViewSelectedOnlyID).style["color"] = "gray";
    document.getElementById(btnViewSelectedOnlyID).onclick = function() { return false; };
    if (document.getElementById(viewOnlySelectedID).value == "false") {
        document.getElementById(btnViewAllID).style["color"] = "gray";
        document.getElementById(btnViewAllID).onclick = function() { return false; };
    }
    else {
        document.getElementById(btnViewAllID).style["color"] = "#000";
        document.getElementById(btnViewAllID).onclick = function() {
        ViewAllRows(firstIDsHiddenID, secondIDsHiddenID); removeGridViewDiv();
        };
    }

}

//------------------------------------------------------
// Add by Marius 08/01/2008
// Desc - Check / Uncheck all checboxes in the gridview
// firstIDs = the first id stored in the checkbox id
// secondIDs = the first id stored in the checkbox id
//------------------------------------------------------
function SelectAll(checkBox,  gridClientID, firstIDsHiddenID, secondIDsHiddenID) {

    var targetBaseControl = document.getElementById(gridClientID);    
    var inputs = targetBaseControl.getElementsByTagName("input");

    firstIDsSelected = "";
    secondIDsSelected = "";

    strSelected = "";
    if (checkBox.checked) {
        for (var iCount = 0; iCount < inputs.length; ++iCount) {
            if (inputs[iCount].id.indexOf("cb", 0) >= 0) {
                inputs[iCount].checked = checkBox.checked;
                if (inputs[iCount].checked && inputs[iCount].firstID != null) {
                    theIds = inputs[iCount].firstID;
                    firstIDsSelected += theIds + ',';
                    if (secondIDsHiddenID != null) {
                        secondIDsSelected += inputs[iCount].secondID + ',';
                    }
                }
            }
        }
        document.getElementById(howManySelectedID).value = "all";
    }
    else {
        //uncheck all
        for (var iCount = 0; iCount < inputs.length; ++iCount) {
            if (inputs[iCount].id.indexOf("cb", 0) >= 0) {
                inputs[iCount].checked = false;
            }
        }
        document.getElementById(howManySelectedID).value = "none";
    }




    document.getElementById(firstIDsHiddenID).value = firstIDsSelected;
    if (secondIDsHiddenID != null) {
        document.getElementById(secondIDsHiddenID).value = secondIDsSelected;
    }

    document.getElementById(btnViewSelectedOnlyID).style["color"] = "gray";
    document.getElementById(btnViewSelectedOnlyID).onclick = function() { return false; };
    if (document.getElementById(viewOnlySelectedID).value == "false") {
        document.getElementById(btnViewAllID).style["color"] = "gray";
        document.getElementById(btnViewAllID).onclick = function() { return false; };
    }
    else {
        document.getElementById(btnViewAllID).style["color"] = "#000";
        document.getElementById(btnViewAllID).onclick = function() {
        ViewAllRows(firstIDsHiddenID, secondIDsHiddenID); removeGridViewDiv();
        };
    }
}

//------------------------------------------------------
// Add by Marius 08/01/2008
// Desc - Check / Uncheck the "select all" checbox in the gridview
//------------------------------------------------------
function ToggleSelectAll(checkBox, checkAllCheckBoxID, gridClientID, firstId, secondId, firstIDsHiddenID, secondIDsHiddenID) {
    var targetBaseControl = document.getElementById(gridClientID);

    var inputs = targetBaseControl.getElementsByTagName("input");

    firstIDsSelected = document.getElementById(firstIDsHiddenID).value;
    if (secondIDsHiddenID != null) {
        secondIDsSelected = document.getElementById(secondIDsHiddenID).value;
    }

    checkAllCheckBox = document.getElementById(selectAllCheckBoxID);
    allchecked = false;
    atleastone = false;
    if (checkBox.checked) {
        document.getElementById(firstIDsHiddenID).value = firstIDsSelected + firstId + ',';
        allchecked = true;
        //check to see if we have selected all the chk
        for (var iCount = 0; iCount < inputs.length; ++iCount) {

            if (!inputs[iCount].checked) {
                allchecked = false;
                if (atleastone == true)
                    break;
            }
            else {
                atleastone = true;
                if (allchecked == false)
                    break;
            }
        }

        checkAllCheckBox.checked = allchecked;
        if (secondIDsHiddenID != null) {
            document.getElementById(secondIDsHiddenID).value = secondIDsSelected + secondId + ',';
        }
        
    }
    else {
        document.getElementById(firstIDsHiddenID).value = firstIDsSelected.replace(firstId + ',', '');
        checkAllCheckBox.checked = allchecked;
        //check to see if there is at least one chk checked
        for (var iCount = 0; iCount < inputs.length; ++iCount) {

            if (inputs[iCount].checked) {
                atleastone = true;
                break;
            }
        }
        if (secondIDsHiddenID != null) {
            document.getElementById(secondIDsHiddenID).value = secondIDsSelected.replace(secondId + ',', '');
        }
    }
    
    if (allchecked || !atleastone) {
        if (allchecked) {
            document.getElementById(howManySelectedID).value = "all";
        }
        else {
            document.getElementById(howManySelectedID).value = "none";
        }

        document.getElementById(btnViewSelectedOnlyID).style["color"] = "gray";
        document.getElementById(btnViewSelectedOnlyID).onclick = function() { return false; };
    }
    else {

        document.getElementById(howManySelectedID).value = "some";

        document.getElementById(btnViewSelectedOnlyID).style["color"] = "#000";
        document.getElementById(btnViewSelectedOnlyID).onclick = function() {
            ViewOnlySelectedRows(firstIDsHiddenID, secondIDsHiddenID); removeGridViewDiv();
        };
    }

    if (document.getElementById(viewOnlySelectedID).value == "false") {
        document.getElementById(btnViewAllID).style["color"] = "gray";
        document.getElementById(btnViewAllID).onclick = function() { return false; };
    }
    else {
        document.getElementById(btnViewAllID).style["color"] = "#000";
        document.getElementById(btnViewAllID).onclick = function() {
        ViewAllRows(firstIDsHiddenID, secondIDsHiddenID); removeGridViewDiv();
        };
    }

}


//------------------------------------------------------
// Add by Marius 09/01/2008
// Desc - View only checkef rows from the datagrid
//------------------------------------------------------
function ViewOnlySelectedRows(firstIDsHiddenID, secondIDsHiddenID) {
    document.getElementById(visibleIDsID).value = document.getElementById(firstIDsHiddenID).value;
    document.getElementById(viewOnlySelectedID).value = "true";
    SaveInSession('selectedFirstIDs', document.getElementById(firstIDsHiddenID).value);
    if (secondIDsHiddenID != null) {
        SaveInSession('selectedSecondIDs', document.getElementById(secondIDsHiddenID).value);
    }
    ids = document.getElementById(firstIDsHiddenID).value;
    SaveInSession('visibleCheckboxes', ids);
    SaveInSession('viewOnlySelected', 'true');
    checkBoxCount = 0;
    removeGrid();   
    return true;
}
function removeGrid() {
    try {
        if (divGridviewID) {
            var div = document.getElementById(divGridviewID);
            var parentDiv = div.parentNode;
            //    var loadDiv = document.createElement("div");
            //    loadDiv.setAttribute("id", "loadDiv");
            //    loadDiv.setAttribute("style", "background-color: #ffffff;width:200px; border:1px solid #dfdfdf");
            //    var image = loadDiv.appendChild(document.createElement("img"));
            //    image.setAttribute("src", "../Images/loading.gif");

            parentDiv.removeChild(div);
        }
    }
    catch (e) { }
}
//------------------------------------------------------
// Add by Marius 09/01/2008
// Desc - View all rows in datagrid
//------------------------------------------------------
function ViewAllRows(firstIDsHiddenID, secondIDsHiddenID) {
    ids = document.getElementById(firstIDsHiddenID).value;
    SaveInSession('visibleCheckboxes', ids);
    SaveInSession('viewOnlySelected', 'false');
    SaveInSession('viewAll', 'true');
    SaveInSession('selectedFirstIDs', 'null');//reset the session values
    SaveInSession('selectedSecondIDs', 'null'); //reste the session values
    checkBoxCount = 0;
    removeGrid();   
    return true;
}


//------------------------------------------------------
// Add by Marius 09/01/2008
// Desc - Saves checked checkboxes in session
//------------------------------------------------------
function SaveSelectedCheckBoxesInSession(hiddenID) {
    ids = document.getElementById(hiddenID).value;
    SaveInSession('selectedCheckboxes', ids);
}

//------------------------------------------------------
// Add by Marius 09/01/2008
// Desc - Gets the xmlHttp object
//------------------------------------------------------
var xmlHttp;
function GetXmlHttpObject() {
    var xmlHttp = null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    
    return xmlHttp;
}


//------------------------------------------------------
// Add by Marius 09/05/2008
// Desc - Saves a key - value pair in session
//------------------------------------------------------
function SaveInSession(key, values) {
    try {
        var httpRequest = GetXmlHttpObject();


        var xmlSOAP = '<?xml version="1.0" encoding="utf-8"?>' +
         '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
         'xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> ' +
          '<soap:Body>' +
           '<SetSessionValue xmlns="http://tempuri.org/">' +
            '<key>' + key + '</key>' +
            '<value>' + values + '</value>' +
           '</SetSessionValue>' +
          '</soap:Body>' +
         '</soap:Envelope>';


        
        // send XML document to Web server
        //httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

        httpRequest.onreadystatechange = new function() {  };
        //alert(UtilitiesWSUrl);
        httpRequest.open("POST", UtilitiesWSUrl, false);
        
        httpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/SetSessionValue");
        httpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        httpRequest.send(xmlSOAP);
    }
    catch (err) { }
}

//------------------------------------------------------
// Add by Rost 10/13/06
// Desc - verify if CheckAll checkbox is checked
// Used in Financing/Pipeline - FetchReports.aspx
//			onj - checkbox (child)
//------------------------------------------------------
function CheckParent(obj) {
    ToggleCheckAll(obj);
    document.getElementById('checkedCompanies').value = (obj && obj.checked) ? parseInt(document.getElementById('checkedCompanies').value) + 1 : parseInt(document.getElementById('checkedCompanies').value) - 1;
    DisableEnableAnchor(document.getElementById('btnViewSelectedOnly'), (document.getElementById('checkedCompanies').value == document.getElementById('displayedNumberOfcompanies').value || document.getElementById('checkedCompanies').value == 0) ? "true" : "false");
}


//------------------------------------------------------
// Add by Rost 10/13/06
// Desc - reset Company Values (nr. of companies)
// Used in Financing/Pipeline - FetchReports.aspx
//------------------------------------------------------
function resetCompanyValues() {
    document.getElementById('checkedCompanies').value = (document.getElementById('cbAll') && document.getElementById('cbAll').checked) ? document.getElementById('displayedNumberOfcompanies').value : "0";
    DisableEnableAnchor(document.getElementById('btnViewSelectedOnly'), 'true');
}


//-------------------------------------------------------------------------------
// GetParam
// ADD by - Bela Gaspar - 11/29/2006
// Descr: return from document.location.search the asked parameter value
// Used in IsFromReport()
//-------------------------------------------------------------------------------
function GetParam(theSearchURL, theParamName) {
    var start = theSearchURL.indexOf("?" + theParamName + "=");
    if (start < 0)
        start = theSearchURL.indexOf("&" + theParamName + "=");
    if (start < 0)
        return '';
    start += theParamName.length + 2;
    var end = theSearchURL.indexOf("&", start) - 1;
    if (end < 0)
        end = theSearchURL.length;
    var result = theSearchURL.substring(start, end);
    var result = '';
    for (var i = start; i <= end; i++) {
        var c = theSearchURL.charAt(i);
        result = result + (c == '+' ? ' ' : c);
    }
    return unescape(result);
}


//-------------------------------------------------------------------------------
// GetParam
// ADD by - Eugen Popa - 11/01/2007
// Descr: enable View/Modify Company List from reports page (left frame)
// Used in Financings/Reports.aspx and Pipeline/Reports.aspx
// Commented by Mihai on 14.11.2008
// Uncommented by Silvia on 20.02.2009
//-------------------------------------------------------------------------------
function viewModifyList(select, lname, lid, module) {

    if (select == null) {//for myBiocentury 
        SaveInSession("CompanySource", null);
        SaveInSession("viewSelectedFinancingSource", null);
        SaveInSession("selectedFirstIDs", null);
        SaveInSession("tempSelectedFirstIDs", null);
        SaveInSession("visibleCheckboxes", null);
        SaveInSession("viewOnlySelected", null);
        SaveInSession("showOnlyFirst", null);
        SaveInSession("showLeftNavigation", null);
        
        SaveInSession("CurrentListID", lid);
        SaveInSession("CurrentListName", lname);
        
        SaveInSession("namesListClientID", null);
        
    }
    else {
        if (lname != null) {
            for (var i = 0; i < select.options.length; i++) {
                if (select.options[i].text == lname) {
                    select.options[i].selected = true;
                    break;
                }
            }
        }
        try {

            //Clear Session Variables
            SaveInSession("CompanySource", null);
            SaveInSession("viewSelectedFinancingSource", null);
            SaveInSession("selectedFirstIDs", null);
            SaveInSession("tempSelectedFirstIDs", null);
            SaveInSession("visibleCheckboxes", null);
            SaveInSession("viewOnlySelected", null);
            SaveInSession("showOnlyFirst", null);
            SaveInSession("showLeftNavigation", null);
            //SaveInSession("CompanyStanding", null);

            //Save ListID and ListName in CurrentListID and CurrentListName
             //Save ListID and ListName in CurrentListID and CurrentListName
            if (lname != "Current List") {
                SaveInSession("CurrentListID", select.options[select.selectedIndex].value);
                SaveInSession("CurrentListName", select.options[select.selectedIndex].innerHTML);
            }
            else {
                SaveInSession("CurrentListID", lid);
                SaveInSession("CurrentListName", lname);
            }       
            
            //drop down clientID       
            SaveInSession("namesListClientID", select.id);
        }

        catch (e) {
            alert(e.Message);            
        }
    }
    //window.open('../Common/ViewModifyCompanyList.aspx?ControlType=TablesCompanies&Module=5', '_blank', 'status=yes,resizable=yes,toolbar=no,menubar=no,scrollbars=yes');    
    window.open('../Common/ViewModifyCompanyList2.aspx?ControlType=TablesCompanies&Module='+module, '_blank', 'status=yes,resizable=yes,toolbar=no,menubar=no,scrollbars=yes');    
}

//-------------------------------------------------------------------------------
// ADD by - Claudiu Sabau - September 05, 2007
// Descr: enable View/Modify Criteria List from reports page (left frame)
// Used in Financings/Reports.aspx, Pipeline/Reports.aspx, FinancialPerformance/Reports.aspx, Stocks/Reports.aspx and Company/FindCompany.aspx.
//-------------------------------------------------------------------------------
function viewModifyListForCriteria(theProduct) {
    var select = document.getElementById(criteriaListDropdownID);
    if (select.value == "0") {
        alert("Please select a saved criteria set");
        return false;
    }

    var theCriteriaName = GetInnerText_IE_FireFox(select.options[select.selectedIndex]);
    var theCriteriaID = select.value;
    switch (theProduct) {
        case 'Financing':
            window.open("../../mybiocentury/CriteriaPages/mybcFinancingCriteria.aspx?criteriaID=" + theCriteriaID + "&criteriaName=" + theCriteriaName, "popUpSection", "directories=no,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=no,width=1024,height=700");
            break;
        case 'FinancialPerformance':
            window.open("../../mybiocentury/CriteriaPages/mybcFinancialPerformanceCriteria.aspx?criteriaID=" + theCriteriaID + "&criteriaName=" + theCriteriaName, "popUpSection", "directories=no,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=no,width=1024,height=700");
            break;
        case 'Pipeline':
            window.open("../../mybiocentury/CriteriaPages/mybcPipelineCriteria.aspx?criteriaID=" + theCriteriaID + "&criteriaName=" + theCriteriaName, "popUpSection", "directories=no,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=no,width=1024,height=700");
            break;
        case 'Stocks':
            window.open("../../mybiocentury/CriteriaPages/mybcStocksCriteria.aspx?criteriaID=" + theCriteriaID + "&criteriaName=" + theCriteriaName, "popUpSection", "directories=no,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=no,width=1024,height=700");
            break;
        case 'Company':
            window.open("../../mybiocentury/CriteriaPages/mybcCompanyCriteria.aspx?criteriaID=" + theCriteriaID + "&criteriaName=" + theCriteriaName, "popUpSection", "directories=no,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=no,width=1024,height=700");
            break;
    }
    //window.open("../../mybiocentury/mybcFinancingCriteria.aspx?criteriaID=" + theCriteriaID + "&criteriaName=" + theCriteriaName + "&ProductID=" + theProductID, "popUpSection", "directories=no,location=no,menubar=no,scrollbars=no,status=no,toolbar=no,resizable=no,width=1024,height=700");
}


//-------------------------------------------------------------------------------
// ADD by - Claudiu Sabau - September 06, 2007
// Descr: toggle check all. (imported from BioCentury Archives)
// Used in \Common\CriteriaManagement.aspx
//-------------------------------------------------------------------------------
var checkCount = 0;
function ToggleCheckAllCriteriaManagement(cb) {
    var bAllChecked = true;
    var checks = document.getElementsByName("cb");

    for (var i = 0; i < checks.length; ++i) {
        var checkbox = checks[i];
        if (!checkbox.checked) {
            bAllChecked = false;
            break;
        }
    }
    var strSelected = document.getElementById("CriteriaListSelections").value;
    var criteriaId = cb.id.split('_')[1];
    if (cb.checked) {
        strSelected = strSelected + criteriaId + ',';
        checkCount++;
    }
    else {
        strSelected = strSelected.split(criteriaId + ',')[0] + strSelected.split(criteriaId + ',')[1];
        checkCount--;
    }

    document.getElementById("CriteriaListSelections").value = strSelected;
    document.getElementById("cbAll").checked = bAllChecked;
}


//-------------------------------------------------------------------------------
// Check All ComboBoxes
// ADD by - Claudiu Sabau - September 05, 2007
// Descr: enables the check all option for data grid (left frame)
// Used in CriteriaManagement.aspx
//-------------------------------------------------------------------------------
function CheckAllForCriteriaManagement(bCheck) {
    var strSelected = "";
    if (document.getElementById('cbAll') != null) document.getElementById('cbAll').checked = bCheck;

    var checks = document.getElementsByName('cb');

    checkCount = (bCheck) ? checks.length : 0;
    for (var i = 0; i < checks.length; ++i) {
        var criteriaIds = checks[i].id.split('_')[1];
        checks[i].checked = bCheck;
        if (bCheck == true)
            strSelected += criteriaIds + ",";
    }
    document.getElementById('CriteriaListSelections').value = strSelected;
}

//-------------------------------------------------------------------------------
// "Confirm Delete Selected"
// used in \Common\CriteriaManagement.aspx.
// ADD Claudiu Sabau, August 31, 2007
//-------------------------------------------------------------------------------
function ConfirmDeleteSelected() {
    try {
        var hdnIds = document.getElementById("CriteriaListSelections").value;
        if (hdnIds != "") {
            return confirm("Are you sure you want to delete selected list(s)?");
        }
        else {
            alert("You must select a Criteria List first.");
            return false;
        }
    }
    catch (err) {
        alert("Some error occured:\n" + err.message);
    }
    return false;
}


//-------------------------------------------------------------------------------
// "load() function for pop-up, used on body"
// used in \Common\CriteriaManagement.aspx.
// ADD Claudiu Sabau, August 31, 2007
//-------------------------------------------------------------------------------
function load() {
    setDIVHeight('dgCriteriaList');
}


//-------------------------------------------------------------------------------
// "sets Div properties for pop-up"
// used in \Common\CriteriaManagement.aspx.
// ADD Claudiu Sabau, August 31, 2007
//-------------------------------------------------------------------------------
function setDIVHeight(gridID) {
    bodyWidth = 800;
    bodyHeight = 610;
    var datagrid = document.getElementById(gridID);
    if (datagrid != null) {
        var div = document.getElementById('CompanyList');
        var maxGridWidth = bodyWidth;

        var diffHeight = 0;
        if (document.getElementById('gridButtons') != null) diffHeight = document.getElementById('gridButtons').offsetHeight;
        if (document.getElementById('copyright1') != null) diffHeight += document.getElementById('copyright1').offsetHeight;
        if (document.getElementById('headmain') != null) diffHeight += document.getElementById('headmain').offsetHeight;
        if (document.getElementById('div_home') != null) diffHeight += document.getElementById('div_home').offsetHeight;

        var maxGridHeight = bodyHeight - diffHeight - 60;

        if (datagrid.offsetHeight > maxGridHeight) {
            if (maxGridHeight > 200)
                div.style.height = maxGridHeight + 'px';
            else
                div.style.height = "200px";
        }
        else {
            if (datagrid.offsetHeight >= parseInt(div.style.height))
                div.style.height = datagrid.offsetHeight + 18 + 'px';
        }
        if (datagrid.offsetWidth >= maxGridWidth) {
            if (maxGridWidth > 300)
                div.style.width = maxGridWidth + 'px';
            else
                div.style.width = "300px";
        }
        else {
            if (datagrid.offsetWidth > parseInt(div.style.width))
                div.style.width = datagrid.offsetWidth + 18 + 'px';
        }
    }
}

//used in Reports.aspx to set widths for CompanyLists/CompanyName
//Modified by Marcu Paul-Robert 07/28/2008
// the third parameter is optional, used only when the reset button is clicked
function setWidth(e, id, reset) {
    //if e is null the function was invoked probably from
    //another javascript function not directly by the control

    if (e != null || e != undefined) {
        //test if it ie
        if (window.event) {
            e = window.event;
            e.cancelBubble = true;
        }
        else if (e.stopPropagation) {
            e.stopPropagation();
        }
    }

    var strPreControlName = 'ctl00_cphMain_UserListsCriteriaControl_';

    var search = document.getElementById(strPreControlName + 'txtCompanyName');

    var ddList = document.getElementById(strPreControlName + 'UserCompanyLists');
    var div = document.getElementById('divCompaniesDropdown');


    if (id == search.id) {

        search.className = "enabled";

        div.style["width"] = "45px";

        if (document.all) {// IE
            ddList.setAttribute('disabled', 'true');

            search.style.width = "126px";
        }
        else {
            ddList.className = "disabledCompanies";
            ddList.setAttribute('onfocus', 'this.blur();');
            search.style.width = "126px";
        }
        ddList.style["width"] = "45px";



        search.value = '';
    }
    if (id == div.id) {
        search.className = "disabled";


        if (document.all) {
            search.style.width = "77px";
            ddList.style["width"] = "94px";
            div.style["width"] = "94px";
            ddList.removeAttribute('disabled');
        }
        else {
            search.style.width = "77px";
            ddList.className = "";
            ddList.style["width"] = "94px";
            ddList.removeAttribute('onfocus');
            div.style["width"] = "94px";
        }




        search.value = 'Company Name';

    }
    if (id == 'body') {

        search.style.width = "77px";
        ddList.style["width"] = "94px";
        div.style["width"] = "94px";
        if (search.value == "" || search.value == 'Company Name') {
            search.value = 'Company Name';
            search.className = "disabled";

        }

        if (document.all) {// IE
            ddList.setAttribute('disabled', 'true');
        }
        else {
            //ddList.className = "disabledCompanies";
            ddList.setAttribute('onfocus', 'this.blur();');
        }

        search.value = 'Company Name';
    }

    //when the third parameter is defined
    //restore the original dimensions
    if (reset != undefined) {
        search.style.width = "77px";
        ddList.style["width"] = "94px";
        div.style["width"] = "94px";
        if (search.value == "" || search.value == 'Company Name') {
            search.value = 'Company Name';
            search.className = "disabled";
        }

        if (document.all) {// IE
            ddList.setAttribute('disabled', 'true');
        }
        else {
            //ddList.className = "disabledCompanies";
            ddList.setAttribute('onfocus', 'this.blur();');
        }

        search.value = 'Company Name';



        ddList.options[0].selected = true;
    }
}

// used in Tables.ascx to set the input hidden field viewOption from TablesF.aspx
function checkView(view) 
{
    //document.getElementById("viewOption").value = view;
    document.getElementById(viewOptionID).value = view;
}

//------------------------------------------------------
// Add by Marius 03/26/2009
// Desc - Check / Uncheck all checboxes in the gridview for removed records
// from the email alert results
//------------------------------------------------------
function SelectAllRemovedRecords(checkBox, divGridviewID) {

    var inputs = document.getElementById(divGridviewID).getElementsByTagName("input");

    for (var iCount = 0; iCount < inputs.length; ++iCount) {
        if (inputs[iCount].id.indexOf("cb", 0) >= 0) {
            inputs[iCount].checked = checkBox.checked;
        }
    }
}

//------------------------------------------------------
// Add by Marius 03/26/2009
// Desc - Check / Uncheck the "select all" checbox in the gridview for removed records
// from the email alert results
//------------------------------------------------------
function ToggleSelectAllRemovedRecords(checkBox, checkAllCheckBoxID, gridClientID) {
    var targetBaseControl = document.getElementById(gridClientID);
    var inputs = targetBaseControl.getElementsByTagName("input");


    checkAllCheckBox = document.getElementById(selectAllCheckBoxID);
    allchecked = false;
    atleastone = false;
    if (checkBox.checked) {
        allchecked = true;
        //check to see if we have selected all the chk
        for (var iCount = 0; iCount < inputs.length; ++iCount) {

            if (!inputs[iCount].checked) {
                allchecked = false;
                break;
            }
        }
        checkAllCheckBox.checked = allchecked;

    }
    else {
        checkAllCheckBox.checked = allchecked;
    }
}

//------------------------------------------------------
// Add by Marius 04/09/2009
// Desc - used for reseting the criteria list box from mybc
//------------------------------------------------------
function ResetCriteriaListbox() {
    var criteriaList = document.getElementById(criteriaListDropdownID);
    criteriaList.selectedIndex = 0;
    criteriaList[0].selected = true;
}

//-------------------------------
// Add by Bela on 05/05/2009
// Used in: ChartsF.aspx.cs, TablesF.aspx.cs
//-------------------------------
function WarningFinancingDateCustomWindow() 
{
    alert("Custom window cannot be used for charting. Please refine your Financing Date selections.");
}

//-------------------------------------------------------------------------------
// Add by Bela on 05/18/2009
// HTML-Encode the supplied input
// parameter: (String) source - the text to be encoded.
//-------------------------------------------------------------------------------
function htmlEncode(source)
{
	function special(source)
	{
		var result = '';
		for (var i = 0; i < source.length; i++)
		{
			var c = source.charAt(i);
			if (c < ' ' || c > '~')
			{
				c = '&#' + c.charCodeAt() + ';';
			}
			result += c;
		}
		return result;
	}
	var result = source;

	// ampersands (&)
	result = result.replace(/\&/g, '&amp;');

	// less-thans (<)
	result = result.replace(/\</g, '&lt;');

	// greater-thans (>)
	result = result.replace(/\>/g, '&gt;');
	
    // Replace quotes if it isn't for display,
    // since it's probably going in an html attribute.
    result = result.replace(new RegExp('"', 'g'), '&quot;');

	// special characters
	result = special(result);
	
	return result;
}

//-------------------------------------------------------------------------------
// Added by Mihai on 25th of November 2009
// This checks if the profile alert is ready to set
// parameters:  (string) criteriaId - the criteria that will be saved over.
//              (bool) notUser - true if the user not logged in
//              (string) redirectUrl - the marketing/login page where the user will be redirected
//-------------------------------------------------------------------------------
function ValidateProfileDialog(listName, notUser, redirectUrl) {
    var isValidCriteria = true;
    //check login
    if (notUser) {
        document.location.href = redirectUrl;
        //alert(IsPublicCompanyProfile);
        return false;
    }

    //check number of saved alerts
    if (isValidCriteria)
        isValidCriteria = CheckAvailableAlerts(5, 'ModalPopupExtenderAvailableAlerts');
        
//    // TODO-Mihai This part is being used for Set Pipeline Alert
//    if (isValidCriteria)
//        isValidCriteria = CheckAvailableAlerts(11, 'ModalPopupExtenderAvailableAlerts');

    if (!isValidCriteria)
        return false;
    //Archives
    hasArchivesAlert = false;
    
//    //TODO-Mihai This part is being used for Set Pipeline Alert
//    hasBCIQAlert = false;

    if (isValidCriteria) {
        var existsCriteriaName = CriteriaAlreadyExists(listName, 5);
        if (existsCriteriaName != -1) {
            isValidCriteria = false;
            hasArchivesAlert = true;
        }
    }
//    //TODO-Mihai This part is being used for Set Pipeline Alert
//    //Financings//Pipeline
//    if (isValidCriteria) {
//        var existsCriteriaName = CriteriaAlreadyExists(listName, 6);
//        if (existsCriteriaName != -1) {
//            isValidCriteria = false;
//            hasBCIQAlert = true;
//        }
//    }

    if (!isValidCriteria) {
        if (hasArchivesAlert) {
            return confirm(listName + ' already exists in your archives saved search terms. Setting this email alert will also overwrite that existing saved search. Continue?');
        }
//        //TODO-Mihai This part is being used for Set Pipeline Alert
//        if (hasBCIQAlert) {
//            return confirm('Overwrite criteria?');
//        }
    }
    else
        return true;
    //return isValidList;
}

//-------------------------------------------------------------------------------
// Added by Mihai on 25th of November 2009
// This checks if the profile alert is ready to set
// parameters:  (string) criteriaId - the criteria that will be saved over.
//              (bool) notUser - true if the user not logged in
//              (string) redirectUrl - the marketing/login page where the user will be redirected
//-------------------------------------------------------------------------------
function ValidateTargetDialog(listName, notUser, redirectUrl) {
    var isValidCriteria = true;
    //check login
    if (notUser) {
        document.location.href = redirectUrl;
        //alert(IsPublicCompanyProfile);
        return false;
    }

    //check number of saved alerts
    if (isValidCriteria)
        isValidCriteria = CheckAvailableAlerts(5, 'ModalPopupExtenderAvailableAlerts');
    if (isValidCriteria)
        isValidCriteria = CheckAvailableAlerts(11, 'ModalPopupExtenderAvailableAlerts');

    if (!isValidCriteria)
        return false;
    //Archives
    hasArchivesAlert = false;
    hasBCIQAlert = false;
    if (isValidCriteria) {
        var existsCriteriaName = CriteriaAlreadyExists(listName, 5);
        if (existsCriteriaName != -1) {
            isValidCriteria = false;
            hasArchivesAlert = true;
        }
    }
    //Financings//Pipeline
    if (isValidCriteria) {
        var existsCriteriaName = CriteriaAlreadyExists(listName, 6);
        if (existsCriteriaName != -1) {
            isValidCriteria = false;
            hasBCIQAlert = true;
        }
    }

    if (!isValidCriteria) {
        if (hasArchivesAlert) {
            return confirm(listName + ' already exists in your archives saved search terms. Setting this email alert will also overwrite that existing saved search. Continue?');
        }
        if (hasBCIQAlert) {
            return confirm('Overwrite criteria?');
        }
    }
    else
        return true;
    //return isValidList;
}