/***************************************************************************************************
 * Copyright 2009 Thomson Reuters Global Resources.
 * All Rights Reserved.  Proprietary and confidential information of TRGR.
 * Disclosure, use, or reproduction without the written authorization of TRGR is prohibited.
 **************************************************************************************************/

//--------------------------------------------------------------------------------
//When adding a new popup window, need to add new elements to both arrays below
//and a define in right_frame_include.jsp as well.
//--------------------------------------------------------------------------------
var relativeToOpener = true;
var isInitialized = false;
var sslDomain = "";
var sensitiveUrl = "";
var workReqParm = "";
var tbWinName = "";
var tbWinUrl = "";
var isRsrch = true;
var rsrchUrl = "";
var gotoRsrchParm = "";
var webAppName = "Checkpoint";

popupWindows = new Array();
var windowsHeight = new Array();
var windowsWidth  = new Array();
var windowsAttrs  = new Array();
var windowsSecure  = new Array();
var windowsMain  = new Array();  // says popup should only be opened from the main window
var windowsExpandable  = new Array(); //says the window is expandable based on the screen resolution
var windowsRsrchOnly  = new Array(); //window should only be displayed from the research tab
var optsPopupWindowsToClose = new Array(); //windows on options page to close when clicking new link

var aboutRelWinName = "aboutRel";
var aboutThesaurusWin = "aboutThes";
var addCredentialWinName = "addCredential";
var advancedWinName = "advQuery";
var ageCalcWinName="ageCalculateWinName";
var changePasswordWinName = "ChangePasswordPrompt";
var chwzFullDocRowWin = "chwzFullDocRow";
var citExpInfo = "citExpInfo";
var copyTextWinName = "CopyText";
var costBasisPlusWinName = "CostBasisPlus";
var doneDealsWinName = "DoneDeals";
var dbListWindowName = "DatabaseNameList";
var emailWinName = "EmailForm";
var exportWinName = "ExportPreview";
var externalLinkWinName = "ExternalLink";
var fasbCodeStrucWinName = "fasbCodify";
var goSystemFormsRSWinName = "GoSystemFormsRS";
var goSystemTaxRSWinName = "GoSystemTaxRS";
var helpWinName = "help";
var imageWindowName = "ImageWindow";
var insourceExpressRSWinName = "InSourceExpressRS";
var intlTaxExpertWinName = "IntlTaxExpert";
var linkWindowName = "LinkWindow";
var newUserSetupSmallWinName = "newUserSetupSmallWinName";
var newUserSetupMediumWinName = "newUserSetupMediumWinName";
var newUserSetupLargeWinName = "newUserSetupLargeWinName";
var newsWglHelpWinName = "newsWglHelpWinName";
var notificationWinName = "UserNotification";
var optsHelpWinName = "optsHelp";
var optionsWizardWinName = "optionsWizardWinName";
var passwordRequirements = "passwordRequirements";
var payrollCalcWinName="calcWindow";
var ppcEToolsWinName = "PPCETools";
var wglEToolsWinName = "WGLETools";
var popupCalendar = "popupCalendar";
var printMultiDocWinName = "printMultiDocWin";
var printPrevWinName = "PrintPreview";
var profitCentsWinName = "ProfitCents";
var protocolSwitchWinName = "changeProtocolWin";
var returnSourceWinName = "returnSourceWinName";
var savNoteWinName = "savNotePrompt";
var schedSrchAlertWinName = "ScheduledSearchResults";
var schedSrchHelpWinName = "SchedSearchHelp";
var secItemWinName = "secItemWindow";
var secSicWinName = "secSicWindow";
var secFindWinName = "secFindWindow";
var secGroupWinName = "secGroupWindow";
var secCompWindow = "secCompWindow";
var selectFolderWinName = "docFolder";
var srchRelLinkWinName = "srchRelLinkWindow";
var surtsWinName = "surtsWindow";
var tellWinName = "tellMeMore";
var tocSrchHelpWinName = "tocSrchHelp";
var xmlDocViewWinName = "xmlDocViewWin";
var stateTaxApportWinName = "osa";

/*---------------------------------------------------------------------------------
Note: if the docAssemWinName var below is renamed, change must also be made in
	doc assembly section of the properties file PersistItemDisplay.properties.
----------------------------------------------------------------------------------*/
var docAssemWinName = "docAssemWin";
var docAssemHelpWinName = "IAHelp";
var docAssemInlineHelpWinName = "IAInlineHelp";
var docAssemPopupWinName = "IAPopUp";
var docAssemAnswersWinName = "docAssemAnswersWin";
var saveGenericItemWinName = "savGenItemWin";

popupWindows[aboutRelWinName] 			= null;
popupWindows[aboutThesaurusWin]         = null;
popupWindows[addCredentialWinName]		= null;
popupWindows[advancedWinName] 			= null;
popupWindows[changePasswordWinName]		= null;
popupWindows[chwzFullDocRowWin]         = null;
popupWindows[citExpInfo]                = null;
popupWindows[copyTextWinName] 			= null;
popupWindows[dbListWindowName] 			= null;
popupWindows[docAssemAnswersWinName]	= null;
popupWindows[docAssemWinName]		    = null;
popupWindows[emailWinName] 			    = null;
popupWindows[exportWinName] 			= null;
popupWindows[externalLinkWinName] 		= null;
popupWindows[fasbCodeStrucWinName] 		= null;
popupWindows[goSystemTaxRSWinName]		= null;
popupWindows[goSystemFormsRSWinName] 	= null;
popupWindows[helpWinName] 			    = null;
popupWindows[imageWindowName] 			= null;
popupWindows[insourceExpressRSWinName]	= null;
popupWindows[linkWindowName] 			= null;
popupWindows[newUserSetupLargeWinName]  = null;
popupWindows[newUserSetupMediumWinName] = null;
popupWindows[newUserSetupSmallWinName]  = null;
popupWindows[newsWglHelpWinName]        = null;
popupWindows[notificationWinName]		= null;
popupWindows[optionsWizardWinName]      = null;
popupWindows[optsHelpWinName] 			= null;
popupWindows[passwordRequirements]      = null;
popupWindows[payrollCalcWinName]        = null;
popupWindows[popupCalendar]             = null;
popupWindows[printMultiDocWinName]		= null;
popupWindows[printPrevWinName] 			= null;
popupWindows[protocolSwitchWinName]		= null;
popupWindows[returnSourceWinName]		= null;
popupWindows[saveGenericItemWinName]    = null;
popupWindows[savNoteWinName]			= null;
popupWindows[secCompWindow]		        = null;
popupWindows[secFindWinName]		    = null;
popupWindows[secGroupWinName]		    = null;
popupWindows[secItemWinName]			= null;
popupWindows[secSicWinName]		        = null;
popupWindows[srchRelLinkWinName]		= null;
popupWindows[tocSrchHelpWinName] 		= null;
popupWindows[schedSrchHelpWinName] 		= null;
popupWindows[schedSrchAlertWinName]     = null;
popupWindows[selectFolderWinName] 		= null;
popupWindows[surtsWinName]		        = null;
popupWindows[tellWinName] 			    = null;
popupWindows[xmlDocViewWinName]		    = null;
popupWindows[stateTaxApportWinName]     = null;

