// <copyright file="SelectionUtilitiesCompany.js" company="BioCentury Publications Inc."> 
// All contents Copyright © 2005-2009 BioCentury Publications, Inc. ALL RIGHTS RESERVED
// 
// http://www.biocentury.com
// </copyright>


/// <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 imgRoot = document.location.href.substring(0, document.location.href.toLowerCase().indexOf('bciq') + 5) + 'Images/';
//-------------------------------------------------------------------------------
//used in CompanySelection.aspx, CompanySubString.aspx
//-------------------------------------------------------------------------------
function selectThis(cb) 
{
    var selectionSet = '';
    document.getElementById('hasChanged').value = 'true';
    if (popup) 
    {//search popup
        doc = window.opener.document;
        if (module == 'cp') 
        {
            if (cb.checked) 
            {
                var oldID = (document.getElementById(hdnTempSelectionSetId).value == '') ? ' ' : document.getElementById(hdnTempSelectionSetId).value;
                if (document.getElementById(oldID))
                    document.getElementById(oldID).checked = false;
                document.getElementById(hdnTempSelectionSetId).value = cb.id;
            }
        }
    }
    else 
    {
        //main company page
        doc = document;
        if (module == 'cp') 
        {
            if (cb.checked) 
            {
                selectionSet = document.getElementById(SearchSelectionSetID);
                var oldID = selectionSet.value.split(',')[0];
                if (oldID != "" && oldID != cb.id && document.getElementById(oldID))
                    document.getElementById(oldID).checked = false;
            }
            document.getElementById('SelectionSet').value = '';
            document.getElementById(divSummaryId).innerHTML = '';
        }
    }
}

function getSummary() 
{
    document.getElementById(hdnSummaryId).value = document.getElementById(divSummaryId).innerHTML;  
}

//-------------------------------------------------------------------------------
// ADD - Eugen Popa
// used in CompanySelection.aspx and CompanySubString.aspx
// Submit button
//-------------------------------------------------------------------------------
function showCP() {
    //alert('show cp');

    var companyID = '';
    var companyName = '';
    var selectionArray = [];
    var spans = document.getElementsByTagName('span');
    for (var i = 0; i < spans.length; i++) {
        if (spans[i].getAttribute('name') == 'summary') {
            companyID = spans[i].id.split('=')[1];
            companyName = spans[i].innerHTML.split('&nbsp;')[3].split('<')[0];
            break;
        }
    }
    if (companyID == "") {
        alert('You must select a company.');
        return false;
    }
    if (popup) {//search popup
        window.opener.document.location.href = '../Company/CompanyProfile.aspx?CompanyID=' + companyID;
        window.close();
    }
    else {//main company selection page
        selectionArray[selectionArray.length] = 'idCompanyID=' + companyID;
        //eval("self.parent.LeftFrame.theCompanySelections = selectionArray; ");
        document.getElementById(hdnSummaryId).value = document.getElementById(divSummaryId).innerHTML;
        //if (document.getElementById('company').checked)
        //    document.getElementById('search').value = companyName;
        location.href = '../Company/CompanyProfile.aspx?CompanyID=' + companyID;
    }
}

function confirmCompanyReset() 
{
    var result = confirm('This will reset all. Continue?');
    return result;
}


function DoReselectCompanies(chart, aSearchSet, doc) {
    if (doc == null) doc = document;   

    if (aSearchSet == '') 
    {
        doc.getElementById("hasChanged").value = 'false';
        var theSelections = [];
        var hdnSessionID = eval("hdnCompanySelectionSessionID;");
        if (eval("document.getElementById('" + hdnSessionID + "')") != null) {
            theSelections = eval("document.getElementById('" + hdnSessionID + "')").value.split(',');
        }
        else
            return;

        for (var i = 0; i < theSelections.length; i++) {
            if (document.getElementById(theSelections[i])) {
                doc.getElementById(theSelections[i]).checked = true;
                if (chart != '1') {
                    if (document.getElementById(theSelections[i]))
                        selectAll(document.getElementById(theSelections[i]), chart);
                }
            }
        }
    }
    else {
        DoReselectAfterSearchMM(aSearchSet, 0, doc);
    }
    createSummaryDivMM(aSearchSet, 0, doc, 'CompanySelection');
}

