var PopupMinWidth = 238;  // at least on IE7 @ 800x600, 1024x768, 1280x1024
var PopupMinHeight = 150;
//var PopupMaxWidth = screen.width * .92;
//var PopupMaxHeight = (screen.height - 50) * .92;

var gintcMinBrowserWidth =80;
var gbMyResize = false;

// magic numbers
var ie6TweakPopupWidth  = 15;  // used to fix display issue for seriesPopup in IE6
var popupVerticalChrome = 120; // the space used by a popup window (mostly along top: title bar, address bar?)
							   // for its non-body (non-client area) features
// Thumbnail Actions
var tnacActionPopup1 = 1;
var tnacActionGoTo = 2;
var tnacActionPopupN = 3;

// Thumbnail Targets
var tntcTargetImage = 1;
var tntcTargetPage = 2;

// Thumbnail Alignments
var tnalcLeft = 1;
var tnalcRight = 2;

// popupPage actions
var ppacSave  = 1;
var ppacPrint = 2;

// popupN dimensions
var popupNTnColumnSpacing = 16;
var popupNTnPadding = 8;
var popupNTnBorder = 0;
var popupNouterPadding = 8;
var popupNTnImgWidth = 93;
var popupNTnImgHeight = 103;
var popupNHeaderHeight = 38;

// size of full-size, non-popup browser window
var browserWinWidth = 1100;
var browserWinHeight = 800;

// when true, windows clicked from series popup will open in the "owner" of the popup window
var bPopupNInPlace = true;

var gstrcToolTipText = "Click to View Details";
var gstrcQsSep = "&";  // queryString separator

// Driver for creating a div to hold a thumbnail and placing it in oTnColl
function addTn( aItems, i, oTnColl, TnWidth, TnHeight, bPopupN, valign ) {
	if ( bPopupN == null ) bPopupN = false;
	if ( valign == null ) valign = false;

	var oTn = document.createElement("div");
	if ( (aItems[i][3] == tnacActionGoTo) && !bPopupN ) { // GoTo
		oTn.innerHTML = "<a href='" + aItems[i][9] + "'>" +
			"<img id='PopupImg_" + i.toString() + "' /></a>";
	} else { // Popup1, PopupN
		// added <a> wrapper with inert  b/c onclick returns(false)) href='#' to make mouse pointer turn to hand
		oTn.innerHTML = "<a href='#' onclick='tnOnClick(event," + i.toString() + "," +
			(bPopupN ? "true": "false") + "); return(false);' >"+
			"<img id='PopupImg_" + i.toString() + "' /></a>";
/*
		oTn.innerHTML = "<img id='PopupImg_" + i.toString() + "' " + 
			"	onclick=tnOnClick(event," + i.toString() + "," 
			+ (bPopupN ? "true": "false") + ") />";
*/
	}

	// Compute the size of the image, scaled to its box
	var tempCoord = scaleImage( aItems[i][1], aItems[i][2], 
								TnWidth, TnHeight);

	oTnColl.appendChild(oTn);
	var oImg = document.getElementById("PopupImg_" + i.toString() );
	oImg.src = aItems[i][0];
	if ( aItems[i][3] == tnacActionPopupN ) {
		oImg.title = "Click to View More " + aItems[i][8] + " Products";
	} else {
		oImg.title = gstrcToolTipText;
	}
	oImg.width = tempCoord.width;  oImg.height = tempCoord.height;
	// set margin to vertically align, otherwise it's 0 by default
	// this is a workaround for poor vertical alignment in CSS 
	// didn't work padding the div, had to set margin of img
	if( (tempCoord.height != TnHeight) && valign ) {
		oImg.style.marginTop=Math.floor((TnHeight-tempCoord.height)/2).toString()+"px";
	}
	return oTn;
}

// Helps put spacer between thumbnails
function addSpacer( oTnCollection, spacerClass ) {

	var oTnSpacer = document.createElement("div");
	oTnSpacer.className = spacerClass;
	oTnCollection.appendChild(oTnSpacer);
}