function initArrays() {
	if (!isInitialized) {
		windowsWidth[secSicWinName]		= 500;
		windowsHeight[secSicWinName]		= 500; //reduced from the screen height
		windowsAttrs[secSicWinName] = ",status,resizable,scrollbars";

		windowsWidth[srchRelLinkWinName]		= 762;
		windowsHeight[srchRelLinkWinName]		= 380;
		windowsAttrs[srchRelLinkWinName] = ",status,resizable,scrollbars";

		windowsWidth[secFindWinName]		= 640;
		windowsHeight[secFindWinName]		= 470; //reduced from the screen height
		windowsAttrs[secFindWinName] = ",status,resizable,scrollbars";

		windowsWidth[secCompWindow]		= 340;
		windowsHeight[secCompWindow]		= 285; //reduced from the screen height
		windowsAttrs[secCompWindow] = ",status,resizable,scrollbars";

		windowsWidth[citExpInfo]		= 500;
		windowsHeight[citExpInfo]		= 395; //reduced from the screen height
		windowsAttrs[citExpInfo] = ",status,resizable,scrollbars";

        windowsWidth[popupCalendar]		= 505;
		windowsHeight[popupCalendar]		= 325; //reduced from the screen height
		windowsAttrs[popupCalendar] = ",status,resizable,scrollbars";

        windowsWidth[secGroupWinName]		= 560;
		windowsHeight[secGroupWinName]		= 300; //reduced from the screen height
		windowsAttrs[secGroupWinName] = ",status,resizable,scrollbars";

		windowsWidth[secItemWinName]		= 640;
		windowsHeight[secItemWinName]		= 320; //reduced from the screen height
		windowsAttrs[secItemWinName] = ",status,resizable,scrollbars";

		windowsWidth[docAssemWinName]		= 615;
		windowsHeight[docAssemWinName]		= 500; //reduced from the screen height
		windowsSecure[docAssemWinName]		= 1;
		windowsAttrs[docAssemWinName] = ",status,resizable,scrollbars";
		windowsMain[docAssemWinName]		= true;// make docAssem be opened from main window
		windowsExpandable[docAssemWinName] = true;
		windowsRsrchOnly[docAssemWinName] = true;

		windowsWidth[docAssemHelpWinName]		= 500;
		windowsHeight[docAssemHelpWinName]		= 600;
		windowsAttrs[docAssemHelpWinName] = ",status,resizable,scrollbars";

		windowsWidth[docAssemInlineHelpWinName]		= 500;
		windowsHeight[docAssemInlineHelpWinName]		= 600;
		windowsAttrs[docAssemInlineHelpWinName] = ",status,resizable,scrollbars";

		windowsWidth[docAssemPopupWinName]		= 500;
		windowsHeight[docAssemPopupWinName]		= 600;
		windowsAttrs[docAssemPopupWinName] = ",status,resizable,scrollbars";

        windowsWidth[externalLinkWinName]  = 600;
		windowsHeight[externalLinkWinName] = 300;
		windowsAttrs[externalLinkWinName] = ",menubar,resizable,scrollbars,toolbar,location,directories";

		windowsWidth[saveGenericItemWinName]  = 545;
		windowsHeight[saveGenericItemWinName] = 480;

		windowsWidth[selectFolderWinName]  = 320;
		windowsHeight[selectFolderWinName] = 350;

		windowsWidth[docAssemAnswersWinName]  = 575;
		windowsHeight[docAssemAnswersWinName] = 400;
		windowsExpandable[docAssemAnswersWinName] = true;

		windowsWidth[savNoteWinName]  = 450;
		windowsHeight[savNoteWinName] = 165;

		windowsWidth[schedSrchHelpWinName]  = 500;
		windowsHeight[schedSrchHelpWinName] = 350;

        windowsWidth[newsWglHelpWinName]  = 500;
		windowsHeight[newsWglHelpWinName] = 350;

        windowsWidth[exportWinName]  = 600;
		windowsHeight[exportWinName] = 450;
		windowsAttrs[exportWinName] = ",menubar,resizable,scrollbars";
		windowsExpandable[exportWinName] = true;

		windowsWidth[emailWinName]  = 650;
		windowsHeight[emailWinName] = 620;
		windowsAttrs[emailWinName] = ",resizable,scrollbars";

        windowsWidth[copyTextWinName]  = 600;
		windowsHeight[copyTextWinName] = 350;
		windowsAttrs[copyTextWinName] = ",resizable";

		windowsWidth[printPrevWinName]  = 600;
		windowsHeight[printPrevWinName] = 450;
		windowsAttrs[printPrevWinName] = ",menubar,resizable,scrollbars";
		windowsExpandable[printPrevWinName] = true;

		windowsWidth[selectFolderWinName]  = 320;
		windowsHeight[selectFolderWinName] = 350;

		windowsWidth[imageWindowName]  = 600;
		windowsHeight[imageWindowName] = 450;
		windowsAttrs[imageWindowName] = ",menubar,resizable,scrollbars";
		windowsExpandable[imageWindowName] = true;

		windowsWidth[schedSrchAlertWinName]  = 650;
		windowsHeight[schedSrchAlertWinName] = 350;

		windowsWidth[goSystemFormsRSWinName]  = 925;
		windowsHeight[goSystemFormsRSWinName] = 675;
		windowsAttrs[goSystemFormsRSWinName] = ",menubar,status,resizable,scrollbars,toolbar,location,directories";

		windowsWidth[costBasisPlusWinName]  = 785;
		windowsHeight[costBasisPlusWinName] = 675;
		windowsAttrs[costBasisPlusWinName] = ",menubar,status,resizable,scrollbars,toolbar,location,directories";

        windowsWidth[doneDealsWinName]  = 900;
		windowsHeight[doneDealsWinName] = 700;
		windowsAttrs[doneDealsWinName] = ",menubar,status,resizable,scrollbars,toolbar,location,directories";

        windowsWidth[intlTaxExpertWinName]  = 785;
        windowsHeight[intlTaxExpertWinName] = 585;
        windowsAttrs[intlTaxExpertWinName] = ",menubar,status,resizable,scrollbars,toolbar,location,directories";

		windowsWidth[profitCentsWinName]  = 785;
		windowsHeight[profitCentsWinName] = 500;
		windowsAttrs[profitCentsWinName] = ",menubar,status,resizable,scrollbars,toolbar,location,directories";

		windowsWidth[ppcEToolsWinName]  = 425;
		windowsHeight[ppcEToolsWinName] = 250;
		windowsAttrs[ppcEToolsWinName] = ",status,resizable,scrollbars";

        windowsWidth[wglEToolsWinName]  = 425;
		windowsHeight[wglEToolsWinName] = 250;
		windowsAttrs[wglEToolsWinName] = ",status,resizable,scrollbars";

        windowsWidth[goSystemTaxRSWinName]  = 600;
		windowsHeight[goSystemTaxRSWinName] = 600;
		windowsAttrs[goSystemTaxRSWinName] = ",resizable,scrollbars";

		windowsWidth[insourceExpressRSWinName]  = 600;
		windowsHeight[insourceExpressRSWinName] = 600;
		windowsAttrs[insourceExpressRSWinName] = ",resizable,scrollbars";

		windowsWidth[surtsWinName]  = 600;
		windowsHeight[surtsWinName] = 400;

		windowsWidth[addCredentialWinName]  = 380;
		windowsHeight[addCredentialWinName] = 400;
		windowsAttrs[addCredentialWinName] = ",status,resizable";
		windowsSecure[addCredentialWinName]= 1;

		windowsWidth[helpWinName]  = 750;
		windowsHeight[helpWinName] = 450;

        windowsWidth[optsHelpWinName]  = 550;
		windowsHeight[optsHelpWinName] = 450;

		windowsWidth[tocSrchHelpWinName]  = 550;
		windowsHeight[tocSrchHelpWinName] = 450;

		windowsWidth[changePasswordWinName]  = 575;
		windowsHeight[changePasswordWinName] = 300;
		windowsAttrs[changePasswordWinName] = ",status,resizable";

		windowsWidth[advancedWinName]  = 525;
		windowsHeight[advancedWinName] = 400;

		windowsWidth[protocolSwitchWinName]  = 450;
		windowsHeight[protocolSwitchWinName] = 150;
		windowsAttrs[protocolSwitchWinName] = ",resizable";

		windowsWidth[aboutRelWinName]  = 500;
		windowsHeight[aboutRelWinName] = 200;

		windowsWidth[aboutThesaurusWin]  = 550;
		windowsHeight[aboutThesaurusWin] = 300;

		windowsWidth[tellWinName]  = 500;
		windowsHeight[tellWinName] = 350;

		windowsWidth[secItemWinName]		= 640;
		windowsHeight[secItemWinName]		= 320; //reduced from the screen height
		windowsAttrs[secItemWinName] = ",status,resizable,scrollbars";
		windowsMain[secItemWinName]		= true;// make docAssem be opened from main window

		windowsWidth[returnSourceWinName]  = 650;
		windowsHeight[returnSourceWinName] = 600;
		windowsAttrs[returnSourceWinName] = ",resizable,scrollbars";
		windowsSecure[returnSourceWinName]= 1;
		windowsMain[returnSourceWinName]= true;

		windowsWidth[xmlDocViewWinName]  = 650;
		windowsHeight[xmlDocViewWinName] = 600;
		windowsAttrs[xmlDocViewWinName] = ",resizable,scrollbars";

		windowsWidth[newUserSetupSmallWinName]  = 600;
		windowsHeight[newUserSetupSmallWinName] = 265;
		windowsAttrs[newUserSetupSmallWinName] = ",resizable,scrollbars";

		windowsWidth[newUserSetupMediumWinName]  = 600;
		windowsHeight[newUserSetupMediumWinName] = 500;
		windowsAttrs[newUserSetupMediumWinName] = ",resizable,scrollbars";

		windowsWidth[newUserSetupLargeWinName]  = 600;
		windowsHeight[newUserSetupLargeWinName] = 550;
		windowsAttrs[newUserSetupLargeWinName] = ",resizable,scrollbars";

        windowsWidth[optionsWizardWinName]  = 750;
		windowsHeight[optionsWizardWinName] = 550;
		windowsAttrs[optionsWizardWinName] = ",resizable,scrollbars";

        windowsWidth[passwordRequirements]  = 500;
		windowsHeight[passwordRequirements] = 215;
		windowsAttrs[passwordRequirements] = ",status";

		windowsWidth[ageCalcWinName]		= 450;
		windowsHeight[ageCalcWinName]		= 155;
		windowsAttrs[ageCalcWinName] = ",status,resizable,scrollbars";

		windowsWidth[payrollCalcWinName]		= 675;
		windowsHeight[payrollCalcWinName]		= 500;
		windowsAttrs[payrollCalcWinName] = ",status,resizable,scrollbars";

		windowsWidth[chwzFullDocRowWin]		= 550;
		windowsHeight[chwzFullDocRowWin]		= 320;
		windowsAttrs[chwzFullDocRowWin] = ",status,resizable,scrollbars";

        windowsWidth[fasbCodeStrucWinName]	= 750;
        windowsHeight[fasbCodeStrucWinName]	= 550;
        windowsAttrs[fasbCodeStrucWinName] = ",status,resizable";

        windowsWidth[stateTaxApportWinName] = 1000;
        windowsHeight[stateTaxApportWinName] = 700;
        windowsAttrs[stateTaxApportWinName] = ",resizable,toolbar,location,scrollbars";

        //these are the windows on the options page we want to cleanup (close)
        //if the user clicks on another link in options when the window is open.
        optsPopupWindowsToClose[addCredentialWinName] = addCredentialWinName;
        optsPopupWindowsToClose[tellWinName] = tellWinName;
        optsPopupWindowsToClose[newUserSetupSmallWinName] = newUserSetupSmallWinName;
        optsPopupWindowsToClose[aboutRelWinName] = aboutRelWinName;
        optsPopupWindowsToClose[aboutThesaurusWin] = aboutThesaurusWin;
        optsPopupWindowsToClose[optsHelpWinName] = optsHelpWinName;

        isInitialized = true;
	}
}

