/* ************************************************************

                OPEN WINDOWS

************************************************************ */

/**
 * Global var to monitor if popup window is still open (used by monitored
 * popup only)
 */
var newwindow = '';


/**
 * Set default popup window properties
 *      These are the defaults for the signup wizard popup
 */
var redirectTo = "http://www.dnc.com/solutions/demo/";
var defaultName = "popup";
var defaultStyle = "width=762,height=525,resizable=1,status=yes,toolbar=no,menubar=no,scrollbars=yes,location=no,top=0,left=0";


/**
 * Open popup window with provided url and default parameters specified here.
 * Only the desired page url is required in the method call. This monitored version
 * is provided in case of IE/NS differences in handling opening a window with the
 * same name as one that already exists. (I think it was early IE which may not
 * need to be concerned with as per minumum browser spec.
 */
function openPopupMonitored(url, winname, winstyle) {
	if (!newwindow.closed && newwindow.location) {
		newwindow.location.href = url;  // window already open
	} else {
		newwindow = openPopup(url, winstyle, winname);     // create new window
		if (!newwindow.opener) newwindow.opener = self;
	}
	return false;
}


/**
 * Open a popup window with provided url, name and style.
 * If no name or style is provided, use defaults.
 */

function openPopup(url, winstyle, winname) {

    // JCR - I'm not sure what's going on here.  In both Moz 1.6 and IE 6,
    //  arguments which aren't specifed are undefined.  In IE when I
    //  perform undefined == null, I get true. In Moz, I get false here, 
    //  but when I extracted the code to test I got true!


    if (typeof(winstyle) == 'undefined')
        winstyle = defaultStyle;

    // IE won't open the new window unless the name is different from the closing one
    // while NS is the opposite. Neither gives an error. Browser quirk of onUnload behavior?
    // Thus, test for IE and supply an alternate popup window name.
    var ie = (document.all&&navigator.userAgent.indexOf("Opera")==-1);
    
    if (typeof(winname) == 'undefined') {
        var winname = defaultName;
    }
//        var winname = ie ? Math.random().toString().replace('0\.', 'win') : defaultName;
//    }

//    alert('opening ' + url + ' ' + winname + ' ' + winstyle);
//    alert('opening ' + winname);
    var child = window.open(url, winname, winstyle);
    if (child && !child.opener) child.opener = self;
    return child;
}

function openUnloadPopup(url, winstyle) {
    // IE won't open the new window unless the name is different from the closing one
    // while NS is the opposite. Neither gives an error. Browser quirk of onUnload behavior?
    // Thus, test for IE and supply an alternate popup window name.
    alert('openUnloadPopup ' + url);

    var ie = (document.all&&navigator.userAgent.indexOf("Opera")==-1);
    var winname = ie ? Math.random().toString().replace('0\.', 'win') : defaultName;
    if (typeof(winstyle) == 'undefined')
        winstyle = defaultStyle;
    return openPopup(url, winstyle, winname)
}

/* ***********************************************************

        ON SIGNUP WIZARD CLOSE HANDLING

************************************************************* */

/* ************************************************************
            RULES AND MONITORING
************************************************************** */

