﻿// <copyright file="MyBioCentury.js" company="BioCentury Publications Inc."> 
// All contents Copyright © 2005-2009 BioCentury Publications, Inc. ALL RIGHTS RESERVED
// 
// http://www.biocentury.com 
// </copyright>

// JScript File


//-------------------------------------------------------------------------------
// 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+/, '');
}


var saveWindow = null; // save criteria window

//-------------------------------------------------------------------------
//   Tab effects
//-------------------------------------------------------------------------
//function used Master for tab effect

/*function setActiveLink(id)
{
    var link = document.getElementById(id);
    link.style.color = "#787878";    
    link.style.cursor = "default";
    currentLink = id;    
}
*/
//---------------------------------------------------------------------------
//   Radio Checker
//---------------------------------------------------------------------------
function RadioOptionCheck(option)
{
    //document.getElementById(option).checked = true;
    return false;
}

//-------------------------------------------------------------------------------------------
//Used in mybcColumnPreferences, for left option selection
//-------------------------------------------------------------------------------------------
function SetSelectedOptionColumn()
{
    var checks = document.getElementsByName('leftOptionsColumns');
    for(var i = 0; i < checks.length; i++)
    {
        if(checks[i].checked == true)
        {
            document.getElementById('ctl00_contentRight_SelectedOption').value = checks[i].id;
            var temp = checks[i].id;
            break;
        }
    }
    __doPostBack('','');    
}

function load()
{
    setDIVHeight('ctl00_contentRight_toolListDataGridArchives_dgCriteriaList');
    setDIVHeight('ctl00_contentRight_toolListDataGridBCIQ_dgCriteriaList');
    setDIVHeight('ctl00_contentRight_toolListDataGridCompany_dgCriteriaList');
    //setActiveLink(currentLink);
}

function setDIVHeight(gridID)
{    
    bodyWidth = pageWidth() - 230; //Math.round(document.body.clientWidth*95/100);
    bodyHeight = pageHeight() - 210; //document.body.clientHeight;
    //alert(bodyWidth + ' - ' + bodyHeight);
    var datagrid = document.getElementById(gridID);
    if (datagrid != null)
    {
        var div = document.getElementById('ctl00_contentRight_toolListDataGridArchives_CriteriaList');
        if(div == null)
        {
            var div = document.getElementById('ctl00_contentRight_toolListDataGridBCIQ_CriteriaList');
            if(div == null)
            {
                var div = document.getElementById('ctl00_contentRight_toolListDataGridCompany_CriteriaList');
            }
        }
        
        var maxGridWidth = bodyWidth;
		
        var diffHeight = 0;        
        if (document.getElementById('gridButtons') != null) diffHeight = document.getElementById('gridButtons').offsetHeight;		        
        if (document.getElementById('copyright') != null) diffHeight += document.getElementById('copyright').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';
        }
    }
}

////-------------------------------------------------------------------------------
//// Confirmation message: Delete Criteria
//// ADD Bela Gaspar
//// Used in: mybcBCIQCriteria.aspx
////-------------------------------------------------------------------------------
//function ConfirmDeleteCriteria() 
//{
//	return confirm("Are you sure you want to delete this criteria list?");
//}

//-------------------------------------------------------------------------------
// Confirmation message: Delete Criteria
// Added by Mihai
// Used in: mybcArchiveSearch.aspx
//-------------------------------------------------------------------------------
function ConfirmDeleteSearch() 
{
    return confirm("Are you sure you want to delete this search?");
}


//-------------------------------------------------------------------------------
// Save Criteria Pop-up
// Add by Bela
// Used in mybcArchiveSearch.aspx.cs, mybcBCIQCriteria.aspx.cs
//-------------------------------------------------------------------------------
function SaveCriteria(theProductID)
{
	// if there is no pop-up already opened
	if (saveWindow == null)
	{
		leftVal = (screen.width - 500) / 2;
	    topVal = (screen.height - 150) / 2;
	    saveWindow = window.open("CriteriaSave.aspx?ProductID=" + theProductID, "_blank", 'width=500,height=150,left='+leftVal+',top='+topVal+',toolbar=0,resizable=0');
		return false;
	}
	else
	{
		saveWindow.close();
		return false;
	}
}

//------------------------------------------------------------------------------
// Added by Claudiu Sabau, October 10, 2007
// Used for resizeing page elements, used in MyBioCentury MasterPage and iFrames
// -----------------------------------------------------------------------------
var bodyWidth, bodyHeight;