// Puts spacer between thumbnails
function addVertLine( oTnCollection, alignment, bWithLine ) {

	if ( (alignment==tnalcLeft) && bWithLine) {
		addSpacer( oTnCollection, "vert_line" );
	} else if ( alignment==tnalcLeft ) {  // and no line
		addSpacer( oTnCollection, "no_vert_line" );
	} else if ( (alignment==tnalcRight) && bWithLine) {
		addSpacer( oTnCollection, "vert_line_right" );
	} else if (alignment==tnalcRight) {   // and no line
		addSpacer( oTnCollection, "no_vert_line_right" );
	}
}

// This function sorts out what do when a thumbnail is clicked
function tnOnClickHelper ( event, iTN, aTN, bPopupN ) {
var action = aTN[iTN][3];
var target = aTN[iTN][4];

	// in popupN, assume you're reading the database built for the underlying menu page
	if ( bPopupN ) {  // in a popup, all clicks are Popup1
		action = tnacActionPopup1;
//		target = tntcTargetPage;
	}

	// if series popup's are opened into the popup's "parent" window
	if ( bPopupN && bPopupNInPlace && (target == tntcTargetPage)) {
		// if the window to hold pointed to page is not open
		if ( !self.opener || self.opener.closed ) {
			// open it
			tnOpenWin( event.clientX, event.clientY, action, target, iTN, aTN, bPopupN );
		} else {
			// otherwise, place the target page in the opened window
			self.opener.document.location = aTN[iTN][9];
		}
	// series popup's are opened into their own NEW window
	} else if ((action == tnacActionPopupN ) && ( target == tntcTargetPage  )) {
		
		if (( !ahPopups[iTN][0] ) || ahPopups[iTN][0].closed) {
			// this page has not opened this popupN yet
			tnOpenWin( event.clientX, event.clientY, action, target, iTN, aTN, bPopupN );
//			include_js(aTN[iTN][10], 
//				function(){self["tnOpenWin"].apply(self,[mouseX, mouseY, action, target, iTN, aTN, bPopupN])} )
		} else if 	( ahPopups[iTN][0].opener == self ) {
			// I was last to open it. Bring it forward.
			ahPopups[iTN][0].focus();
		} else {
			// I'm no longer the owner.  Must rewrite this window.
			tnOpenWin( event.clientX, event.clientY, action, target, iTN, aTN, bPopupN );
//			include_js(aTN[iTN][10], 
//				function(){self["tnOpenWin"].apply(self,[mouseX, mouseY, action, target, iTN, aTN, bPopupN])} )
		}
	// it's not a series popup, it's a GoTo page (not frequently used)
	} else if (( !ahPopups[iTN][0] ) || ahPopups[iTN][0].closed) {
		// if never opened a window from this thumbnail, open a new one
		tnOpenWin( event.clientX, event.clientY, action, target, iTN, aTN, bPopupN );
	} else {
		//  otherwise bring it forward
		ahPopups[iTN][0].focus();
	}
}