function actionOnClose(key, signupId, opener) {

    if (key == -1) { return true; }
    var g = redirectTo + '?';
    if (key > 0) {
        g = g + '&key=' + key;
    }
    if (signupId) {
        g = g + '&signupId=' + signupId;
//    } else {
//        // DEBUG ONLY!!
//        g = g + '&signupId=' + '96CB12917A378BB6FF86C2DEAC899F207D7EA401EFD1';
    }
    if (opener) {
        // JCR - Probably need to be checking that we can get opener.location 
        // in a catch so no permission error
        opener.location.href = g;
/*    } else if (key == 7 || key == 8 || key == 10 || key == 11) {
        // opening window no longer exists, try to open a popup ourselves
        var msg = "Although we have processed your order, you have not finished configuring your account.\n" +
                  "If the signup wizard does not reopen automatically, please click on the signup link again.\n" +
                  "The wizard will close automatically once your account is ready.";
        if (!confirm(msg)) { return false; } // DEBUG - CHANGE TO ALERT
        var url = "fs-signup.adp?src=%2fNS%2fam%2fWizard2%2fsignup%2fsignup" + key + "%2ehtml";
        openUnloadPopup(url);
    } else {
        openUnloadPopup(redirectTo);
*/
    }
    return true;







    if (key == 0) {
        if (signupId) {
            redirectTo = redirectTo + '?signupId=' + signupId;
        }
        if (opener) {
            opener.location.href = redirectTo;
        } else {
            var win = openPopup(redirectTo, "width=762,height=525,resizable=1,status=yes,toolbar=yes,menubar=yes,scrollbars=yes,location=yes,top=0,left=0");
        }
        return false;
    } else if (key == 7 || key == 8 || key == 10 || key == 11) {
        var msg = "Although we have processed your order, you have not finished configuring your account.\n" +
                  "If the signup wizard does not reopen automatically, please click on the signup link again.\n" +
                  "The wizard will close automatically once your account is ready.";
        if (!confirm(msg)) { return false; } // DEBUG - CHANGE TO ALERT
        var url = "fs-signup.adp?src=%2fNS%2fam%2fWizard2%2fsignup%2fsignup" + key + "%2ehtml";
        openPopup(url);
        return true;
    }

    // Unknown page code, don't do anything
    return false;
}


/* ************************************************************
            FUNCTIONS FOR PARENT-MONITORED APPROACH
************************************************************** */
/**
 * IN PARENT
 * Global var to store handle to child upon creation.
 */
var myChild = null;
var myChildName = null;
var myChildPage = 0;
var myChildSignupId = null;

/**
 * IN PARENT
 * Check at periodic intervals if the child popup window has been closed, and
 * if so redirect this page to test drive.
 */
function detectChild() {
    // TODO: WE'D LIKE TO SUPPRESS THE PARENT REDIRECTION WHEN ON SIGNUP STEP 7 OR 8
    var x = 10000;   // check for child window every x milliseconds
//    alert('detectChild() ==> ' + myChild + ' is ' + isClosed(myChild));
//    if (myChild) alert(myChild.name + ' is myChild.name');
    if(isClosed(myChild)) {
        if (myChild)
            alert(myChild.name + ' is closed');
        else
            alert(myChildName + " last saved name has closed");

        if (actionOnClose(myChildPage, myChildSignupId)) {
            setTimeout("detectChild()", x);
        }
        return;
    } else if (myChild) {
        // if the child isn't closed, try to read out the signup step var for use in
        // suppressing parent redirection.
//        alert(myChild.signupStep + ' is myChild.signupStep, ' + myChildSignupId);

        try {
            myChildName = myChild.name;
            myChildPage = myChild.signupStep;
            myChildSignupId = myChild.signupId;
        } catch(exception) {
            return false;
        }
    }
    setTimeout("detectChild()", x);
}


/**
 * IN PARENT
 * Pass in handle to child window to determine if child has been closed.
 * Returns false before window is opened and while window is open.
 */
function isClosed(myWin) {
  return (myWin ? myWin.closed : false);
}


/**
 * IN PARENT
 * Allow child popup window to redirect this parent window in the case of
 * this page being refreshed and losing the parent-child relationship. Do this by
 * saving info to the child onUnload of this page which will act as an indicator
 * that this page has lost the relationship.
 * SIGNUP WIZARD NOTE:
 * DISABLED - this feature was disabled in the child, so this function has been removed
 * from the onUnload event.
 */
function kissGoodbye() {
    if (myChild  &&  !myChild.closed) {
        myChild.myparentHref = self.location.href;
    }
}

/**
 * IN CHILD
 * On unload of the frameset, we would like to recognize if the parent-child relationship is broken by
 * a parent refresh, as then we still have a chance of redirecting the parent
 * window manually from the child via this method.
 * SIGNUP WIZARD NOTE:
 * DISABLED - must allow client to navigate parent with wizard open and not then have closing the wizard
 * redirect them.
 */