/* window.open and focus functionality in one place and easy to find. */
function openWindowWithFocus(url, name, features) {
    var aNewWin = openCPWindow(url, name, features);
    if (aNewWin != null) {
        aNewWin.focus();
    }
}

/* window.open and focus functionality in one place and easy to find. */
function getOpenWindowWithFocus(url, name, features) {
    var aNewWin = openCPWindow(url, name, features);
    if (aNewWin != null) {
        aNewWin.focus();
    }
    return aNewWin;
}

/** window.open functionality in one place and easy to find. This function should be used
instead of window.open. Also use this to call window.open so that we can alert user if if didn't open properly.   */
function openCPWindow(url, name, features) {
   var wCallee =  window.open(url, name, features);
   // var wCallee = null;
   if (openWindowFailed(wCallee)) {
       alertUnableToOpenWindow();
   }
   return wCallee;
}

/** alert to let the user know a window could not be opened */
function alertUnableToOpenWindow() {
    alert(webAppName + " is unable to open the requested window.  This may be due to a popup blocker.  Please make sure ["+cpFrame.location.hostname+"] is in the allowed sites list for your browser\'s popup blocker.");
}

/** check to see if the window opened correctly */
function openWindowFailed(wCallee) {
    return wCallee == null || typeof(wCallee)=="undefined";
}
/**used for opening simple content windows that will not be closed. */
function openWindowNotTracked(uniqueId, url) {
    /** here we use the getSaveFeatures from the preview pop up window because they are the size we want. */
    var windowFeatures = cpFrame.previewWinPopUp.getSaveFeatures();
    // make sure no invalid characters in name
    uniqueId = uniqueId.replace(/(\W)/g, "x");
    openWindowWithFocus(url, uniqueId, windowFeatures);
    return false;
}