function resizePageElements()
{
    resize('masterTable'); 
    resize('ctl00_contentRight_toolListDataGridCompany_dgCriteriaList');
    resize('ctl00_contentRight_toolListDataGridBCIQ_dgCriteriaList');
    resize('ctl00_contentRight_toolListDataGridArchives_dgCriteriaList');
}
function resize(id)
{	
	if (bodyHeight == document.body.clientHeight && bodyWidth == Math.round(document.body.clientWidth*95/100)) 
	{   	
	    if((id == 'masterTable') || (id == 'CompanyFrame') || (id == 'FinancialFrame') || (id == 'PipelineFrame') || (id == 'FinancialPerformanceFrame')|| (id == 'StocksFrame') )
	    {
	        SetHeight(id);
	    }	
	    else
	    {
	        setDIVHeight(id);
	    }    
	}
	else
	{
		bodyWidth = Math.round(document.body.clientWidth*95/100);
		bodyHeight = document.body.clientHeight;
		setTimeout("resize('" + id + "')",5);
	}
}
function SetHeight(id)
{
    var tempPageHeight = pageHeight() - 250;
    var tempPageWidth = pageWidth() - 210;
    //alert(tempPageWidth + ' x ' + tempPageHeight);
    if(tempPageHeight > 0)
    {
        document.getElementById(id).style.height = tempPageHeight;    
    }
}
  
//---------------------------------------------------------------------------
// Added by Claudiu Sabau, october 10, 2007
// Get, Set - Page Height and Width
//---------------------------------------------------------------------------  
function pageHeight() 
{
    return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}
function pageWidth() 
{
    return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
} 

//-------------------------------------------------------------------------------
// Update Criteria
// ADD Bela Gaspar, October 12, 2007
// Used in GenerateArchivesDataMember.ascx.cs and GenerateBCIQDataMember.ascx.cs
//-------------------------------------------------------------------------------
function UpdateCriteria(txtIDcriteriaName, criteriaID, productID, UserCriteriaListID, isArchives, userId)
{
    var criteriaName = trim (document.getElementById(txtIDcriteriaName).value);   
    
    if (criteriaName == '')
	{
		alert("Please name your criteria before saving it");
		return false;
	}
	else
	{
	    var criteriaList;
        criteriaList = document.getElementById(UserCriteriaListID).value.split('|');
	    
	    if (!isArchives) 
	    {
	        var isBCCriteria = ReservedCriteria(criteriaName, productID, userId);
            if (isBCCriteria != "undefined" && isBCCriteria != null && isBCCriteria == "true") 
            {
                alert('This is a reserved criteria name. Please choose another one.');
                return false;
            }
	    }	    	   
	    
        for (var i = 0; i < criteriaList.length - 1; i++)
        {
            if (!isArchives)
            {
                if(criteriaList[i].split(' ')[2].toLowerCase() == criteriaName.toLowerCase() && criteriaList[i].split(' ')[0] != criteriaID)
                {
                    if(productID == criteriaList[i].split(' ')[1]) {
                        var isCriteriaUsedInEmailAlert = IsCriteriaUsedInEmailAlert(productID, criteriaName, userId)
                        if (isCriteriaUsedInEmailAlert != "undefined" && isCriteriaUsedInEmailAlert != null && isCriteriaUsedInEmailAlert == "true")
                        {
                            return confirm('This Criteria set already exist 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.');
                        }
                        else 
                        {
                            return confirm('This Criteria Name already exists.\n Are you sure you want to overwrite it?');         
                        }
                    }
                }
            }
            else
            {
                if(criteriaList[i].split(' ')[1].toLowerCase() == criteriaName.toLowerCase() && criteriaList[i].split(' ')[0] != criteriaID) {
                    var isCriteriaUsedInEmailAlert = IsCriteriaUsedInEmailAlert(productID, criteriaName, userId)
                    if (isCriteriaUsedInEmailAlert != "undefined" && isCriteriaUsedInEmailAlert != null && isCriteriaUsedInEmailAlert == "true") 
                    {
                        return confirm('This Criteria set already exist 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.');
                    }
                    else 
                    {
                        return confirm('This Criteria Name already exists.\n Are you sure you want to overwrite it?');
                    } 
                }
            }              
        }
        return true;
	}	
}