function doClose() {

    if (opener.myChild) {
        // we have found a non-null value in the parent page pointing to this window
        // so we can do nothing and let the parent handle the detection

    } else {
        // the parent has lost the reference to the child, or the child's pointer to
        // 'opener' has been changed

        if (myparentHref) {
            // this variable being non-null says that the onunload event of
            // the parent wrote data here (like during a page refresh).
            // Since the parent can no longer monitor this page (but the child still
            // knows who the parent is), we have to manually retarget the parent

            // this line fails in NS after navigation in the child and refresh in the parent
            // because the opener has been changed to the signup page from the signup_start page
            // (doesn't break in ie). Thus we're trying to set the location on a window that is disappearing.
//            if (opener.location.href != myparentHref)
//                alert("parent/opener href mismatch: 1) parent var 2) opener\n:" + myparentHref + "\n" + opener.location.href)
        	opener.location.href = redirectTo;

        }
    }

}

/* ************************************************************
            FUNCTIONS FOR CHILD-MONITORED APPROACH
************************************************************** */

/**
 * Call onUnload of page to do any on close processing.
 */
function onClosePostProcess() {
    if (isWindowClosed) {
        // openNextWindow...
    }
}


/**
 * Test if signup wizard popup window has been closed and return true or false.
 */
function isWindowClosed() {
    if (window.event) {      // IE indicates with negative mouse position values
        if ((window.event.clientX < 0) && (window.event.clientY < 0))
            return true;
        else
            return false;
    } else {                // Netscape requires more work
        if (checkWindowExists(winname)) {
            return false;
        } else {
            return true;
        }
    }
}


/**
 * NETSCAPE - SPECIFIC
 * Check and see if a child window has been opened by attempting to create one by the same
 * name. If the window had been closed, this will create a new one that we must then
 * manually shut down ourselves.
 * NOTE: This method causes a blank window to open and close causing an undesirable 'flash'.
 * In addition, a security error appears in the javascript console.
 */
function checkWindowExists(windowname) {
    try {
        var win = window.open('', windowname, winstyle);
        var myHref = win.location.href
        if(myHref == "about:blank") {
            win.close();
            return false;
        } else {
            return true;
        }
    } catch(exception) {
        return false;
    }
}


/* *******************************************************************

            WINDOW RESIZING BASED ON RESOLUTION

******************************************************************* */

/**
 * Set the height of the browser window to a larger value for high resolution screens.
 * Currently the rule we use is:
 *      IF SCREEN HEIGHT IS GREATER THAN 600, THEN
 *          SET WINDOW HEIGHT TO SCREEN HEIGHT - 75
 * The width should remain unchanged.
 *
 * DNC NOTE: WINDOW WIDTH IS HARDCODED HERE
 * It is currently hardcoded to the standard
 * width of the signup wizard screens.
 *
 *     http://www.quirksmode.org/js/winprop.html
 *
 * JCR addition, if window is already larger than requested size, leave it alone
 */
function setHeight() {

    var dimensions = getFrameDimensions();

    if (self.screen.width > 600) {
        // set new browser height to screen height minus 75
//JCR        newHeight = self.screen.height - 75;

        // 12/22/03 JG - Set the new height, leaving the width the same.
        // NOTE: The signup popups are all set to width=762. But if I try
        // to read the width back from the browser, I get a different value
        // from ie and ns. Thus, instead of making a generic method that
        // maintains whatever value is read from the browser, I'm going to
        // hardcode the width to the standard value.
        var newHeight = self.screen.availHeight;
        var newWidth = 762;

        // However, Netscape 4 has a bug in its implementation of resizeTo: it resizes
        // the window so that the actual content window (without the toolbars etc.) gets
        // the required size instead of the entire window, as the other browsers do.
        // Therefore we have to do an extra calculation for Netscape 4.
        if (document.layers) {
            // First we have to find out how much space the toolbars, status bars and other
            // stuff take. Subtract the inner dimensions from the outer dimensions to get
            // this values. Note that I'll have to take the width and height of the parent.
            // I want to use the dimensions of the entire window, not only of this frame.
            tmp2 = parent.outerHeight - parent.innerHeight;
            newHeight -= tmp2;
        }

        // JCR - Make sure that we never shrink the window
        var currentWidth = 640, currentHeight = 480;
        if (document.all) {
            currentWidth = document.body.clientWidth;
            currentHeight = document.body.clientHeight;
        } else if (document.layers || document.getElementById) {
            currentWidth = window.innerWidth;
            currentHeight = window.innerHeight;
        }
//        alert(currentWidth + ' is currentWidth, ' + newWidth + ' is newWidth');
//        alert(currentHeight + ' is currentHeight, ' + newHeight + ' is newHeight');
        if (currentWidth >= newWidth)   newWidth = currentWidth;
        if (currentHeight >= newHeight) newHeight = currentHeight;

        // Now we can resize the parent (= the frameset) to the new width and
        // height and have the desired result in all browsers:
        try {
//            parent.window.moveTo(0,0);
            parent.window.resizeTo(newWidth, newHeight);
        } catch(exception) {
        }
    }
}