/** need a separate function to open the login page window stuff because the windows are not initialized
 at this point so can't use the pop up stuff */
function openLoginPageWindow(pageToLoad, winName, width, height, center, resizable, scrollbars) {

    xposition=0; yposition=0;
    if ((parseInt(navigator.appVersion) >= 4) && (center)) {
        xposition = (screen.width - width) / 2;
        yposition = (screen.height - height) / 2;
    }
    args = "width=" + width + ","
    + "height=" + height + ","
    + "location=0,"
    + "menubar=0,"
    + "resizable=" + resizable + ","
    + "scrollbars=" + scrollbars + ","
    + "status=0,"
    + "titlebar=0,"
    + "toolbar=0,"
    + "hotkeys=0,"
    + "screenx=" + xposition + ","
    + "screeny=" + yposition + ","
    + "left=" + xposition + ","
    + "right=" + yposition;
    openWindowWithFocus(pageToLoad, winName, args);
}

/**
 * Method called to give focus to popups that may have been opened before the
 * mainFs is fully loaded - so not have focus.
 */
function focusPopups() {
	for (windName in popupWindows) {
        if (popupWindows[windName] != null) {
            var windHandle = popupWindows[windName];
            var wCHandleType  = typeof windHandle.wCalleeHandle;
            if (!(wCHandleType == "unknown" || wCHandleType == "undefined")) {
                //Make sure the window still open before setting focus, otherwise error occurs
                if (!windHandle.wCalleeHandle.closed) {
                    windHandle.wCalleeHandle.focus();
                }
            }
        }
	}
}

/**
 * Generic display window method. We use this method when we need to keep track of the open window if Checkpoint is closed.
 * We also need to use this method when ssl is involved. Also, good to use when pop-up blocker may be involved - places
 * where the browser tries to open a window onload method or a timer for example.
 */