// This function consolidates window opening behavior
function tnOpenWin( clickX, clickY, action, target, iTN, aTN, bPopupN ) {
	var bPreventAutoClose = false;

	// popup1 Image
	if (( action == tnacActionPopup1 ) && ( target == tntcTargetImage  )) {  
		// get image's scaled dimensions
		var winSize   = getWinSize();
		var tempCoord = scaleImage( aTN[iTN][6], aTN[iTN][7], 
									winSize.width, winSize.height-popupVerticalChrome);  // subtract vertical chrome

		// Compute coords so that popup opens near the thumbnail that was clicked
		var lower = clickY + TnImgHeight/2;
		var upper = lower - tempCoord.height;
		if ( clickX < 0.3 * screen.width ) { // left-sided popup
			var left  = clickX - TnImgWidth/2;
		} else if ( clickX < 0.70 * screen.width ) { // central popup
			var left  = clickX - tempCoord.width/2;
		} else { // right-sided popup
			var right = clickX  + TnImgWidth/2;
			var left  = right - tempCoord.width;
		}
		
		// encodeURIComponent changes special chars to numeric text strings (e.g., " " = %20)
		var strWinPage = "popup1.html?" +
			"imgFile=" + encodeURIComponent(aTN[iTN][5]) + gstrcQsSep +
			"popupTitle=" + encodeURIComponent(aTN[iTN][8]) + gstrcQsSep +
			"scaledW=" + tempCoord.width.toString() + gstrcQsSep +
			"scaledH=" + tempCoord.height.toString();
		var strWinName = "";
		var strWinOtherFeatures = 	"toolbar=no,menubar=no,scrollbars=no," + 
									"resizable=no,location=no,directories=no,status=no";

	// popup1 Page (rarely used)
	} else if (( action == tnacActionPopup1 ) && ( target == tntcTargetPage  )) {  
		if ( !bPopupN ) {  // not IN a series popup
			// new window will be same size as this one
			var tempCoord = getWinSize(self); // of this window
			var winPos = getWinPos(self);
			upper = winPos.top;
			left = winPos.left;
		// NB: IN a series popup  but not  bPopupNInPlace, b/c bPopupNInPlace is caught in tnOnClickHelper
		} else if ( self.opener && !self.opener.closed ) {
			// new window will be same size as series popup's parent (which is this window, self)
			var tempCoord = getWinSize(self.opener);
			var winPos = getWinPos(self.opener);
			upper = winPos.top;
			left = winPos.left;
		} else {
			// we've lost parent window, just open to default sizes and placement
			var tempCoord = new Object();
			tempCoord.width = browserWinWidth;
			tempCoord.height = browserWinHeight;
			upper = 0;
			left = 0;
		}

		var strWinPage = aTN[iTN][9];
		var strWinName = "";
		var strWinOtherFeatures = 
			"toolbar=yes,menubar=yes,scrollbars=yes," + 
			"resizable=yes,location=yes,directories=yes,status=yes";
			
	// were not IN a series popup, but we're opening one
	} else if (( action == tnacActionPopupN ) && ( target == tntcTargetPage  )) {
		bPreventAutoClose = bPopupNInPlace;

		// precompute window size based on itemCount (the number of items on the menu page that series popup displays
		var tempCoord = popupNsize( nRows(itemCount), nCols(itemCount) );
		// make an adjustment for anomaly in IE6 display of series popup
		if ( isIE && !isMinIE7 ) tempCoord.width += ie6TweakPopupWidth;

		// Assume clicked center of thumbnail, compute lower right corner, then upper left
		var lower = clickY + TnImgHeight/2;
		var right = clickX + TnImgWidth/2;
		var upper = lower - tempCoord.height;
		var left  = right - tempCoord.width;
		var strWinPage = aTN[iTN][9] + gstrcQsSep +
			"popupTitle=" + encodeURIComponent(aTN[iTN][8]);
		var strWinName = "SysPopupN";  // only 1 per system (actually per browser)
		var strWinOtherFeatures =	"toolbar=no,menubar=no,scrollbars=no," + 
									"resizable=yes,location=no,directories=no,status=no";
	} // else, GoTo-Image and PopupN-Image are invalid, GoTo-Page is handled as href, not an onclick()
	var strWinFeatures = 
		"top=" + upper.toString() + "," + "left=" + left.toString() + "," +
		"width=" + tempCoord.width.toString() + "," + 
		"height=" + tempCoord.height.toString() + "," +
		strWinOtherFeatures + ";"

	// Open the window and hold pointer to it
	ahPopups[iTN][0] = window.open( strWinPage, strWinName, strWinFeatures );
	if ( ahPopups[iTN][0] ) { // successfully opened
		// set the series popup parent to this window (self) that just opened it
		if ( action == tnacActionPopupN ) ahPopups[iTN][0].opener = self.window;
//		ahPopups[iTN][0].onload = function(){self["popupNsetWinOwner"].apply(self,[ahPopups[iTN][0], self.window])};
		// set its autoClose property
		ahPopups[iTN][1] = bPreventAutoClose;
		ahPopups[iTN][0].focus(); // need to bring to front named, previously-opened popupN
		if ( bPopupN ) self.focus();
	} else {
		alert("Error opening window.");
	}
}