/**
 * Get the frame width and height and return them as values in an array.
 * Cross-browser enabled and taken from example at:
 *     http://www.quirksmode.org/js/winprop.html
 */
function getFrameDimensions() {

    var dimensions = new Array('width','height');

    var frameWidth;
    var frameHeight;

    if (self.innerWidth)
    {   // ns 7.1
        frameWidth = self.innerWidth;
        frameHeight = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientWidth)
    {   // ie 6 with DOCTYPE or strict mode
        frameWidth = document.documentElement.clientWidth;
        frameHeight = document.documentElement.clientHeight;
    }
    else if (document.body)
    {   // ie 5,6
        // Netscape 6 also supports document.body, though the information we need is
        // still stored in innerWidth/Height. So keep this after the innerWidth part
        frameWidth = document.body.clientWidth;
        frameHeight = document.body.clientHeight;
    }
    else
        // browsers older than version 4 are not supported
        return;

    dimensions.width = frameWidth;
    dimensions.height = frameHeight;

    //alert("w x h: " + frameWidth + " x " + frameHeight);

    return dimensions;
}

/**
 * Resize browser window to full screen height and desired width (as indicated
 * by pixels of screen width to cover) and shift to side of screen.
 *
 * Parameters:
 *		oWindow - Window object to resize. Will use current frame if no window provided
 *		newWidth - integer pixels to set width to
 *		side - string 'left' or 'right' indicating side of screen to use
 */
function resizeForSideBySide(oWindow, newWidth, screenSide) {

	// get the window to work on
	var win = (oWindow) ? oWindow : self;

	// get which side of screen or default to left
	var onLeft = (screenSide.toUpperCase() == 'RIGHT') ? false : true;

	// set new height for window to maximum available
	newHeight = self.screen.availHeight;
	//alert('set window ' + win + ' to newWidth ' + newWidth + ', newHeight to ' + newHeight + ', onLeft is ' + onLeft);

    // JCR - If window is not resized before movement, the move might
    // not work in Netscape and Mozilla.
	win.parent.window.resizeTo(newWidth,newHeight);
	if (onLeft) {
		win.parent.window.moveTo(0,0);
	} else {
		win.parent.window.moveTo(self.screen.width - newWidth, 0);	
	}
	win.focus();
}

/* *******************************************************************

            PARAMETER PASSING ON THE URL

******************************************************************* */

/*
* Created: 2002-09-17
* Creator: Erik Beijnoff erik@beijnoff.com
*
* Changes: none
*
* This is a convenience method that indexes all parameters on the querystring
* into a hashtable that's appended to the window object.
*
* Usage:
*
* createQueryStringIndex();
* window.parameters["parameterName"];
*
* Create the index by calling createQueryStringIndex() anywhere on the page,
* a suggested place would be on the onload event for the body of a document.
* The parameters can after that be found in a newly created hashtable that's
* accessed through the window object on the form window.parameters["parameterName"].
* If the parameter doesn't exist, undefined is returned. If the parameter
* doesn't have a value specified, an empty string is returned.
* The parameter is returned as an array, since several parameters with the same
* name can be specified in a query string
*/
function createQueryStringIndex(){
	var params= new Object();
	window.parameters = params;

	var reEquals= /=/ig;
	var reAnd= /&/ig;
	var reQuestionMark= /\?/ig;

	var query= window.location.href.split(reQuestionMark);

	if (query.length > 1) {
		var querySplit= query[1].split(reAnd);
		var length= querySplit.length;
		var split, arr, name;

		for (var i=0;i<length;i++) {
			split= querySplit[i].split(reEquals);
			name= split[0];

			if(!params[name]){
				arr= new Array();
				params[name]= arr;
			}else{
				arr= params[name];
			}

			if(split.length < 2){
				arr[arr.length]= "";
			}else{
				arr[arr.length]= unescape(split[1]);
			}
		}
	}
	return params;
}