function CheckIfCompaniesSelectedAnalyst(companyIdsHiddenID, modalPopupExtenderID) {
    if (document.getElementById(companyIdsHiddenID) != null && document.getElementById(companyIdsHiddenID).value != "") {
        var popup = $find(modalPopupExtenderID);
        popup.show();
        return false;
    }
    else {
        alert('You must select at least one company.');
        return false;
    }
}

function DeleteSelectedCompanies(checkAllID, selected) {
    if (selected != null && selected.replace(',', '') != "") {
        if (document.getElementById(viewOnlySelectedID).value == "false" && document.getElementById(checkAllID).checked) {
            return confirm("You selected all companies. Delete list?");
        }
        else {
            return confirm("Are you sure you want to delete selected companies?");
        }
    }
    else {
        alert("You must select at least one company.");
        return false;
    }
}


function GetSelectionSetNames() {

    var summaryIDs = document.getElementsByTagName('span'); 
	var inactive = 0;
	var isSomethingSelect = false;
	var namesArray = [];
	for(var i=0;i<summaryIDs.length;i++)
	{
		if (summaryIDs[i].attributes['name'] && summaryIDs[i].attributes['name'].value == 'summary')
		{ 
			var cbID = summaryIDs[i].id.split('_')[1];
			isSomethingSelect = true;			
			namesArray[namesArray.length] = GetInnerText_IE_FireFox(summaryIDs[i]);
			if (document.getElementById('a_'+cbID))
				inactive++;
		}
	}
	if (!isSomethingSelect) {
	    alert(m_strMessageUnselection);
	    return false;
	}
	else {
	    document.getElementById(SearchSelectionSetNamesID).value = namesArray.join('|') + '|';
	}
}

function doSearchCompany(module) {
    if (document.getElementById('txtSearch').value == '') {
        alert('Please fill in the textbox.');
        return false;
    }
    else if (document.getElementById('txtSearch').value.length < 3) {
        alert('Please enter at least 3 characters.');
        return false;
    }
    else {
        window.open('../Common/PopUpPage.aspx?ControlType=CompanySubString&module='+module+'&divSummaryID=' + divSummaryId + '&searchSelectionSetID=' + SearchSelectionSetID + '&str=' + document.getElementById('txtSearch').value, '_blank', 'status=yes,toolbar=no,resizable=yes,menubar=no,scrollbars=yes');
    }
}

function SaveList(css, companyIdsHiddenID, IsPopup) {
    if (document.getElementById(companyIdsHiddenID) == null || document.getElementById(companyIdsHiddenID).value == "") {
        alert('You must select at least one company.');
        return false;
    }

    if (saveWindow == null) {
        leftVal = (screen.width - 500) / 2;
        topVal = (screen.height - 150) / 2;
        if (window.showModalDialog) {
            saveWindow = window.showModalDialog("../Common/SaveCompanyList.aspx?css=" + css + "&IsPopup="+IsPopup, window, 'dialogWidth:500px;dialogHeight:150px;dialogLeft:' + leftVal + ';dialogTop:' + topVal);
        }
        else {
            saveWindow = window.open("../Common/SaveCompanyList.aspx?css=" + css + "&IsPopup=" + IsPopup, "_blank", 'width=500px,height=150px,left=' + leftVal + ',top=' + topVal + ',toolbar=0,resizable=0,modal=yes');
        }
        return false;
    }
    else {
        saveWindow.close();
        if (document.getElementById('btnSaveSelectionsClicked').value == "1") {
            document.getElementById('CompanyListSelections').value = strAllCompanies;
            return true;
        }
        else {
            saveWindow = window.open("../Common/SaveCompanyList.aspx?css=" + css + "&IsPopup=" + IsPopup, "_blank", 'width=500,height=150,left=' + leftVal + ',top=' + topVal + ',toolbar=0,resizable=0');
            return false;
        }
    }
}