function displayPopupWindow(windName, url, wCallingHandle) {

	initArrays();
	var mainWin = null;
	if (cpFrame.opener != null) {
		mainWin = findCheckpointFrame(cpFrame.opener);
	}
	if (windowsMain[windName] && mainWin != null && mainWin != cpFrame) {
		// if the window should only be opened from the main window and this
		// is not the main - have it open the popup
		var popupWin = mainWin.getPopupControl();
		popupWin.displayPopupWindow(windName, url, wCallingHandle);
	} else {
		if (!checkCanOpenFromMain(windName, url)) {
			// some popups may need to be ssl, if so the main frame needs to
			// be redirected before opening it so we can still script between
			var windHandle = popupWindows[windName];
			if (windHandle != null &&  windHandle.wCalleeHandle != null && !windHandle.wCalleeHandle.closed &&
				!(typeof(windHandle.wCalleeHandle) == "unknown" || typeof(windHandle.wCalleeHandle) == "undefined") &&
				windHandle.wCalleeHandle.confirmClose != null && windHandle.wCalleeHandle.confirmClose() != null){
				// some popups may need to be saved before we replace them.
				if (confirm("You have unsaved changes in your current document. To save your changes, click Cancel and then Save Answers in the document window. "+
						"Otherwise, click OK to continue loading the new document without saving your changes.")) {
					windHandle.wCalleeHandle.confirm = false;
					var wCallee = openCPWindow(url, windName, getWindowFeature(windName));
					popupWindows[windName] = new windowHandle(windName, wCallingHandle, wCallee);
				    wCallee.focus();
				} else {
					windHandle.wCalleeHandle.focus();
				}
				return windHandle.wCalleeHandle;
			} else {

                var is = new Is();
                if (is.ie6 && windName == imageWindowName){
                    //wCallee.focus(); will cause a "Member not found" error for IE6
                    //occurs if there is a popup already open
                    // Grab it with blank url then close it
                    var wCallee = openCPWindow("", windName, getWindowFeature(windName));
                    if (!openWindowFailed(wCallee)){
                        wCallee.close();
                    }
                }
                // Re-open it with url and set focus to it
                wCallee = openCPWindow(url, windName, getWindowFeature(windName)); //openWindow will notify user if it fails
				if (!openWindowFailed(wCallee)) {
					popupWindows[windName] = new windowHandle(windName, wCallingHandle, wCallee);
				    wCallee.focus();
				    return wCallee;
				}
			}
		}
	}
}
/**
*  Change the top window to SSL
*/
function changeToSecure(reqId) {
	if (sslDomain != "") {
		var nurl = sslDomain + cpFrame.location.pathname + "?" + cpFrame.location.search;
		nurl = appendUrlParm(nurl, workReqParm, reqId);
		//alert("change proto url " + nurl);
		cpFrame.location = nurl;
	}
}
/**
* some popups may need to be ssl, if so the main frame needs to
* be redirected before opening it so we can still script between
* return true if the window should not be opened yet
*/

function checkCanOpenFromMain(winName, url) {
	var curProt = cpFrame.location.protocol;
	if (windowsRsrchOnly[winName] && gotoRsrchParm.length > 0) {
		var nurl = rsrchUrl;
		if (windowsSecure[winName] == 1 && sensitiveUrl != "" && curProt == "http:" && url.substring(0,5) == "https") {
			nurl = "https" + nurl.substring(4);
		}
		nurl = appendUrlParm(nurl, gotoRsrchParm, "Y");
		nurl = appendUrlParm(nurl, 'winName', winName);
		nurl = appendUrlParm(nurl, 'winUrl', url);
		cpFrame.location = nurl;
		return true;
	} else if (windowsSecure[winName] == 1 && sensitiveUrl != "" && curProt == "http:" && url.substring(0,5) == "https") {
		var nurl = sslDomain + cpFrame.location.pathname + cpFrame.location.search;
		nurl = appendUrlParm(nurl, 'winName', winName);
		nurl = appendUrlParm(nurl, 'winUrl', url);
		// alert("change proto url " + nurl);
		cpFrame.location = nurl;
		// cpFrame.location.replace(nurl);
		return true;
	}
	return false;
}

/**
 * Opens a new browser window. It will return the object reference to the newly
 * created window if ref boolean value is true. If this function is used
 * as an href target (i.e. <a href="displayLinkWindow(xxxx)">) you will NOT
 * want the reference since it will cause the object to be loaded in your
 * browser window. If you want the reference from an achor, use it as an "onclick"
 * event: <a href="#" onClick="javascript:mywindow=displayLinkWindow(xxxx)"> to
 * get the reference. Or if called from another javascript file you can just use:
 * mywindow=displayLinkWindow(xxx);
 * @param url The URL location to display in the window
 * @param name The handle of the window opened
 * @param resize yes (or 1) if the window should be resizable, no (or 0) if not
 * @param scroll yes (or 1) if the window should be scrollable, no (or 0) if not
 * @param width The width of the window in pixels
 * @param height The height of the window in pixels
 * @param ref boolean value if the reference should be returned or not.
 */
function displayLinkWindow(url, name, resize, scroll, width, height, ref ) {
	if (!checkCanOpenFromMain(name, url)){
		linkWindowName = name;
		popupWindows[linkWindowName] = openCPWindow(url, linkWindowName, "resizable="+ resize + ",scrollbars="+ scroll + ",width=" + width + ",height=" + height);
		popupWindows[linkWindowName].opener = cpFrame;
		var is = new Is();

		if (!is.ie4){
		  popupWindows[linkWindowName].focus();
		}

		if (ref == 'true')
		  return popupWindows[linkWindowName];
	}
}
// This function opens a window with the various search options -- select previous
// keywords, append connectors and thesaurus funtionality.
function DisplayAdvanced(textField, queryText, practiceArea, maxlength) {
	connectorText = textField;
	var advUrl = advancedUrl;
    var termLength = fnExist(typeof maxlength)? maxlength : 500;
    advUrl = appendUrlParm(advUrl, 'termLength', termLength);
    advUrl = appendUrlParm(advUrl, 'keywords', queryText);
	advUrl = appendUrlParm(advUrl, 'practice', practiceArea);
	displayPopupWindow(advancedWinName, advUrl);
}

/**
 * This function opens the Advanced Search popup.
 * @param queryField the query (keywords) element
 * @param practiceArea the search practice area
 * @param searchTypeField the searchType element
 */
function DisplayAdvancedSearch(queryField, practiceArea, searchTypeField) {
	connectorText = queryField;
	var advUrl = advancedUrl;
    var termLength = queryField.maxLength != "undefined" ? queryField.maxLength : 500;
    var searchType = fnExist(typeof searchTypeField) ? getSelectedRadioValue(searchTypeField) : "tnc";
    if (searchType == "" && searchTypeField.type == "hidden") {
        searchType = searchTypeField.value;
    }
    advUrl = appendUrlParm(advUrl, 'termLength', termLength);
    advUrl = appendUrlParm(advUrl, 'keywords', queryField.value);
	advUrl = appendUrlParm(advUrl, 'practice', practiceArea);
    advUrl = appendUrlParm(advUrl, 'searchType', searchType);
	displayPopupWindow(advancedWinName, advUrl);
    return false;
}