/* ************************************************************
        			CAPTURE TAB KEY
        				IE ONLY
	Adapted for contenteditable from:
		http://www.siteexperts.com/tips/elements/ts34/page1.asp
************************************************************ */
/* Copyright 2000 SiteExperts.com/ InsideDHTML.com, LLC
   This code can be reusedas long as the above copyright notice
   is not removed
*/

/* Notes from article describing functions:
First, the TAB key only fires the onkeydown and the onkeyup event - no onkeypress event
is fired. Both these events are physical events and signal that the user has
physically pressed or released a key. As physical events, these events are not
cancelable. This means that while you can detect that the TAB key is pressed you
cannot prevent the tab from moving the focus.

However, there is a work-around. You can use a timer
with a duration of 0 to force code to execute immediately following an event
sequence. Therefore, rather than stop the tab from moving the focus we simply
use a timer to move the focus immediately back into the textbox.

This keeps the user inside of the textbox. However, once the user tabs
their previous selection is lost. The next step is to also cache the
selection in the onkeydown event and restore it when we return the focus.
When we return the focus we also insert a tab character into the
textbox (which does get properly rendered).

It takes only 7 lines of code to accomplish this trick.
Below is the complete script from the example above:
*/

function CheckTab(el) {
  // Run only in IE and if tab key is pressed and not shift-tab
  if ((document.all) && (9==event.keyCode) && !event.shiftKey) {
    // Cache the selection
    el.selection=document.selection.createRange();
    // store current document scroll offset coordinates
    saveDsoc();
    setTimeout("ProcessTab('" + el.id + "')",0)
  }
}

function ProcessTab(id) {
  // Insert tab character in place of cached selection
  //document.all[id].selection.text=String.fromCharCode(9)
  // CUSTOMIZE set in 4 spaces instead of tab character
  document.all[id].selection.text = "    ";
  // Set the focus
  document.all[id].focus()
  // Scroll to previous window dsoc
  window.scrollTo(scrollX, scrollY);

}
/*
This code should get you started with processing the tab key.
We did not write support for removing tabs (shift-tab). This can be added
with a little work. You need to check for the shift key (event.shiftKey)
and then write code that locates and removes the tab character (if one exists)
on the current line. Another interesting feature common in code editors is
the ability to select and indent multiple lines by pressing tab. This can
also be added but would require you to analyze the selection and insert the
tab characters at the appropriate location. Currently our script replaces
the selection with a tab key.
*/

/**
 * Global variables and helper function to preserve the current document
 * scroll offset coordinates (in an IE way) to later window positioning.
 */
var scrollX = 0;
var scrollY = 0;
function saveDsoc() {
	scrollX = document.body.scrollLeft;
	scrollY = document.body.scrollTop;
}


/* ************************************************************

        HELPER FUNCTIONS READING EVENT PROPERTIES
        COPIED FROM EXAMPLES AT:
            http://www.quirksmode.org/js/events_properties.html

************************************************************ */

function getType(e)
{
    if (!e) var e = window.event;
    return (e.type) ? e.type : '';
}

function getTarget(e)
{
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    alert(targ);
}

function getKey(e)
{
    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    var character = String.fromCharCode(code);
    alert('Character was ' + character + ' for code ' + code);
}

function getCoords(e)
{
    var posx = 0;
    var posy = 0;

    if (!e) var e = window.event;

    if (e.pageX || e.pageY)
    {
        posx = e.pageX;
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY) // ie
    {
        posx = e.clientX + document.body.scrollLeft;
        posy = e.clientY + document.body.scrollTop;
    }

}