function closePopups( ) {
   for ( var i=0; i<ahPopups.length; i++) {
	 	if ( !ahPopups[i][0] ) {
		} else {
			// if not closed already, and not bPreventAutoClose, then close it.
			if (!ahPopups[i][0].closed  && !ahPopups[i][1]) ahPopups[i][0].close();
		}
	}
}

/*
 * Determines which breadcrumb (BC) to display if there are multiple (typically, series and category).
 * When window is opened it is often passed the pageId of the opener.  If opened from series page,
 * the series BC should show.  If opened from category page, the category BC should show.
 * If the opening window is not known or not found, look through the ordered list of BC preferences
 * and pick the first match.
 */
function getBcHTML( intPageID ) {
var bcHTML = null;
	if ( breadCrumbs.length > 0 ) {
		if ( breadCrumbs.length == 1 ) {
			// there's only one BC, no choice involved
			bcHTML = breadCrumbs[0][1];
		} else {
			// intPageId is the page that opened this one
			if ( intPageID ) {
				// look for match in all but last bcPath element
				for(var j=0; (j<breadCrumbs.length) && (bcHTML==null) ; j++){
					bcPage = breadCrumbs[j][0].split("/")
					// split creates empty first cell and empty last cell, hence k=1, length-1
					// length-2 b/c last filled cell always contains intPageID, not a real match
					for(var k=1;(k<bcPage.length-2) && (bcHTML==null) ; k++){
						if(bcPage[k]==intPageID) bcHTML = breadCrumbs[j][1];
					}
				}
      		} 
			// if a match was found, bcHTML is now set (!= null),
			// otherwise, walk through the list of BC preferences until you find a match
			for(var i=0; (i<bcPrefs.length) && (bcHTML == null) ; i++){
				for(var j=0; (j<breadCrumbs.length) && (bcHTML==null) ; j++){
					if ( breadCrumbs[j][0].match("/"+bcPrefs[i].toString()+"/") != null ) {
						bcHTML = breadCrumbs[j][1];
					}
				}
			}
			// Found no matches, take the first one in the list
			if (bcHTML == null) bcHTML = breadCrumbs[0][1];
		}
	}
	return bcHTML;
}

// Parse name/value param pairs into Params array
// Read out as Params["paramName"]
function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = decodeURIComponent( KeyVal[0] );  // remove the special char encoding
      var val = decodeURIComponent( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

// Provides layer of indirection in case details are provided in the future by something
// other than the pre-built Javascript array
function getDetails( intPageID ) {
	return details;
}

// Retired
function getHeader( intPageID ) {
	return header;
}

// Provides cross-browser window size.  Uses algorithm from
// http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function getWinSize( hWnd ) {
var winCoord = new Object();

	if ( !hWnd ) hWnd = self;
	
	if( typeof( hWnd.window.innerWidth ) == 'number' ) {
    	//Non-IE
		winCoord.width = hWnd.window.innerWidth;
		winCoord.height = hWnd.window.innerHeight;
	} else if( hWnd.document.documentElement && 
			  ( hWnd.document.documentElement.clientWidth || 
			    hWnd.document.documentElement.clientHeight ) ) {
    	//IE 6+ in 'standards compliant mode'
		winCoord.width = hWnd.document.documentElement.clientWidth;
		winCoord.height = hWnd.document.documentElement.clientHeight;
	} else if( hWnd.document.body && 
			 ( hWnd.document.body.clientWidth || hWnd.document.body.clientHeight ) ) {
    	//IE 4 compatible
		winCoord.width = hWnd.document.body.clientWidth;
		winCoord.height = hWnd.document.body.clientHeight;
	}
	return winCoord;
}