//bool = true from Save and false from Cancel 
//button is the button
function validateCompanySaveDialog(bool, button, isPopup, userId)
{
    //close window if parent is closed
    var openerWindow;
    try {
        if (window.dialogArguments ) {
            openerWindow = window.dialogArguments;
        }
        else {
            openerWindow = window.opener;
        }
    }
    catch (e) {
        window.close();
        return false;
    }

    if (button == '') button = 'btnSaveSelections';
    if (bool) {
        var listName = trim (document.getElementById('CompanyListName').value);
        var strListName = new String(listName);
        
        if (strListName.length !== 0) 
            strListName=strListName.replace(/^\s+|\s+$/g, '');
    
        if (strListName == "") {
            alert("Please name your list before saving it.");
            return false;
        }

        var isBCList = SynchronAJAX(listName, userId);

        if (isBCList != "undefined" && isBCList != null && isBCList == "true") {
            alert('This is a reserved list name. Please choose another one.');
            return false;
        }
        exists = false;
        if (isPopup) {
            //nameList = openerWindow.window.opener.document.getElementById(openerWindow.window.nameListDropDownID);
            isReserved = CompanyListAlreadyExists(listName);
            if (isReserved != -1) {
                exists = true;
            }
        }
        else {
            nameList = openerWindow.document.getElementById(openerWindow.window.nameListDropDownID);
            //hdnSelected = openerWindow.document.getElementById(openerWindow.window.hdnSelectedCompanyListID);
            
            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, userId)
            if (isListUsedInEmailAlert != "undefined" && isListUsedInEmailAlert != null && isListUsedInEmailAlert == "true") 
            {
                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 
            {
                if (!confirm('This list already exists.\n Are you sure you want to owerwrite it?')) 
                {
                    return false;
                }
            }
        }

        openerWindow.document.getElementById(openerWindow.hdnNewCompanyListID).value = document.getElementById('CompanyListName').value;
        openerWindow.document.getElementById(openerWindow.hdnNewCompanyListDescriptionID).value = document.getElementById('CompanyListDescription').value;


        if (button != 'btnSaveSelections') openerWindow.saveWindow = null;
            openerWindow.document.getElementById(eval("openerWindow." + button + "ClickedID")).value = '1';

            eval("openerWindow.__doPostBack('" + eval("openerWindow." + button + "ClickedID") + "','')");
            window.close();
            if (!isPopup) {
                removeDiv(true);
            }
        return true;
    }
    else {//Cancel button
        if (button != 'btnSaveSelections') openerWindow.saveWindow = null;
        eval("var b = openerWindow.document.getElementById('" + button + "Clicked');");
        if (b != null)
            eval("openerWindow.document.getElementById('" + button + "Clicked').value = '0';");
        window.close();
        return false;
    }
}




//-------------------------------------------------------------------------------
// Created by Mihai on 17 April 2009	
// used in Save Company List 
//-------------------------------------------------------------------------------
function ValidateSaveDialogForSameList(listName, userId) 
{
    var isListUsedInEmailAlert = IsListUsedInEmailAlert(trim(listName), userId)
    if (isListUsedInEmailAlert != "undefined" && isListUsedInEmailAlert != null && isListUsedInEmailAlert == "true") 
    {
        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 
        {
            return true;
        }
    }
}

//-------------------------------------------------------------------------------
// Createt by Mihai on 19 May 2009	
// used in CompanyProfile.ascx for Archives Items 
//-------------------------------------------------------------------------------
function CollapseExpandTree(id, parentState) {
    var divs = document.getElementsByTagName('div');
    var count = 0;
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].getAttribute('name') == id) {
            if (divs[i].className == 'hiddenRow') {
                if (parentState == null || parentState == 'visible') {
                    divs[i].className = 'visibleRow';
                    document.getElementById('img' + id).src = document.getElementById('img' + id).src.replace('expand', 'collapse');
                }
                if (divs[i].id != "" && document.getElementsByName(divs[i].id))
                    CollapseExpandTree(divs[i].id, 'visible');

            }
            else {
                if (parentState == null || parentState == 'hidden') {
                    divs[i].className = 'hiddenRow';
                    document.getElementById('img' + id).src = document.getElementById('img' + id).src.replace('collapse', 'expand');
                }
                if (divs[i].id != "" && document.getElementsByName(divs[i].id))
                    CollapseExpandTree(divs[i].id, 'hidden');
            }
        }
    }
}

//-------------------------------------------------------------------------------
// Createt by Mihai on 19 May 2009	
// used in CompanyProfile.ascx for Archives Items 
//-------------------------------------------------------------------------------
var openeeHandler = null;
function createPopUp(urlString) {
    openeeHandler = window.open(urlString, 'popUpContent', 'directories=no,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=yes');
}