function DisplayChangePasswordPrompt(changePasswordUrl) {
	displayPopupWindow(changePasswordWinName, changePasswordUrl);
}

function DisplayCredentialMgmt(addCredentialUrl) {
	displayPopupWindow(addCredentialWinName, addCredentialUrl);
}

function DisplayReturnSourceDetails(returnSourceUrl) {
	displayPopupWindow(returnSourceWinName, returnSourceUrl);
}

function DisplayAboutRelevance(aboutRelUrl) {
	displayPopupWindow(aboutRelWinName, aboutRelUrl);
}

function DisplayTellMeMore(tellUrl) {
	displayPopupWindow(tellWinName, tellUrl);
}

/**
 * Opens the Notification window.
 *
 */
function DisplayNotificationWindow(notificationURL, notificationWindowName, notificationHeight,
										notificationWidth, notificationMenubar, notificationToolbar,
										notificationScrollbar, notificationResizable) {
    popupWindows[notificationWinName] = getOpenWindowWithFocus(notificationURL, notificationWindowName, "toolbar="+notificationToolbar +
    	",menubar=" + notificationMenubar + ",scrollbars=" + notificationScrollbar +
    	",resizable=" + notificationResizable + ",width=" + notificationWidth + ",height=" + notificationHeight);
}

/**
 * Opens the Table of Contents Search help window.
 */
function DisplayTocSearchHelp() {
	displayPopupWindow(tocSrchHelpWinName, tocSrchHelpUrl);
}

function DisplayOptionsWizard(optionsWizardUrl) {
	displayPopupWindow(optionsWizardWinName, optionsWizardUrl);
}

/**
 * Opens the Options help window.
 */
function DisplayOptsHelp() {
	displayPopupWindow(optsHelpWinName, optsHelpUrl);
}

/**
 * Opens the Help window.
 */
function DisplayHelpWindow() {
	displayPopupWindow(helpWinName, helpUrl);
}

/**
 * Opens the Sales And Use Tax Rate Lookup window.
 */
function DisplaySURTSWindow(surtsUrl) {
	displayPopupWindow(surtsWinName, surtsUrl);
}

//display the goSystemFormsRS window
function DisplayGoSystemFormsRSWindow() {
	displayPopupWindow(goSystemFormsRSWinName, goSystemFormsRSUrl);
}

//display the Cost Basis Plus window
function DisplayCostBasisPlusWindow() {
	displayPopupWindow(costBasisPlusWinName, costBasisPlusUrl);
}

//display the State Tax Apportionment Wizard window
function DisplayStateTaxApportWindow() {
	displayPopupWindow(stateTaxApportWinName, stateTaxApportUrl);
}

//display the done Deals window
function DisplayDoneDealsWindow(doneDealsUrl) {
	displayPopupWindow(doneDealsWinName, doneDealsUrl);
}

//display the International Tax Expert window
function DisplayIntlTaxExpertWindow() {
	displayPopupWindow(intlTaxExpertWinName, intlTaxExpertUrl);
}

//display the goSystemTaxRS window
function DisplayGoSystemTaxRSWindow(goSystemTaxRSUrl) {
	displayPopupWindow(goSystemTaxRSWinName, goSystemTaxRSUrl);
}

//display the insourceExpressRS window
function DisplayInsourceExpressRSWindow(inSourceExpressRSUrl) {
	displayPopupWindow(insourceExpressRSWinName, inSourceExpressRSUrl);
}

//display scheduled search result alert
function DisplaySchedSearchAlertWindow() {
	if (schedSrchAlertUrl != null &&
	    schedSrchAlertUrl != "") {
		displayPopupWindow(schedSrchAlertWinName, schedSrchAlertUrl);
	}
}

function DisplayImageWindow(imgurl) {
	displayPopupWindow(imageWindowName, imgurl);
}

//display database name window used in search history, folder search and saved search
function displayDBNames(dbNamesUrl, count) {
	var height = 500;
	if (count < 24) {
		height = (count * 20) + 20; //minimum is 100 since minimum count is 4
	}
	var width = 500;
	popupWindows[dbListWindowName] = getOpenWindowWithFocus(dbNamesUrl, dbListWindowName, getWindowFeatureWithAttribute(width, height, null, false));
}

/**
 * Display the folder list window for adding or moving items.
 */
function DisplaySelectFolder(url, wCallingHandle) {
	displayPopupWindow(selectFolderWinName, url, wCallingHandle);
}

/**
 * Display the folder list window for adding or moving items.
 */
function DisplaySavePreview(url, wCallingHandle) {
	displayPopupWindow(saveGenericItemWinName, url, wCallingHandle);
}

/**
 * Display the print preview window.
 */
function DisplayPrintPreview(url, wCallingHandle) {
	displayPopupWindow(printPrevWinName, url, wCallingHandle);
}

/**
 * Display the print preview window.
 */
function DisplayExportPreview(url, wCallingHandle) {
	displayPopupWindow(exportWinName, url, wCallingHandle);
}

/**
 * Display the email form window
 */
function DisplayEmailForm(url, wCallingHandle) {
	displayPopupWindow(emailWinName, url, wCallingHandle);
}

/**
 * Display the copy text window
 */
function DisplayCopyText(url, wCallingHandle) {
	displayPopupWindow(copyTextWinName, url, wCallingHandle);
}

/**
 * Display the external link url window
 */
function DisplayExternalLinkUrl(url, wCallingHandle) {
	displayPopupWindow(externalLinkWinName, url, wCallingHandle);
}

//display search scheduling help
function displaySchedSrchHelp() {
	displayPopupWindow(schedSrchHelpWinName, schedSrchHelpUrl);
}

//display search scheduling help  for ITDW
function displaySchedSrchITDWHelp() {
	displayPopupWindow(schedSrchHelpWinName, srchSchedITDWHelpUrl);
}

//prompt for entering the notes for Folders and folder items
function PromptSaveNote(notePromptUrl, wCallingHandle) {
	displayPopupWindow(savNoteWinName, notePromptUrl, wCallingHandle);
}

/**
 * Display the folder list window for adding or moving items.
 */