//-------------------------------------------------------------------------------
// Added by Marius Paltanea 2/25/2009
// Moved from BCIQCriteria.js by Mihai on 04/30/2009
// Returns if a criteria with the same name
// already exists in the database
//-------------------------------------------------------------------------------
function CriteriaAlreadyExists(criteriaName, productID, userId) 
{
    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>' +
           '<IsReservedCriteriaName xmlns="http://www.biocentury.com/webservices/">' +
            '<listName>' + htmlEncode(criteriaName) + '</listName>' +
            '<currentProduct>' + productID + '</currentProduct>' +
            '<userId>' + htmlEncode(userId) + '</userId>' +
           '</IsReservedCriteriaName>' +
          '</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://www.biocentury.com/webservices/IsReservedCriteriaName");
        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);
            }
            catch (e) {
                try //Firefox, Mozilla, Opera, etc.
                {
                    parser = new DOMParser();
                    xmlDoc = parser.parseFromString(text, "text/xml");
                }
                catch (e) {
                    alert(e.message);
                }
            }
            try {
                //  document.write("xmlDoc is loaded, ready for use");
                //document.write(xmlDoc.getElementsByTagName("IsReservedListNameResult"));
                return xmlDoc.getElementsByTagName("IsReservedCriteriaNameResult")[0].text;
            }
            catch (e) {
                alert(e.message);
            }
        }
        else {
            alert("Criteria couldn't be accessed.");
        }
    }
    catch (err)
    { }
}

//-------------------------------------------------------------------------------
// Created by Marius, copied by Bela from BCIQ to Tools
//-------------------------------------------------------------------------------
function ReservedCriteria(criteriaName, productID, userId) 
{
    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://www.biocentury.com/webservices/">' +
            '<criteriaSet>' + htmlEncode(criteriaName) + '</criteriaSet>' +
            '<productID>' + productID + '</productID>' +
            '<userId>' + htmlEncode(userId) + '</userId>' +
           '</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://www.biocentury.com/webservices/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)
    { }
}


//-------------------------------------------------------------------------------
// Createt by Mihai on 06 April 2009
// Used in ValidateSaveDialog
// The one bellow is the old one
//-------------------------------------------------------------------------------
function IsCriteriaUsedInEmailAlert(productID, criteriaName, userId) {
    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://www.biocentury.com/webservices/">' +
            '<productID>' + productID + '</productID>' +
            '<criteriaName>' + htmlEncode(criteriaName) + '</criteriaName>' +
            '<userId>' + htmlEncode(userId) + '</userId>' +
           '</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://www.biocentury.com/webservices/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)
    { }
}

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;
}

//-------------------------------------------------------------------------------
// Update List
// ADD Claudiu Sabau, October 16, 2007
// Used in GenerateCompanyDataMember.ascx.cs
//-------------------------------------------------------------------------------
function UpdateList(txtIDlistName, listID, userId)
{
    var listName = trim (document.getElementById(txtIDlistName).value);   
    
    if (listName == '')
	{
		alert("Please name your list before saving it");
		return false;
	}
	else
	{	
	    var isBCList = AjaxUtilities.IsReservedListName(listName, userId);
		if (isBCList.value)
		{
		    alert('"' + listName + '" is a reserved list name. Please choose another one.');
			return false;

        }
        // TODO Bela - listnames with "," - BUG !!!
	    var companyList; 	    
	    companyList = document.getElementById('ctl00_contentRight_toolListDataGridCompany_CompanyListNames').value.split(',');	   
	        
        for (var i = 0; i < companyList.length - 1; i++)
        {
            if (listName.toLowerCase() == companyList[i].split('|')[0].toLowerCase() && companyList[i].split('|')[1] != listID)
            {
                return confirm('This list already exists.\n Are you sure you want to owerwrite it?');         
            }
        }
		// TODO Bela - listnames with "," - BUG !!!
		/*
		var str = document.getElementById('ctl00_contentRight_toolListDataGridCompany_CompanyListNames').value;
		var companyList = str.split(',');
		//var a = str.replace('""', '"');
		//var companyList = {eval(str)};
		//var companyList = { document.getElementById('ctl00_contentRight_toolListDataGridCompany_CompanyListNames').value };
		
		
		var companyList = document.getElementById('ctl00_contentRight_toolListDataGridCompany_CompanyListNames').value;
		for (k in companyList) 
		{
		    if (companyList[k].toLowerCase() == listName.toLowerCase() && k != listID)
		        return confirm('This list already exists.\n Are you sure you want to owerwrite it?');
		}*/
        return true;
	}	
}

//-------------------------------------------------------------------------------------------------
// Used to open Archives application and BCIQ application
//-------------------------------------------------------------------------------------------------

var Parent = null;
var Child = null;