function getWinPos( hWnd ) {
var winCoord = new Object();

	if ( !hWnd ) hWnd = self;
	
  	if ( typeof( hWnd.window.screenLeft ) != 'undefined' ) {
    	//IE 4 compatible
		winCoord.left = hWnd.screenLeft;
		winCoord.top = hWnd.screenTop;
	} else if ( typeof( hWnd.window.screenX ) != 'undefined' ) {
    	//Non-IE
		winCoord.left = hWnd.screenX;
		winCoord.top = hWnd.screenY;
	} else {
		winCoord.left = 0;
		winCoord.top = 0;
	}
	return winCoord;
//x = typeof window.screenLeft != 'undefined' ? w.screenLeft : w.screenX;
//y = typeof window.screenTop != 'undefined' ? w.screenTop - 22 : w.screenY;	return winCoord;
}

/*
 * Dynamically loads a Javascript file.
 * Used to get itemCount.js
 * fmpp could have accomplished this, if we had been using it earlier.
 * This is still  a useful RPC-like technique to know.
 */
function include_js(file, callback) {
var js;

	var html_doc = document.getElementsByTagName('head')[0];
    var old  = document.getElementById('lastIncludedJs');	
	if (old) html_doc.removeChild(old);	// delete last include file first
	js = document.createElement('script');
	js.id = 'lastIncludedJs';
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', file);
	//js.defer = true;	
    html_doc.appendChild(js);

	// notification for 1 browser
    js.onreadystatechange = function () {
        if (js.readyState == 'complete') {
            if (callback) callback();
        }
    }

	// notification for another browser
    js.onload = function () {
        if (callback) callback();
    }
    return false;
}

/* Resizes window to accommodate given INNER dimensions
   works by opening to desired size, measuring the difference b/n desired and actual
   (which is the size of the "chrome"), and the reopening with chrome added
*/ 
function resizeToInner( innerWidth, innerHeight) {
	window.resizeTo(innerWidth, innerHeight);
	resizeCoord = getWinSize();
	window.resizeTo( 2*innerWidth - resizeCoord.width, 
					 2*innerHeight - resizeCoord.height );
}

// Determines size of series popup  based on # of rows and columns
function popupNsize( numRows, numCols ) {
	var popupNCoord = new Object();
	popupNCoord.width  = numCols*(popupNTnImgWidth+2*popupNTnPadding
									+popupNTnColumnSpacing+2*popupNTnBorder)
									-popupNTnColumnSpacing+2*popupNouterPadding;
	popupNCoord.height = numRows*(popupNTnImgHeight+2*popupNTnPadding
								+2*popupNTnBorder)+2*popupNouterPadding
								+popupNHeaderHeight;
	return popupNCoord;
}

// There are 2 cols in series popup
function nCols( nItems ) {
//	return Math.ceil(Math.sqrt(nItems));
	return 2;
}

// Computes # of rows needed to hold nItems based on given # of cols
function nRows( nItems ) {
	return Math.ceil(nItems/nCols(nItems));
}

// returns random integer between lower and upper
function randInt( lowerBound, upperBound ) {
	return (Math.floor(Math.random()*(upperBound-lowerBound+1))+lowerBound );
}

function max( a, b) {
	return ( (a > b) ? a : b );
}

function min( a, b) {
	return ( (a < b) ? a : b );
}

function imgRoll(img_name, img_src) {
   document[img_name].src = img_src;
}

/*
function addEventHandler( obj, strEventName, fnEventHandler ) {
	if(window.addEventListener){ // Mozilla, Netscape, Firefox
		obj.addEventListener(strEventName, fnEventHandler, false);
	} else { // IE
		obj.attachEvent(strEventName, fnEventHandler);
	}
}

function currentPageNavLink( navLinkID ) {
	var nl = document.getElementById(navLinkID)
	nl.className = "currentPage";
}
\
function popupNsetWinOwner( hWinPopup, hWinOwner) {
	hWinPopup.winOwner = hWinOwner;
}
*/