function docAssemAnswersWindow(url, wCallingHandle) {
	displayPopupWindow(docAssemAnswersWinName, url, wCallingHandle);
}

/**
 * Display fasb codification structure
 */
function showCodification(url, wCallingHandle) {
	displayPopupWindow(fasbCodeStrucWinName, url, wCallingHandle);
}

/**
* Displays the print multiple document window from toc.  This
* is a special case of displaying the popup window because of
* the fact that the toc frame could add entry in the option while
* the print multiple window is open.  But, still it's using the
* cleanupWindows function to close this window once the main frame
* is unloaded
*
* It has a static member variable and function used by the docPrintMult.jsp
*/
DisplayPrintMultiDoc.initDocID = null;
DisplayPrintMultiDoc.initTitle = null;

function DisplayPrintMultiDoc(printMultiURL, docId, docTitle) {
    //if there isn't an open window, we need to open one. If not, write to the window already opened.
    if (openWindowFailed(popupWindows[printMultiDocWinName])) {
		DisplayPrintMultiDoc.initDocID = docId;
		DisplayPrintMultiDoc.initTitle = docTitle;
		popupWindows[printMultiDocWinName] = getOpenWindowWithFocus(printMultiURL, printMultiDocWinName, getPrintMultiWindowFeatures());
	} else {
        // check to see if we're in the 15 document limit.
		// the options of the select tag is 0 based, that's the
		// reason for >= 15 condition
		if (popupWindows[printMultiDocWinName].optionLength() >= 15) {
			alert("You can print no more than 15 documents at a time.");
		} else {
			popupWindows[printMultiDocWinName].focus();
			popupWindows[printMultiDocWinName].add2PrintList(docId, docTitle);
		}
    }
}

/**
*  Use by docPrintMult.jsp to reset the array value of the popupWindows[printMultiDocWinName]
*/
DisplayPrintMultiDoc.reset = function() {
	DisplayPrintMultiDoc.initDocID = null;
	DisplayPrintMultiDoc.initTitle = null;
	popupWindows[printMultiDocWinName] = null;
};

/**
*  Use by DisplayPrintMultiDoc function.  This is a very specific window
*  location
*/
function getPrintMultiWindowFeatures() {
	var width  = 470;
	var height = 300;
	var xOffset = screen.width-width;
	var yOffset = 0;

	var features;
	var is = new Is();

	if (is.nav) {
		features =  "width="+width+",height="+height+",menubar, scrollbars,status ,resizable"+",screenX="+xOffset+",screenY="+yOffset;
	} else {	// ie
		features = "width="+width+",height="+height+",menubar, scrollbars,status ,resizable"+",left="+xOffset+",top="+yOffset;
	}
	return features;
}

function CleanupOptionsWindows() {
    for (windName in optsPopupWindowsToClose) {
        var windHandle = popupWindows[windName];
        if (windHandle != null) {
             doTheClose(windHandle);
        }
	}
}

function doTheClose(windHandle) {

    if (windHandle.close != null && !windHandle.closed) {
        // There's a close method and the window hasn't been closed already
        windHandle.close();
    } else {
        // check if it's windowHandle function
        var wCHandleType  = typeof windHandle.wCalleeHandle;
        if (!(wCHandleType == "unknown" || wCHandleType == "undefined") &&
            windHandle.wCalleeHandle != null && !windHandle.wCalleeHandle.closed) {
           if (windHandle.wCalleeHandle.forceClose != null) {
                // There's a forceClose method to prevent close warnings and the window hasn't been closed already
                windHandle.wCalleeHandle.forceClose();
            } else if (windHandle.wCalleeHandle.close != null && !windHandle.wCalleeHandle.closed) {
                windHandle.wCalleeHandle.close();
            }
        }
        // Close export window when exported into Word.  Somehow Word window cannot be closed
        // the 1st time it's open so have to open it again and then close it.
        if (windName == exportWinName && wCHandleType == "undefined") {
            //here do a window.open because we don't want error checking. Basically, we are just opening
            //the window to get a handle so that we can close it.
            popupWindows[exportWinName] = window.open(null, exportWinName, "");
            popupWindows[exportWinName].close();
        }

        // Close image window when displaying PDF in Adobe Acrobat with frameless Checkpoint.
        // Somehow Acrobat window cannot be closed the 1st time it's open so have to open it
        // again and then close it.  (windHandle.closed returns true above even though the window
        // is still open!)
        if (windName == imageWindowName && wCHandleType == "undefined") {
            //here do a window.open because we don't want error checking. Basically, we are just opening
            //the window to get a handle so that we can close it.
            popupWindows[imageWindowName] = window.open(null, imageWindowName, "");
            popupWindows[imageWindowName].close();
        }
    }
}

function CleanupWindows() {
    for (windName in popupWindows) {
		/* Do not want to close the eForms window since it would
		 * logs user out or timedout of Checkpoint. Currently, if the users are working on eForms
		 * and their Checkpoint timedout, then, the eForms window is closed. This results is loss of
		 * all work done on eForms.
		 */
		if (windName != goSystemFormsRSWinName) {
			var windHandle = popupWindows[windName];
	        if (windHandle != null){
				doTheClose(windHandle);
	        }
		}
	}
}

/**
*  This function is used as a data object
*  It holds the reference of the frame that
*  the popup window is triggered and the name
*  and reference of the popup window.
*/
function windowHandle(name, wCallingHandle, wCalleeHandle) {
	this.name = name;
	this.wCallingHandle = wCallingHandle;
	this.wCalleeHandle  = wCalleeHandle;
}

function getWHandle(wName) {
	return popupWindows[wName];
}

function resetWHandle(wName) {
	popupWindows[wName] = null;
}

/**
* Method to get the window feature and attributes for the new window.
* windName - the window name used to retrieve the appropriate dimentions and attributes.
* scrnRelative -  whether it is based on the user's screen or the CPFrame. It is screen relative if it is true.
*/
function getWindowFeature(windName) {
	var width  = windowsWidth[windName];
	var height = windowsHeight[windName];
	var attr = windowsAttrs[windName];
	var expandable = windowsExpandable[windName];
	if (expandable != true) {
		expandable = false;
	}
	return getWindowFeatureWithAttribute(width, height, attr, expandable);
}