function openArchives(theHRef)
{
    if (Parent == null) Parent = window.opener;
    try
    {
	    if (Parent && !Parent.closed)
	    {
		    
            if (Parent.top.frames.length > 1)
            {
                Parent.top.location.href = (theHRef != null ? theHRef : "../Archives/ArchiveSearch.aspx");
            }
            else
            {
                if (Parent.location.href.indexOf("/Archives/")<0)
                {
                    Parent.location.href = (theHRef != null ? theHRef : "../Archives/ArchiveSearch.aspx");
                }
            }
		    Parent.focus();
		    return;
	    }
	
	    if (Child && !Child.closed)
	    {
			if (Child.top.frames.length > 1)
			{
	            Child.top.location.href = (theHRef != null ? theHRef : "../Archives/ArchiveSearch.aspx");
	        }
	        else
	        {
	            if (Child.location.href.indexOf("/Archives/")<0)
	            {
	                Child.location.href = (theHRef != null ? theHRef : "../Archives/ArchiveSearch.aspx");
	            }
		    }
		    Child.focus();
		    return;
	    }
	    //Child = window.open((theHRef != null ? theHRef : "../Archives/ArchiveSearch.aspx"));
	    document.location.href = (theHRef != null ? theHRef : "../Archives/ArchiveSearch.aspx");
    }
    catch(e)
    {
	   Child = window.open((theHRef != null ? theHRef : "../Archives/ArchiveSearch.aspx"));
    }
}
	
function openBCIS(theHRef)
{
	if (Parent == null) Parent = window.opener;
	try
	{
	    if (Parent && !Parent.closed)
	    {
	        if (Parent.top.frames.length > 1)
	        {
	            if (Parent.top.location.href.indexOf("bciq/home.aspx") < 0)
	            {
	                Parent.top.location.href = (theHRef != null ? theHRef : "../bciq/home.aspx");
                }
            }
            else
            {
                if (Parent.location.href.indexOf("bciq/home.aspx") < 0)
	            {
	                Parent.location.href = (theHRef != null ? theHRef : "../bciq/home.aspx");
                }
            }
		    Parent.top.parent.window.focus();
		    return;
	    }
	    
	
	    if (Child && !Child.closed)
	    {
	        if (Child.top.frames.length > 1)
	        {
	            if (Child.top.location.href.indexOf("bciq/Common/start.aspx") < 0)
	            {
	                Child.top.location.href = (theHRef != null ? theHRef : "../bciq/home.aspx");
                }
            }
            else
            {
                if (Child.location.href.indexOf("bciq/home.aspx") < 0)
	            {
	                Child.location.href = (theHRef != null ? theHRef : "../bciq/home.aspx");
                }
            }
		    Child.focus();
		    return;
	    }
	    //Child = window.open((theHRef != null ? theHRef : "../bciq/Common/start.aspx"));
	    document.location.href = (theHRef != null ? theHRef : "../bciq/home.aspx");
	}
	catch(e)
	{
	    Child = window.open((theHRef != null ? theHRef : "../bciq/home.aspx"));
	}
}
        


//-------------------------------------------------------------------------------
// ADD - Miha Rotar - 3/12/2008
// HELP
// Descr: open help window in the pop-up
//-------------------------------------------------------------------------------
function createHelpPopUp(helpType) 
{
    window.open('../BioCenturyHelp/MyBiocenturyTools.aspx');
}

//-------------------------------------------------------------------------------
// "Confirm Delete Selected"
//-------------------------------------------------------------------------------
function ConfirmDeleteSelectedCriteria(CriteriaListSelectionsID, CriteriaListNamesID, userId) {
    try {
        var hdnIds = document.getElementById(CriteriaListSelectionsID).value;
        if (hdnIds != "") {
            var hdnIdsArray = hdnIds.split(',');
            var hdnNames = document.getElementById(CriteriaListNamesID).value;
            // CriteriaName|CriteriaID|ProductID
            var hdnNamesArray = hdnNames.split(',');
            var name = "";
            criteriasInAlert = 0;
            for (var i = 0; i < hdnIdsArray.length - 1; i++) {
                for (var j = 0; j < hdnNamesArray.length - 1; j++) {
                    if (hdnIdsArray[i] == hdnNamesArray[j].split('|')[1]) 
                    {
                        // Bela - Reserved criteria name. Don't delete it.
                        var isBCCriteria = ReservedCriteria(hdnNamesArray[j].split('|')[0], hdnNamesArray[j].split('|')[2], userId);
                        if (isBCCriteria != "undefined" && isBCCriteria != null && isBCCriteria == "true") 
                        {
                            alert('This is a reserved criteria name. Please choose another one.');
                            return false;
                        }
                        
                        var IsCriteriaUsedInAlerts = AjaxUtilities.IsCriteriaUsed(hdnNamesArray[j].split('|')[1]);
                        if (IsCriteriaUsedInAlerts.value) {
                            if (criteriasInAlert > 0) {
                                name += ", "
                            }
                            name += "'" + hdnNamesArray[j].split('|')[0] + "'";
                            criteriasInAlert++;
                        }

                    }
                }
            }
            if (criteriasInAlert == 0) {
                return confirm("Are you sure you want to delete selected list(s)?");
            }
            else {
                if (criteriasInAlert == 1) {
                    return confirm("The " + name + " criteria list is used for email alerts. \nDeleting the criteria list will also delete the email alerts. \nAre you sure you want to delete selected criteria list?");
                }
                else {
                    return confirm("The " + name + " criteria lists are used for email alerts. \nDeleting the criteria lists will also delete the email alerts. \nAre you sure you want to delete selected criteria lists?");
                }
            }
        }
        else
            alert("You must select a Criteria List first.");
    }
    catch (err) {
        alert("Some error occured:\n" + err.message);
    }
    return false;
}

function showDiv(divName,e) 
{
    var div = document.getElementById(divName);
    div.style.visibility = "visible";
    div.style.display = "block";

    var posx = 0;
    var posy = 0;

    if (!e)
        var e = window.event;

    if (e.pageX || e.pageY) {
        posx = e.pageX + document.body.scrollLeft;
        posy = e.pageY + document.body.scrollTop;
    } else if (e.clientX || e.clientY) {
        posx = e.clientX + document.body.scrollLeft;
        posy = e.clientY + document.body.scrollTop;
    }

    // posx and posy contain the mouse position relative to the document
    // Do something with this information
    if (document.all) {
        div.style.left = posx + 20;
        div.style.top = posy + 35;
    }
    else {
        div.style.left = (posx + 20) + "px";
        div.style.top = (posy + 35) + "px";
    }
}

function hideDiv(divName) 
{
    var div = document.getElementById(divName);
    div.style.display = "none";
}

//-------------------------------------------------------------------------------
// 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;
}

function CheckIfCriteriasSelected(modalPopupExtenderID) {
    $find(modalPopupExtenderID).show();
    return false;
}

//-------------------------------------------------------------------------------
// Added by Marius 2/25/2009
// When the Submit button is clicked to save criteria
// we look if the name is reserved or it already exists
//-------------------------------------------------------------------------------
function ValidateSaveCriteriaDialog(txtCriteriaNameID, productID, userId) {
    var criteriaName = trim (document.getElementById(txtCriteriaNameID).value);
    if (criteriaName.trim().length == 0) {
        alert("Please name your Criteria before saving it");
        return false;
    }

    var isBCCriteria = ReservedCriteria(criteriaName, productID, userId);
    if (isBCCriteria != "undefined" && isBCCriteria != null && isBCCriteria == "true") 
    {
        alert('This is a reserved criteria name. Please choose another one.');
        return false;
    }

    var isReserved = CriteriaAlreadyExists(criteriaName, productID, userId);

    if (isReserved != "undefined" && isReserved != null) {
        switch (isReserved) 
        {
            case "0":
                alert('This is a reserved criteria. Please choose another name.');
                return false;
            case "1":
                document.getElementById(selectedCriteriaID).value = "";
                return true;
            default:
                var isCriteriaUsedInEmailAlert = IsCriteriaUsedInEmailAlert(productID, criteriaName, userId)
                if (isCriteriaUsedInEmailAlert != "undefined" && isCriteriaUsedInEmailAlert != null && isCriteriaUsedInEmailAlert == "true") {
                    if (confirm('This Criteria set already exist 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 = isReserved;
                        return true;
                    }
                    else {
                        return false;
                    }
                }
                else {
                    if (confirm('This Criteria Name already exists.\n Are you sure you want to owerwrite it?')) {
                        document.getElementById(selectedCriteriaID).value = isReserved;
                        return true;
                    }
                    else {
                        return false;
                    }
                }
        }
    }

    document.getElementById(selectedCriteriaID).value = "";
    return false;
}

// title - modal popup title
// text - text to ve shown
function ShowGenericModalPopup(title, text, modalPopup) {
    document.getElementById('pGenericModalPopupTitle').innerHTML = title;
    document.getElementById('divGenericModalPopup').innerHTML = text;
    $find(modalPopup).show();
}