/**
* Method to get the window feature and attributes for the new window.
* width - the width of the new window. If it is expandable it is a negative value.
* height - the height of the new window. If it is expandable it is a negative value.
* expandable -  true if the popup window is to be expandable based on the opener or screen resolution.
*/
function getWindowFeatureWithAttribute(minWidth, minHeight, attr, expandable) {
	var width = minWidth;
	var height = minHeight;
	var xOffset = 0;
	var yOffset = 0;
	var withReducedRate = .7;
	var heighteducedRate = .8;
	var widthReduction = 50;
	var heightReduction = 65;

	var is = new Is();

	//default screen dimensions
	var availScrnWidth = 800;
	var availScrnHeight = 572;
	//get user's screen dimensions
	if (typeof(screen.availWidth) != "undefined") {
		availScrnWidth = screen.availWidth;
	}
	if (typeof(screen.availHeight) != "undefined") {
		availScrnHeight = screen.availHeight;
	}

	if (typeof(attr) == "undefined") {
		attr = null;
	}

	if (!relativeToOpener) {
		if (expandable) {
		    width = availScrnWidth * withReducedRate - widthReduction;
		    height = availScrnHeight - heightReduction;
		}
		//make the new window fit the user's screen and also within the minimum dimension
		if (width >= availScrnWidth) {
			width = availScrnWidth - 10;
		}
		if (width < minWidth) {
			width = minWidth;
		}
		if (height >= availScrnHeight - 45) { //leave room for status bar for some windows
			height = availScrnHeight - 45;
		}
		if (height < minHeight) {
			height = minHeight;
		}
		//adjust the window so it's centered
		var horizOffset = availScrnWidth - width;
		if (horizOffset > 20) {
			xOffset = horizOffset/2; //find middle
		}
		var reservedWidth = screen.width - availScrnWidth;
		if (xOffset <= reservedWidth) { //width is too big? shrink it
			width -= reservedWidth - 10;
			xOffset = reservedWidth - 10;
		}
		var vertOffset = availScrnHeight - height;
		if (vertOffset > 50) {
			yOffset = (vertOffset - 45)/2; //get the center but exclude the status bar
		}
		var reservedHeight = screen.height - availScrnHeight;
		if (yOffset <= reservedHeight) { //height is too big? shrink it
			height -= reservedHeight - 30;
			yOffset = reservedHeight - 15;
		}
	} else { //relative to browser window
		var WinWidth = 0;
		var WinHeight = 0;
		var browserLeft = 0;
		var browserTop = 0;

		if (is.nav) {
		 	WinWidth = cpFrame.outerWidth;
		    WinHeight = cpFrame.outerHeight;
		    browserLeft = cpFrame.top.window.screenX;
		    browserTop = cpFrame.top.window.screenY;
		} else { // ie
		 	WinWidth = cpFrame.document.body.clientWidth;
		    WinHeight = cpFrame.document.body.clientHeight;
		    browserLeft = cpFrame.top.screenLeft;
		    browserTop = cpFrame.top.screenTop;
		}
		if (expandable) {
	    	width = WinWidth * withReducedRate - widthReduction;
		    height = WinHeight - heightReduction;
	    }
	    // If there is some room move the popup up a little and make it bigger
	    if (browserTop > 50){
	    	browserTop -= 50;
	     	height += 50;
	    }
		//make the new window fit the parent window and also within the minimum dimension
		if (width >= WinWidth) {
			width = WinWidth * withReducedRate - widthReduction;
		}
		if (width < minWidth) {
			width = minWidth;
		}
		if (height >= WinHeight) {
			height = WinHeight - heightReduction;
		}
		if (height < minHeight) {
			height = minHeight;
		}
	    xOffset = browserLeft + (WinWidth - width)/2;
	    yOffset = browserTop + 5;

	    //adjust the  horizontal position of the window if part of it is going to be hidden
	    if (xOffset < browserLeft) {
	    	xOffset += 5;
	    }
	    var xEndPopup = xOffset + width;
	    if (xEndPopup > availScrnWidth) {
	    	xOffset -= xEndPopup - availScrnWidth;
	    }
	    if (xOffset < 0 ) {
	    	xOffset = browserLeft;
	    }
	    //adjust the  vertical position of the window if part of it is going to be hidden
	    var yEndPopup = yOffset + height + 45; //the extra 45 is reserved for the status bar
	    if (yEndPopup > availScrnHeight) {
	    	yOffset -= yEndPopup - availScrnHeight;
	    }
	    if (yOffset < 0) {
	    	yOffset = browserTop;
	    }
	}

	var wFeature = null;
	var attributes = ",resizable,scrollbars";
	if (attr != null) {
		attributes = attr;
	}

    if (is.ie4up){  // using IE 4.x
		wFeature = "width="+width+",height="+height+",left="+xOffset+",top="+yOffset+attributes;
	} else if (is.nav4up) { // using Netscape 4.x
        wFeature = "width="+width+",height="+height+",screenX="+xOffset+",screenY="+yOffset+attributes;
    } else {
        wFeature = "width="+width+",height="+height+ attributes;
    }
	return wFeature;
}

function openImage(BLOBName) {
	var newImgUrl = pdfUrl;
	if (BLOBName == "") {
		docParent.location = unsubs_url;
	}
	newImgUrl = appendUrlParm(newImgUrl, blob_ID, BLOBName);
	DisplayImageWindow(newImgUrl);
}

function calendarPopup(form, datefield, parentTarget) {
	var formName = form.name;
	var value = form.elements[datefield].value;
	var calUrl = appContext + "/JSP/calendar.jsp";
	calUrl = appendUrlParm(calUrl, "form", formName);
	calUrl = appendUrlParm(calUrl, "field", datefield);
	calUrl = appendUrlParm(calUrl, "startDate", value);
	calUrl = appendUrlParm(calUrl, "pTarget", parentTarget);
	displayPopupWindow("popupCalendar", calUrl);
}