// fixed.js: fix fixed positioning and fixed backgrounds in IE/Win
// version 1.8, 08-Aug-2003
// written by Andrew Clover <and@doxdesk.com>, use freely

/*@cc_on
@if (@_win32 && @_jscript_version>4 )

var fixed_positions= new Array();
var fixed_backgrounds= new Array();
var fixed_viewport;

// Initialisation. Called when the <body> tag arrives. Set up viewport so the
// rest of the script knows we're going, and add a measurer div, used to detect
// font size changes and measure image sizes for backgrounds later

function fixed_init() {
  fixed_viewport= (document.compatMode=='CSS1Compat') ?
    document.documentElement : document.body;
  var el= document.createElement('div');
  el.setAttribute('id', 'fixed-measure');
  el.style.position= 'absolute';
  el.style.top= '0'; el.style.left= '0';
  el.style.overflow= 'hidden'; el.style.visibility= 'hidden';
  el.style.fontSize= 'xx-large'; el.style.height= '5em';
  el.style.setExpression('width', 'fixed_measureFont()');
  document.body.insertBefore(el, document.body.firstChild);
}

// Binding. Called every time an element is added to the document, check it
// for fixed features, if found add to our lists and set initial props

function fixed_bind(el) {
  var needLayout= false;
  var tag= el.tagName.toLowerCase();
  var st= el.style;
  var cst= el.currentStyle;
  var anc;

  // find fixed-position elements
  if (cst.position=='fixed') {
    needLayout= true;
    fixed_positions[fixed_positions.length]= el;
    // store original positioning as we'll overwrite it
    st.position= 'absolute';
    st.fixedPLeft=   cst.left;
    st.fixedPTop=    cst.top;
    st.fixedPRight=  cst.right;
    st.fixedPBottom= cst.bottom;
    st.fixedPWidth=  fixed_parseLength(cst.width);
    st.fixedPHeight= fixed_parseLength(cst.height);
    // find element that will act as containing box, for convenience later
    st.fixedCB= null;
    for (anc= el; (anc= anc.parentElement).parentElement;) {
      if (anc.currentStyle.position!='static') {
        st.fixedCB= anc;
        break;
    } }
    // detect nested fixed positioning (only ancestor need move)
    st.fixedNest= false;
    for (anc= el; anc= anc.parentElement;) {
      if (anc.style.fixedNest!=null)
        st.fixedNest= true;
        break;
    }
  }

  // find fixed-background elements (not body/html which IE already gets right)
  if (cst.backgroundAttachment=='fixed' && tag!='body' && tag!='html') {
    needLayout= true;
    fixed_backgrounds[fixed_backgrounds.length]= el;
    // get background offset, converting from keyword if necessary
    st.fixedBLeft= fixed_parseLength(cst.backgroundPositionX);
    st.fixedBTop=  fixed_parseLength(cst.backgroundPositionY);
    // if it's a non-zero %age, need to know size of image for layout
    if (st.fixedBLeft[1]=='%' || st.fixedBTop[1]=='%') {
      st.fixedBWidth= 0; st.fixedBHeight= 0;
      fixed_measureBack(el);
    }
  }
  if (needLayout) fixed_layout();
}

// Layout. On every window or font size change, recalculate positioning

// Request re-layout at next free moment
var fixed_delaying= false;
function fixed_delayout() {
  if (fixed_delaying) return;
  fixed_delaying= true;
  window.setTimeout(fixed_layout, 0);
}

var fixed_ARBITRARY= 200;

function fixed_layout() {
  fixed_delaying= false;
  if (!fixed_viewport) return;
  var i, el, st, j, pr, tmp, A= 'auto';
  var cb, cbLeft, cbTop, cbRight, cbBottom, oLeft, oTop, oRight, oBottom;
  var vpWidth=fixed_viewport.clientWidth, vpHeight=fixed_viewport.clientHeight;

  // calculate initial position for fixed-position elements [black magic]
  for (i= fixed_positions.length; i-->0;) {
    el= fixed_positions[i]; st= el.style;
    // find positioning of containing block
    cb= st.fixedCB; if (!cb) cb= fixed_viewport;
    cbLeft= fixed_pageLeft(cb); cbTop= fixed_pageTop(cb);
    if (cb!=fixed_viewport) { cbLeft+= cb.clientLeft; cbTop+= cb.clientTop; }
    cbRight= fixed_viewport.clientWidth-cbLeft-cb.clientWidth;
    cbBottom= fixed_viewport.clientHeight-cbTop-cb.clientHeight;
    // if size is in %, must recalculate relative to viewport
    if (st.fixedPWidth[1]=='%')
      st.width= Math.round(vpWidth*st.fixedPWidth[0]/100)+'px';
    if (st.fixedPHeight[1]=='%')
      st.height= Math.round(vpHeight*st.fixedPHeight[0]/100)+'px';
    // find out offset values at max size, to account for margins
    st.left= A; st.right= '0'; st.top= A; st.bottom= '0';
    oRight= el.offsetLeft+el.offsetWidth; oBottom= el.offsetTop+el.offsetHeight;
    st.left= '0'; st.right= A; st.top= '0'; st.bottom= A;
    oLeft= el.offsetLeft; oTop= el.offsetTop;
    // use this to convert all edges to pixels
    st.left= A; st.right= st.fixedPRight;
    st.top= A; st.bottom= st.fixedPBottom;
    oRight-= el.offsetLeft+el.offsetWidth;
    oBottom-= el.offsetTop+el.offsetHeight;
    st.left= st.fixedPLeft; st.top= st.fixedPTop;
    oLeft= el.offsetLeft-oLeft; oTop= el.offsetTop-oTop;
    // edge positioning fix
    if (st.fixedPWidth[1]==A && st.fixedPLeft!=A && st.fixedPRight!=A) {
      tmp= el.offsetLeft; st.left= A; st.width= fixed_ARBITRARY+'px';
      tmp= fixed_ARBITRARY+el.offsetLeft-tmp+cbLeft+cbRight;
      st.left= st.fixedPLeft; st.width= ((tmp<1)?1:tmp)+'px';
    }
    if (st.fixedPHeight[1]==A && st.fixedPTop!=A && st.fixedPBottom!=A) {
      tmp= el.offsetTop; st.top= A; st.height= fixed_ARBITRARY+'px';
      tmp= fixed_ARBITRARY+el.offsetTop-tmp+cbTop+cbBottom;
      st.top= st.fixedPTop; st.height= ((tmp<1)?1:tmp)+'px';
    }
    // move all non-auto edges relative to the viewport
    st.fixedCLeft= (st.fixedPLeft=='auto') ? oLeft : oLeft-cbLeft;
    st.fixedCTop= (st.fixedPTop=='auto') ? oTop : oTop-cbTop;
    st.fixedCRight= (st.fixedPRight=='auto') ? oRight : oRight-cbRight;
    st.fixedCBottom= (st.fixedPBottom=='auto') ? oBottom : oBottom-cbBottom;
    // remove left-positioning of right-positioned elements
    if (st.fixedPLeft=='auto' && st.fixedPRight!='auto') st.fixedCLeft= 'auto';
    if (st.fixedPTop=='auto' && st.fixedPBottom!='auto') st.fixedCTop= 'auto';
  }


  // calculate initial positioning of fixed backgrounds
  for (i= fixed_backgrounds.length; i-->0;) {
    el= fixed_backgrounds[i]; st= el.style;
    tmp= st.fixedBImage;
    if (tmp) {
      if (tmp.readyState!='uninitialized') {
        st.fixedBWidth= tmp.offsetWidth;
        st.fixedBHeight= tmp.offsetHeight;
        st.fixedBImage= window.undefined;
      }
    }
    st.fixedBX= fixed_length(el, st.fixedBLeft, vpWidth-st.fixedBWidth);
    st.fixedBY= fixed_length(el, st.fixedBTop, vpHeight-st.fixedBHeight);
  }

  // now call scroll() to set the positions from the values just calculated
  fixed_scroll();
}

// Scrolling. Offset fixed elements relative to viewport scrollness

var fixed_lastX, fixed_lastY;
var fixed_PATCHDELAY= 300;
var fixed_patching= false;

// callback function after a scroll, because incorrect scroll position is
// often reported first go!
function fixed_patch() {
  fixed_patching= false;
  var scrollX= fixed_viewport.scrollLeft, scrollY= fixed_viewport.scrollTop;
  if (scrollX!=fixed_lastX && scrollY!=fixed_lastY) fixed_scroll();
}


function fixed_scroll() {
//console.log("fixed_scroll");
  if (!fixed_viewport) return;
  //carlos add timed restriction hide div
  var now = new Date();
  //end carlos
  if ( lastScrollTime == 0 )
  {
  	lastScrollTime = now;
  }

  var rw_elem = document.getElementById('right_wrapper');
  if ( rw_elem != null && rw_elem != 'undefined' )
  {
  	rw_elem.style.visibility='hidden';
  }
  var i, el, st, viewportX, viewportY;
  var scrollX= fixed_viewport.scrollLeft, scrollY= fixed_viewport.scrollTop;
  fixed_lastX= scrollX; fixed_lastY= scrollY;

  // move non-nested fixed-position elements
  for (i= fixed_positions.length; i-->0;) {
    st= fixed_positions[i].style;
    viewportX= (st.fixedNest) ? 0 : scrollX;
    viewportY= (st.fixedNest) ? 0 : scrollY;
    if (st.fixedCLeft!='auto') st.left= (st.fixedCLeft+viewportX)+'px';
    if (st.fixedCTop!='auto') st.top= (st.fixedCTop+viewportY)+'px';
    viewportX= (st.fixedCB==null || st.fixedCB==fixed_viewport) ? 0 : viewportX;
    viewportY= (st.fixedCB==null || st.fixedCB==fixed_viewport) ? 0 : viewportY;
    st.right= (st.fixedCRight-viewportX+1)+'px'; st.right= (st.fixedCRight-viewportX)+'px';
    st.bottom= (st.fixedCBottom-viewportY+1)+'px'; st.bottom= (st.fixedCBottom-viewportY)+'px';
  }

  // align fixed backgrounds to viewport
  for (i= fixed_backgrounds.length; i-->0;) {
    el= fixed_backgrounds[i]; st= el.style;
    viewportX= scrollX;
    viewportY= scrollY;
    while (el.offsetParent) {
      viewportX-= el.offsetLeft+el.clientLeft;
      viewportY-= el.offsetTop +el.clientTop;
      el= el.offsetParent;
    }
    st.backgroundPositionX= (st.fixedBX+viewportX)+'px';
    st.backgroundPositionY= (st.fixedBY+viewportY)+'px';
  }

  // call back again in a tic
  if (!fixed_patching) {
    fixed_patching= true;
    window.setTimeout(fixed_patch, fixed_PATCHDELAY);
  }
}

// Measurement. Load bg-image into an invisible element on the page, when
// loaded write the width/height to an element's style for layout use; detect
// when font size changes

function fixed_measureBack(el) {
  var measure= document.getElementById('fixed-measure');
  var img= document.createElement('img');
  img.setAttribute('src', fixed_parseURL(el.currentStyle.backgroundImage));
  measure.appendChild(img);
  el.style.fixedBImage= img;
  if (img.readyState=='uninitialized')
    img.attachEvent('onreadystatechange', fixed_measureBackImage_ready);
}

function fixed_measureBackImage_ready() {
  var img= event.srcElement;
  if (img && img.readyState!='uninitialized') {
    img.detachEvent('onreadystatechange', fixed_measureBackImage_ready);
    fixed_layout();
  }
}

var fixed_fontsize= 0;
function fixed_measureFont() {
  var fs= document.getElementById('fixed-measure').offsetHeight;
  if (fixed_fontsize!=fs && fixed_fontsize!=0)
    fixed_delayout();
  fixed_fontsize= fs;
  return '5em';
}

// Utility. General-purpose functions

// parse url() to get value inside

function fixed_parseURL(v) {
  v= v.substring(4, v.length-1);
  if (v.charAt(0)=='"' && v.charAt(v.length-1)=='"' ||
      v.charAt(0)=="'" && v.charAt(v.length-1)=="'")
    return v.substring(1, v.length-1);
  else return v;
}

// parse length or auto or background-position keyword into number and unit

var fixed_numberChars= '+-0123456789.';
var fixed_ZERO= new Array(0, 'px');
var fixed_50PC= new Array(50, '%');
var fixed_100PC= new Array(100, '%');
var fixed_AUTO= new Array(0, 'auto');

function fixed_parseLength(v) {
  var num, i;
  if (v=='left'  || v=='top')    return fixed_ZERO;
  if (v=='right' || v=='bottom') return fixed_100PC;
  if (v=='center') return fixed_50PC;
  if (v=='auto')   return fixed_AUTO;
  i= 0;
  while (i<v.length && fixed_numberChars.indexOf(v.charAt(i))!=-1)
    i++;
  num= parseFloat(v.substring(0, i));
  if (num==0) return fixed_ZERO;
  else return new Array(num, v.substring(i));
}

// convert parsed (number, unit) into a number of pixels

function fixed_length(el, l, full) {
  var tmp, x;
  if (l[1]=='px') return l[0];
  if (l[1]=='%')  return Math.round(full*l[0]/100);
  // other units - measure by setting position; this is rather inefficient
  // but then these units are used for background-position so seldom...
  tmp= el.currentStyle.left;
  el.style.left= '0';
  x= el.offsetLeft;
  el.style.left= l[0]+l[1];
  x= el.offsetLeft-x;
  el.style.left= tmp;
  return x;
}

// convert stupid IE offsetLeft/Top to page-relative values

function fixed_pageLeft(el) {
  var v= 0;
  while (el.offsetParent) {
    v+= el.offsetLeft;
    el= el.offsetParent;
  }
  return v;
}
function fixed_pageTop(el) {
  var v= 0;
  while (el.offsetParent) {
    v+= el.offsetTop;
    el= el.offsetParent;
  }
  return v;
}

// Scanning. Check document every so often until it has finished loading. Do
// nothing until <body> arrives, then call main init. Pass any new elements
// found on each scan to be bound

var fixed_SCANDELAY= 500;

function fixed_scan() {
  if (!document.body) return;
  if (!fixed_viewport) fixed_init();
  var el;
  //for (var i= 0; i<document.all.length; i++) {
  //  el= document.all[i];
  //  if (!el.fixed_bound) {
  //    el.fixed_bound= true;
  //    fixed_bind(el);
  //  }
  //}
  el = document.getElementById('right_wrapper');
  if ( el != null && el != "undefined" )
  {
	  if ( !el.fixed_bound )
	  {
	  	el.fixed_bound = true;
	  	fixed_bind(el);
	  }
  }
}

var fixed_scanner;
function fixed_stop() {
  window.clearInterval(fixed_scanner);
  fixed_scan();
}

fixed_scan();
fixed_scanner= window.setInterval(fixed_scan, fixed_SCANDELAY);
window.attachEvent('onload', fixed_stop);
window.attachEvent('onresize', fixed_delayout);
window.attachEvent('onscroll', fixed_scroll);

@end @*/


function track_scroll()
{

	alert('scroll');

}



var lastScrollTime = new Date();

// Set Netscape up to run the "captureMousePosition" function whenever
// the mouse is moved. For Internet Explorer and Netscape 6, you can capture
// the movement a little easier.
if (document.layers) { // Netscape
    document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = captureMousePosition;
} else if (document.all) { // Internet Explorer
    document.onmousemove = captureMousePosition;
} else if (document.getElementById) { // Netcsape 6
    document.onmousemove = captureMousePosition;
}
// Global variables
xMousePos = 0; // Horizontal position of the mouse on the screen
yMousePos = 0; // Vertical position of the mouse on the screen
yMousePosLast = 0;  // Vertical position of the mouse on the screen - used to detect large jumps and cancel them
xMousePosMax = 0; // Width of the page
yMousePosMax = 0; // Height of the page
isOnImage = false;
timeOnImage = 0;
hasCurrentImageClosed = false;
lastReturnedContext = false;

function captureMousePosition(e) {
    if (document.layers) {
        // When the page scrolls in Netscape, the event's mouse position
        // reflects the absolute position on the screen. innerHight/Width
        // is the position from the top/left of the screen that the user is
        // looking at. pageX/YOffset is the amount that the user has
        // scrolled into the page. So the values will be in relation to
        // each other as the total offsets into the page, no matter if
        // the user has scrolled or not.
        //xMousePos = e.pageX;
        //yMousePos = e.pageY;
        //xMousePos = e.offsetX;
        //yMousePos = e.offsetY;
        //xMousePos = e.clientX;
        //yMousePos = e.clientY;
        //xMousePos = e.layerX;
        //yMousePos = e.layerY;
        //xMousePos = e.x;
        //yMousePos = e.y;



        xMousePos = e.screenX;
        yMousePos = e.screenY;


        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    } else if (document.all) {
        // When the page scrolls in IE, the event's mouse position
        // reflects the position from the top/left of the screen the
        // user is looking at. scrollLeft/Top is the amount the user
        // has scrolled into the page. clientWidth/Height is the height/
        // width of the current page the user is looking at. So, to be
        // consistent with Netscape (above), add the scroll offsets to
        // both so we end up with an absolute value on the page, no
        // matter if the user has scrolled or not.
        //xMousePos = window.event.x+document.body.scrollLeft;
        //yMousePos = window.event.y+document.body.scrollTop;
        //xMousePos = window.event.x;
        //yMousePos = window.event.y;
        //xMousePos = window.event.pageX;
        //yMousePos = window.event.pageY;
        //xMousePos = window.event.offsetX;
        //yMousePos = window.event.offsetY;
        if ( !isOnImage)
        {
	        xMousePos = window.event.clientX;
	        yMousePos = window.event.clientY;
        }

        xMousePosMax = document.body.clientWidth+document.body.scrollLeft;
        yMousePosMax = document.body.clientHeight+document.body.scrollTop;

        //if we are on image do not update anyy values
        if ( isOnImage )
		{
			//alert('jump');
			//large jump
			yMousePos = yMousePosLast;
		}
		if ( !isOnImage)
		{
			yMousePosLast = window.event.clientY;
		}


    } else if (document.getElementById) {
        // Netscape 6 behaves the same as Netscape 4 in this regard

        //xMousePos = e.pageX;
        //yMousePos = e.pageY;
        //xMousePos = e.offsetX;
        //yMousePos = e.offsetY;
        xMousePos = e.clientX;
        yMousePos = e.clientY;
        //xMousePos = e.layerX;
        //yMousePos = e.layerY;
        //xMousePos = e.x;
        //yMousePos = e.y;
        //xMousePos = e.screenX;
        //yMousePos = e.screenY;



        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    }
    //window.status = "xMousePos=" + xMousePos + ", yMousePos=" + yMousePos + ", xMousePosMax=" + xMousePosMax + ", yMousePosMax=" + yMousePosMax + ", YMousePosLast=" + yMousePosLast;

}





var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
dataBrowser: [
	{
		prop: window.opera,
		identity: "Opera" // note: no comma
	},
	{
		string: navigator.userAgent,
		subString: "MSIE",
		identity: "Explorer",
		versionSearch: "MSIE" // note: no comma
	} // note: no comma
];
//alert(BrowserDetect.OS);
//alert(BrowserDetect.OS+' / '+BrowserDetect.browser+' / '+BrowserDetect.version);

	var isSafari = ('Safari' == BrowserDetect.browser)?true:false;
	var isIE = ('Explorer' == BrowserDetect.browser)?true:false;

	function blowupWindow(functionToCall, maxWidth, maxHeight, left, top, currentStep, maxSteps, timeout) {
		//alert('blowing up window');
		var elemWindow = document.getElementById('windowDiv');
		if (currentStep<=1) {
			//alert('making visible!!');
			var widthInc = (maxWidth - (maxWidth % maxSteps))/maxSteps; if (widthInc<1) widthInc = 1;
			var heightInc = (maxHeight - (maxHeight % maxSteps))/maxSteps; if (heightInc<1) heightInc = 1;
			var leftSet = (left + Math.round(maxWidth-(widthInc*currentStep))/2);
			var topSet = (top + Math.round(maxHeight-(heightInc*currentStep))/2);
			//alert('setting');
			elemWindow.style.left = leftSet;
			elemWindow.style.top = topSet;
			elemWindow.style.visibility = 'visible';
			elemWindow.style.width=0; elemWindow.style.height=0;



			//alert('done!!');
		}
		if (currentStep>=maxSteps) {
			//alert(elem.style.width+', '+maxWidth);
			elemWindow.style.visibility = 'hidden';
			eval(functionToCall);
		}
		else {
			//alert(maxWidth); alert(maxHeight);
			var widthInc = (maxWidth - (maxWidth % maxSteps))/maxSteps; if (widthInc<1) widthInc = 1;
			var heightInc = (maxHeight - (maxHeight % maxSteps))/maxSteps; if (heightInc<1) heightInc = 1;
			//alert(widthInc+', '+heightInc);
			var elem = document.getElementById('windowDivImg');
			elem.width=(widthInc*currentStep);
			elem.height=(heightInc*currentStep);
			//alert(elemWindow.style.left);
			var leftSet = (left + Math.round(maxWidth-(widthInc*currentStep))/2);
			var topSet = (top + Math.round(maxHeight-(heightInc*currentStep))/2);
			//alert('leftSet: '+leftSet+' / topSet: '+topSet);
			elemWindow.style.left = leftSet;
			elemWindow.style.top = topSet;
			//alert(elem.width+', '+elem.height);
			var func = "blowupWindow('"+functionToCall+"', "+maxWidth+", "+maxHeight+", "+left+", "+top+", "+(currentStep+1)+", "+maxSteps+", "+timeout+")";
			//alert(func);
			setTimeout(func, timeout);
		}
	}

function clearDefault(el) {
  if (el.defaultValue==el.value) el.value = ""
}


function lmWheel(event) {
	if (!event) event = window.event;
	var delta = 0;
	//var h = document.getElementById(getLayerName(currentSection)).offsetHeight;
	var h = document.getElementById(getLayerListName(currentSection)).offsetHeight;
	h = h / 100;
	//alert(h);
	//h = h.substring(0, h.length()-2);
	//alert(h);
      if (event.wheelDelta) {
            delta = event.wheelDelta*(h/1.9/40);
            if (window.opera) delta = -delta;
      } else if (event.detail) { //firefox
		delta = (-event.detail)*(h/1.9);
      }
	if (delta<-100) delta = -100;
	//alert(delta);
	dw_scrollObj.scrollBy('lnavwin',0, delta, 1);
}

function setText(elem, text) {
	if (BrowserDetect.browser=='Explorer' || BrowserDetect.browser=='Safari')
		elem.innerText = text;
	else
		elem.textContent = text;
}

function go(url) {
	document.location.href = url;
}
if (!document.getElementById && document.all) { document.getElementById = new Function('id', 'return document.all[id]'); }

function openWindow(url, width, height) {
	var params = 'location=no,menubar=no,scrollbars=yes,resizable=yes,left=0,top=0,height='+height+',width='+width;
	window.open(url, '_blank', params);
}
function showSizing() { var params = ''; openWindow('/b/SizingHelp.html', 600, 730); }

/* COMMON BRAND FUNCTIONS HERE */

function updateInfo(brandName){
	var imgObject = document.getElementById('brandsimg');
	//var newImageName = imageHost+'/images/brands/' + brandName;
	var newImageName = '/b/images/brands/' + brandName;
	var lowerCase = newImageName.toLowerCase();
	var nospace = removeSpaces(lowerCase);
	var replaceAmp = nospace.replace("&","and");
	//alert (replaceAmp);
	//var finalImg = replaceAmp + '-header-F.jpg';
	var finalImg = replaceAmp + '.jpg';
	imgObject.style.backgroundImage="url(" +finalImg + ")";
	//document.getElementById('brandsimg').style.backgroundImage=url(replaceAmp);
	//Element.setStyle(imgObject, {background:url(replaceAmp)});

	var txtObject = document.getElementById('branddesc');
	txtObject.innerHTML = '<span class=brandstxttitle>' + brandName + '</span><br>' + SingleObject.myMethod(brandName);
}

function removeSpaces(string) {
	var tstring = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
	tstring += splitstring[i];
	return tstring;
}


function getLayerName(newSection) {
	if (layers) {
		var layerNum = 0;
		for (layerNum=0; layerNum<layers.length; layerNum++)
			if (layers[layerNum]==newSection) { break; }
		var layerName = 'lnav-data' + (layerNum>0 ? layerNum : '');
		//alert(newSection+', '+layerName);
		return layerName;

	} else {
		return 'lnav-data';
	}
}
function getLayerListName(newSection) {
	if (layers) {
		var layerNum = 0;
		for (layerNum=0; layerNum<layers.length; layerNum++)
			if (layers[layerNum]==newSection) { break; }
		var layerName = 'tnav' + (layerNum>0 ? layerNum : '');
		//alert(newSection+', '+layerName);
		return layerName;

	} else {
		return 'lnav-data';
	}
}
function swapSection(newSection) {
		if (currentSection==newSection) return;
		else {
			var elem = document.getElementById(currentSection+'Select');
			elem.style.fontWeight='normal'; elem.style.textDecoration='underline';
			var newElem = document.getElementById(newSection+'Select');
			newElem.style.fontWeight='bold'; newElem.style.textDecoration='none';
			//alert(newSection);
			//alert('loading layer: '+layer);

			dw_scrollObj.loadLayer('lnavwin', getLayerName(newSection));
			//alert(document.getElementById(layer));
			//dw_scrollObj.loadLayer('lnavwin', 'lnav-data');
			currentSection = newSection;
		}
	}

function initScrollLayer() {
   var navWin = document.getElementById('lnavwin');
   if (navWin.addEventListener)
	   navWin.addEventListener('DOMMouseScroll', lmWheel, false);
   var dataLayer = getLayerName(currentSection);
  //if (dataLayer!='lnav-data') document.getElementById('lnav-data').style.visibility='hidden';
  var wndo = new dw_scrollObj('lnavwin', dataLayer, 0, -scrollTo);
  wndo.bSizeDragBar = false;


  if (false) {//BrowserDetect.browser=='Explorer') {
	document.getElementById('select-type').style.width=(menuWidth+'px');
	//document.getElementById('arrows').style.marginLeft+=2;

	 document.getElementById('dragBar1').innerHTML = "<img src='/b/images/dragbar.jpg' />";
	 document.getElementById('dragBar1').style.background='';
	  wndo.setUpScrollbar("dragBar1", "track1", "v", 1, 0);
  } else {
	//alert(document.getElementById('dragBar1'));
	//alert(document.getElementById('dragBar1').style);
	//alert(document.getElementById('dragBar1').style.visibility);

	//alert('blah1');
	  //document.getElementById('dragBar1').style.zIndex=-500;
	wndo.setUpScrollbar("dragBar1", "track1", "v", 1, 0);
  }
  if (false)
	  dw_scrollObj.GeckoTableBugFix('lnavwin');

  //alert('scrolling to');
  dw_scrollObj.scrollTo('lnavwin', 0, scrollTo, 1);
  setTimeout("showBar()", 50);
}
	function showBar() {
		document.getElementById('dragBar1').style.visibility='visible';
	}

	function setCheckBoxDisplay(mode) {
		//alert('setting check box display with mode: '+mode);
		if (!mode) mode = sortBy;
		//alert('mode is: '+sortBy+', currentSubCategoryLoc is: '+currentSubCategoryLoc);
		if (currentSubCategoryLoc>0 && mode=='cat') mode = 'new';
		var checkbox = document.getElementById('pref'+'0'+'m'+mode+'Img');
		checkbox.src = '/b/images/check-yes.gif';

		//alert('filter: '+filter);
		if (filterBySize=='size') {
			document.getElementById('pref'+'0'+'m'+'size'+'Img').src='/b/images/check-yes.gif';
		} else
			document.getElementById('pref'+'0'+'m'+'size'+'Img').src='/b/images/check-no.gif';

		//alert('setting stuff');
		//alert(currentSubCategoryLoc);
		//alert(document.getElementById('pref'+'0'+'m'+'catImg'.src));
		if (currentSubCategoryLoc!=0) {
			document.getElementById('pref'+'0'+'m'+'catImg').src='/images/spacer.gif';
			setText(document.getElementById('catSortLabel'), '');
		} else {
			setText(document.getElementById('catSortLabel'), 'Category');
		}

		if (mode!='cat' && currentSubCategoryLoc==0) document.getElementById('pref'+'0'+'m'+'catImg').src='/b/images/check-no.gif';
		if (mode!='new') document.getElementById('pref'+'0'+'m'+'newImg').src='/b/images/check-no.gif';
		if (mode!='price') document.getElementById('pref'+'0'+'m'+'priceImg').src='/b/images/check-no.gif';
		if (mode!='popularity') document.getElementById('pref'+'0'+'m'+'popularityImg').src='/b/images/check-no.gif';
		//alert('done');
		//alert(checkbox);
		//if (!checkbox) return;
		//alert('exiting setCheckBoxDisplay');
	}



	function applyFilterBySize() {
		//alert('filter by size');
		if (!prefsSet || prefsSet==false) {
			showSizeDiv();
		} else {
			var checkbox = document.getElementById('pref'+'0'+'m'+'size'+'Img');
			//var pageGroup = document.getElementById('pg'+'0'+'c'+'0');
			//var filter = getFilterBySize();
			//alert(filterBySize);
			if (filterBySize=='size') {
				checkbox.src = '/b/images/check-no.gif';
				saveFilterBySize('');
				if (preload) {
					sortProducts(sortBy, '', '', 'true');
					adjustPageGroupSettings(products, pageGroup);
				} else {
					document.location.href = removeFilterBySizeURL;
				}
			} else {
				checkbox.src = '/b/images/check-yes.gif';
				//alert('setting filter by size to size');
				saveFilterBySize('size');
				if (preload) {
					sortProducts(sortBy, '', '', 'true');
					adjustPageGroupSettings(products, pageGroup);
				} else {
					document.location.href = addFilterBySizeURL;
				}
				//sort products
			}
		}
	}

	function applyFilterByColor() {
		if (!colorPrefsSet || colorPrefsSet==false) {
			showColorDiv();
		} else {
			var checkbox = document.getElementById('pref'+'0'+'m'+'size'+'Img2');
			if (filterByColor=='color') {
				checkbox.src = '/b/images/check-no.gif';
				document.location.href = removeFilterByColorURL;
			} else {
				checkbox.src = '/b/images/check-yes.gif';
				document.location.href = addFilterByColorURL;
			}
		}
	}


	function sortProducts(mode, start, finish, force) {
		//alert('sorting products');
		if (false);
		else {
			setCheckBoxDisplay(mode);


			if (!start) start = 0; if (!finish) finish = productsPerPage;

			//alert(mode);
			//alert(filter);
			//alert((filter=='size'));
			if (mode=='cat') {
				if (catSort!='asc' || start>0 || force) {
					sortBy='cat';
					if (currentSubCategory=='main') products = (filterBySize=='size') ? cSFP : cSP;
					else setProductsNoSwap();
					swap(start, finish);
				}
				catSort = 'asc'; newSort = ''; priceSort=''; popSort='';
			} else if (mode=='new') {
				if (newSort!='asc' || start>0 || force) {
					sortBy='new';
					if (currentSubCategory=='main') products = (filterBySize=='size') ? nSFP : nSP;
					else setProductsNoSwap();
					swap(start, finish);
				}
				catSort = ''; newSort = 'asc'; priceSort=''; popSort='';
			} else if (mode=='price') {
				if (priceSort!='asc' || start>0 || force) {
					sortBy='price';
					if (currentSubCategory=='main') products = (filterBySize=='size') ? pSFP : pSP;
					else setProductsNoSwap();
					//alert('swapping price sorted products...'+start+', '+finish);
					swap(start, finish);
				}
				catSort = ''; newSort = ''; priceSort='asc'; popSort='';
			} else if (mode=='popularity') {
				//alert('sorting by popularity');
				if (popSort!='asc' || start>0 || force) {
					sortBy='popularity';
					if (currentSubCategory=='main') products = (filterBySize=='size') ? poSFP : poSP;
					else setProductsNoSwap();
					//alert('swapping price sorted products...'+start+', '+finish);
					swap(start, finish);
				}
				catSort = ''; newSort = ''; priceSort=''; popSort='asc';
			}
		}
	}

	var imageHash;

	var currSetArray;
	var currSetLoc;

	function getImageSrc(product) {
		if (!product.imageSrc) {
			product.imageSrc = getImageHost(product.code)+'/images/'+product.code+'_CAT.jpg'
		}
		return product.imageSrc;
	}

	function getLink(product) {
		if (!product.link) {
			product.link = 'product_info.php?products_id=' + product.code + '&' + (navParams ? navParams : '');
		}
		return product.link;
	}


	function set(name, code, model, price,image,slide_images) {
		var elem = new Object();
		var images = new Array();
		if(slide_images) images = slide_images.split(";");
		elem.code = code;
		elem.name = name;
		elem.model = model;
		elem.price = price;
		elem.image = image;
		elem.images = images;
		elem.numViews = images.length;
		currSetArray[currSetLoc] = elem;
		currSetLoc++;
	}
	function st(code) {
		currSetArray[currSetLoc] = imageHash[code];
		currSetLoc++;
	}

	function createShortLivedCookie(name,value,minutes) {
		if (minutes) {
			var date = new Date();
			date.setTime(date.getTime()+(minutes*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}


	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	function eraseCookie(name) {
		createCookie(name,"",-1);
	}


	function savePageInfo(start, finish) {
		lastStart = start;
		lastFinish = finish;
		//alert('saving info'+start+', '+finish+', '+sortBy);
		createCookie(pageSaveString+'start', start);
		createCookie(pageSaveString+'finish', finish);
		createCookie(pageSaveString+'sortBy', sortBy);
	}

	function getSubCategoryCookieName() {
		return pageSaveString+'subCategory';
	}

	function saveSubCategory(subCategory, subCategoryLoc) {
		createCookie(getSubCategoryCookieName(), subCategory);
		createCookie(pageSaveString+'subCategoryLoc', subCategoryLoc);
		//alert('saved cookie: '+getSubCategoryCookieName()+' with value: '+getSubCategory()+'/'+subCategory);
	}

	function getSubCategory() {
		var cookieName = getSubCategoryCookieName();//pageSaveString+'subCategory';
		//alert('reading cookie: '+cookieName);
		var ret = readCookie(cookieName);
		if (ret) return ret;
	}
	function getSubCategoryLoc() {
		var cookieName = pageSaveString+'subCategoryLoc';
		var ret = readCookie(cookieName);
		if (ret) return eval(ret);
	}

	function getFilterBySizeCookieName() { return pageSaveString+'filterBySize'; }
	function saveFilterBySize(value) {
		//if (!value) value = filter;
		var cookieName = getFilterBySizeCookieName();
		createCookie(cookieName, value);
		filterBySize = value;
	}
	function getFilterBySize() {
		var cookieName = getFilterBySizeCookieName();
		var ret = readCookie(cookieName);
		if (ret) return ret;
	}

	function getSortBy() {
		var cookieName = pageSaveString+'sortBy';
		var ret = readCookie(cookieName);
		if (ret) return ret;
	}
	function getStart() {
		var ret = readCookie(pageSaveString+'start');
		if (ret) return eval(ret);
	}
	function getFinish() {
		var ret = readCookie(pageSaveString+'finish');
		if (ret) return eval(ret);
	}

	var displayViewPulldown = true;
	function hideViewPulldown() {
		displayViewPulldown = false;
		document.getElementById('viewpulldown').style.visibility = 'hidden';
	}
	function showViewPulldown() {
		displayViewPulldown = true;
		document.getElementById('viewpulldown').style.visibility = 'visible';
	}

	function showSizeDivNow() {
		document.getElementById('sizeDiv').style.zIndex = 10;
		document.getElementById('sizeDiv').style.visibility = 'visible';
	}

	function showSizeDiv() {
		var elem = document.getElementById('sizeDiv');
		hideViewPulldown();
		blowupWindow('showSizeDivNow()', 548, 250, 290, 40, 1, 10, 4);
	}

	function hideSizeDiv() {
		document.getElementById('sizeDiv').style.visibility = 'hidden';
		showViewPulldown();
		document.getElementById('sizeDiv').style.zIndex = -1;
	}

	function showColorDivNow() {
		document.getElementById('colorDiv').style.zIndex = 11;
		document.getElementById('colorDiv').style.visibility = 'visible';
	}

	function showColorDiv() {
		var elem = document.getElementById('colorDiv');
		hideViewPulldown();
		blowupWindow('showColorDivNow()', 548, 250, 290, 40, 1, 10, 4);
	}

	function hideColorDiv() {
		document.getElementById('colorDiv').style.visibility = 'hidden';
		showViewPulldown();
		document.getElementById('sizeDiv').style.zIndex = -1;
	}

	function showWaitDiv() {
		//alert('showing wait div');
		document.getElementById('imageWait').style.visibility = 'visible';
	}
	function hideWaitDiv() {
		document.getElementById('imageWait').style.visibility = 'hidden';
	}

	var canceled = false;
	var bigViewVisible = false;
	var bvCode;
	var currentBVCode;
	var bvRow;
	var bvCol;
	var yyPos;
	var productCodeHash = {};
	var swheight = 0;
	var swwidth  = 0;


	var bigImageLoc = 0;
	var numBigImages = 0;

	function nextBigView() {		if (!numBigImages) return;
		bigImageLoc++;
		if (bigImageLoc>=(numBigImages)) bigImageLoc = 0;
		swapBigPic();
	}

	function prevBigView() {		if (!numBigImages) return;
		bigImageLoc--;
		if (bigImageLoc<0) bigImageLoc = numBigImages-1;
		swapBigPic();
	}

	function swapBigPic() {
		var pic = document.getElementById('bigViewImg');
		var product = imageHash[currentBVCode];
		var numViews = product.numViews;
		var code = currentBVCode;
		pic.src = imageHost + 'images/' + product.images[bigImageLoc];

		checkBigViewLoaded(currentBVCode);
	}

	var needToLoadAlternateViews = true;
	var needToLoadSecondView = true;
	function showBigView(code, leftDivName, rightDivName) {
	//    alert("code: " + imageHash[code].code);
	//    alert("name: " + imageHash[code].name);
	//    alert("price: " + imageHash[code].price);
	//    alert("retailPrice: " + imageHash[code].retailPrice);
	//    alert("isNew: " + imageHash[code].isNew);
	//    alert("inventory: " + imageHash[code].inventory);
	//    alert("numViews: " + imageHash[code].numViews);
		//var s = document['pR'+r+'C'+c+'Pic'].src;
		row=0;
		col=1;


		var newCode = productCodeHash['pR'+row+'C'+col];
		if (newCode) code = newCode;
		if (!code || code=='blank') return;
		else {
			canceled = false;
			bigViewVisible = true;
			if (!imageHash) return;
			var product = imageHash[code];
			if (!product) return;

			if (!product.bigPic) {
				product.bigPic = new Image();
				if ( isSafari )product.bigPic.src = imageHost + '/images/pixel_trans.gif';
				product.bigPic.src = imageHost +'/images/'+ product.image;
				swheight = ((product.bigPic.height));
				swwidth  = ((product.bigPic.width));
			} else {
				if (isSafari) {
					product.bigPic = new Image();
					if ( isSafari ) product.bigPic.src = imageHost + '/images/pixel_trans.gif';
					product.bigPic.src = imageHost +'/images/'+ product.image;
					swheight = ((product.bigPic.height));
					swwidth  = ((product.bigPic.width));
				}
			}

			var numViews = product.numViews;

			bvCode = code;
			bvRow = row;
			bvCol= col;

			var colPos;
			if (col>=5) {
				colPos = col==5 ? 3 : 4
			} else
				colPos = (col+1);
			var left = (colPos)*112+10;
			var rowPos = (row-1); if (rowPos<0) rowPos = 0;
			var top = 20+((rowPos)*(180+40));

			//blowupWindow('showBigViewNow()', 180, 360, left, top, 1, 20, 10);
			setTimeout("showBigViewNow('"+code+"','" + leftDivName + "','" + rightDivName + "')", 50);
		}
	}

	function wheelHide() {
		hideBigView();isOnImage=false;timeOnImage=0;lastReturnedContext=true;lastMWTime = (new Date().getTime());return true;
	}
	function hideBigView(leftDivName, rightDivName) {
		bvCode='';
		bigViewVisible = false;
		bigViewLastClosed = new Date().getTime();
		setTimeout("hideBigViewNow('" +leftDivName + "','" + rightDivName + "')", 1);
	}

	var lastBVCode='';
	function cancelCancelBV() {
		if (lastBVCode && !lastBVCode=='') bvCode = lastBVCode;
	}
	function hideBigView2() {
		lastBVCode=bvCode;
		bvCode='';
		bigViewVisible = false;
		bigViewLastClosed = new Date().getTime();
		setTimeout("hideBigViewNow()", 1);
	}

	function cancelHideBigView() {
		bigViewVisible = true;
		bigViewState = 'open';
	}
	function forceHideBigViewNow() {
		bvCode='';
		bigViewVisible = false;
		hideBigViewNow();
	}
	function hideBigViewNow2() {
		bvCode='';
		hideBigViewNow();
	}
	function hideBigViewNow(leftDivName, rightDivName) {
		if (bigViewVisible==false) {

			//if (displayViewPulldown) document.getElementById('viewpulldown').style.visibility='visible';

			var elem = document.getElementById('bigViewDiv');
			elem.style.visibility='hidden';
			bigViewState = 'closedForGood';
			bigViewVisible = false;

			var leftArrow = document.getElementById(leftDivName);
			if (leftArrow) leftArrow.style.visibility='hidden';
			var rightArrow = document.getElementById(rightDivName);
			if (rightArrow) rightArrow.style.visibility='hidden';
		}
	}

	function hideBigViewCheckDelay() {
		var elem2 = document.getElementById('addProductText');
		if (delayBigViewClosing==true) {
			delayBigViewClosing = false;
			setText(elem2, new Date().getTime()+'ignoring close, setting to check again in 50 ms');
			setTimeout("hideBigViewCheckDelay()", 50);
			return;
		}
		setText(elem2, new Date().getTime()+'closing');
		if (bigViewVisible==true && bigViewState!='open') {
			setText(elem2, new Date().getTime()+'closing for real');
			var elem = document.getElementById('bigViewDiv');
			elem.style.visibility='hidden';
			bigViewState = 'closedForGood';
			bigViewVisible = false;
			var leftArrow = document.getElementById('bigViewLeftArrowDiv');
			if (leftArrow) leftArrow.style.visibility='hidden';
			var rightArrow = document.getElementById('bigViewRightArrowDiv');
			if (rightArrow) rightArrow.style.visibility='hidden';
		}
	}


	var delayBigView = false;
	var bigViewState = 'closed';
	var delayBigViewClosing = false;
	var bigViewLastClosed = 0;
	var lastMWTime = 0;
	var bigViewLastRightClick = 0;

	var mouseX;
	var mouseY;
	var bigViewOpenTime;

	function catMouseMove(event) {
		delayBigView=true;
	}

	/*function catMouseMove(event) {
		var elem = document.getElementById('addProductText');
		if ( (new Date()).getTime()<=(bigViewOpenTime+1000) ) return;
		else if (mouseX==event.clientX && mouseY==event.clientY) {
			setText(elem, new Date().getTime()+'same coords: ('+mouseX+', '+mouseY+'), ('+event.clientX+', '+event.clientY+')');
			return;
		} else {
			setText(elem, new Date().getTime()+'different coords: ('+mouseX+', '+mouseY+'), ('+event.clientX+', '+event.clientY+')');
			mouseX = event.clientX;
			mouseY = event.clientY;
			if (bigViewState=='closed') {
				delayBigView=true;
			} else if (bigViewState=='open') {
				bigViewState='closing';
 				delayBigViewClosing = false;
				setText(elem, new Date().getTime()+'closing');
				setTimeout("hideBigViewCheckDelay()", 50);
			} else if (bigViewState=='closing') {
				setText(elem, new Date().getTime()+'delaying');
				delayBigViewClosing = true;
			}
		}
	}*/

	function delayBigView() {
		//alert('delay big view');
		//delayBigView = true;
	}
	function test() {
	}

	var lastCol = -1;
	var leftStart = 172;
	var picWidth = 117;
	var bigWidth = 274+2;
	var rightStart = leftStart+(7*picWidth)-bigWidth;

	function getX(col, left) {
		var pos;
		if (left==true && false) {
			col = col + 1;
			pos = 2+leftStart+col*picWidth;
		} else {
			pos = rightStart-(6-col)*picWidth;
		}
		return pos;
	}

	function hideImageLoadingDiv() {
		document.getElementById('imgLoading').style.visibility='hidden';
	}

	var bigViewWaitState = 0;
	function checkBigViewLoaded(code) {
		var loaded = false;
		var pic = document.getElementById('bigViewImg');
		var product = imageHash[code];
		var bigPic = product.bigPic;
		//if (bigImageLoc>0) alert(bigImageLoc);
		/*
		switch (bigImageLoc) {
			case 0: bigPic = product.bigPic; break;
			case 1: bigPic = product.bigPic2; break;
			case 2: bigPic = product.bigPic3; break;
			case 3: bigPic = product.bigPic4; break;
			case 4: bigPic = product.bigPic5; break;
			case 5: bigPic = product.bigPic6; break;
			case 6: bigPic = product.bigPic7; break;
			case 7: bigPic = product.bigPic8; break;
		}
		*/
	   bigPic = product.images[bigImageLoc]

		if (isIE && pic.readyState=='loading')
			pic.src = bigPic.src;
		if ((bigPic.width>0 && !isIE) || (isIE && pic.readyState=='complete')) { loaded = true; }
		//if (bigPic.width>0 && (!isIE || pic.readyState=='complete')) { loaded = true; }
		//window.status=pic.readyState;
		if (loaded==true) { // && pic.readyState=='complete') {
			if (!isIE) {
				pic.src = bigPic.src;
				pic.style.visibility='inherit';
				setTimeout("hideImageLoadingDiv()", 400);
			} else
				document.getElementById('imgLoading').style.visibility='hidden';
		} else {
			//alert('still loading');
			var loadText = document.getElementById('imgLoadingSpan');
			if (bigViewWaitState<5) setText(loadText, 'Image Loading..');
			else if (bigViewWaitState<10) setText(loadText, 'Image Loading...');
			else if (bigViewWaitState<15) setText(loadText, 'Image Loading....');
			else setText(loadText, 'Image Loading.....');
			if (bigImageLoc==0) {
				document.getElementById('bgImage').src = '/b/images/productbg.jpg';
			}
			else document.getElementById('bgImage').src = '/images/spacer.gif';
			document.getElementById('imgLoading').style.visibility='inherit';
			bigViewWaitState++; if (bigViewWaitState>=20) bigViewWaitState = 0;
			setTimeout("checkBigViewLoaded('"+code+"')", 100);
		}
	}

	function getScrollTop() {
		var ScrollTop = document.body.scrollTop;
		if (ScrollTop == 0) {
		if (window.pageYOffset)
			ScrollTop = window.pageYOffset;
		else
			ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
		}
		return ScrollTop;
	}
function getAbsPos( oId, tl ) {
var o = ( typeof oId == 'String' ) ? document.getElementById( oId ) : oId;
var val = 0;
while ( o.nodeName != "BODY" ) {
val += parseInt( ( tl == 'top' ) ? o.offsetTop : o.offsetLeft );
o = o.parentNode;
}
return val;
}

	var forceBigView = false;
	function showBigViewNow(matchCode,leftDivName, rightDivName) {
		/*
		//if we recently scrolled don't show it yet!!!
		var now = new Date();
		if ( (now.getTime() - lastScrollTime.getTime()) < 400)
		{
			//console.log("return");
			return;
		}
		//console.log("continue");
		*/

		if (delayBigView==true) {
			delayBigView = false;
			setTimeout("showBigViewNow('"+matchCode+"','" + leftDivName + "','" + rightDivName + "')", 50);
			return;
		}

		bigViewOpenTime = new Date().getTime();
		bigViewState = 'open';
		var code = bvCode;
		var row = bvRow;
		var col = bvCol;


		if ((canceled==true || (matchCode && matchCode!=code)) && forceBigView==false) {
			canceled=false;
			return;
		} else {

			if (forceBigView) {
				forceBigView = false;
				code = matchCode;
				//return;
			}

			//alert('showing big div');
			//alert(code);

			currentBVCode = code;
			var product = imageHash[code];
			//if(!product || !product.numViews) alert(code+', '+matchCode);
			//alert('setting big images for product: '+code+' to : '+product.numViews);
			numBigImages = product.numViews; bigImageLoc = 0;
//if (col==0) {window.status='SBD '+matchCode+' '+code; return; }

			var pic = document.getElementById('bigViewImg');
			//pic = new Image();
			document.getElementById('imgLoading').style.visibility='hidden';
			pic.src = product.bigPic.src;////getImageHost(code)+'/images/'+code+'_V1.jpg';
			setTimeout("checkBigViewLoaded('"+code+"')", 100);

			//pic.src = getImageHost(code)+'/images/'+code+'_V1.jpg';
			var name = document.getElementById('bigViewLink2');
			name.href = getLink(product);
			setText(name, product.name);
			document.getElementById('bigViewLink').href=getLink(product);
			setText(document.getElementById('bigViewInventory'), product.model);
			if (product.retailPrice=='') {
				//setText(document.getElementById('bigViewRetailPrice'), '');
				setText(document.getElementById('bigViewPrice'), product.price);
			} else {
				//setText(document.getElementById('bigViewRetailPrice'), product.retailPrice);
				setText(document.getElementById('bigViewPrice'), '  '+product.price);
			}


			var elem = document.getElementById('bigViewDiv');
			var colPos;
			if (col>=5) {
				colPos = col==5 ? 3 : 4
			} else
				colPos = (col+1);
			if (col<2 || col>5) elem.style.left=447;
			else {
				elem.style.left = 247;
			}

			elem.style.left = (colPos)*112+10+173;
			if (col==0) col = 3;
			var left = getX(col, true)-88;
			//if (left<leftStart) left = leftStart;
			elem.style.left = left;
			//elem.style.left = (colPos)*112+10+173;

			var rowPos = (row); if (rowPos<0) rowPos = 0;

			if (popLeft) {
				var mww = document.getElementById('mww');
				var pc = document.getElementById('popClose');
				//alert(mww);
				//alert(mww.style.width);
				var mw = document.getElementById('masterwrapper');
				var mwL = getAbsPos(mw, 'left');
				if (mwL>10) {
					mwL = -mwL+8;
					if (mwL<-86) mwL = -86;
					elem.style.left = mwL;
					pc.width=152 + (4-mwL)
				} else {
					elem.style.left = 4;
					pc.width=152;
				}
				//elem.style.left = bvCol>0 ? left - 70 : left+90;
				elem.style.top = 110+getScrollTop();
				var leftArrow = document.getElementById(leftDivName);
				if (leftArrow) {
					//leftArrow.style.left = bvCol*117+173+2;
					//leftArrow.style.top = 287+((row)*(rowHeight));
					leftArrow.style.visibility='visible';
				}
				var rightArrow = document.getElementById(rightDivName);
				if (rightArrow) {
					//rightArrow.style.left = bvCol*117+173+90;
					//rightArrow.style.top = 287+((row)*(rowHeight));
					rightArrow.style.visibility='visible';
				}
			} else {
				if (rowPos==0)
				{
					elem.style.top = 180;
				}
				else if ( rowPos > 0 && yMousePos < 270 )
				{
					elem.style.top = ((rowPos+1)*(rowHeight-2))- 40 ;
				}
				else {
					elem.style.top = 95+((rowPos-1)*(rowHeight-2));
				}
			}

			elem.style.visibility='visible';
			bigViewVisible = true;

//			if ( row == 1  && (col==4 || col==5 || col==6))
//			{
//				//document.getElementById('viewpulldown').style.visibility='hidden';
//			}
//			else
//			{
//				if (displayViewPulldown)  document.getElementById('viewpulldown').style.visibility='visible';
//			}

			var theBigImage = document.getElementById('bigViewImg');
			if ( theBigImage != null && theBigImage != 'undefined' )
			{
				if (isSafari) {
					theBigImage.style.height = swheight;
					theBigImage.style.width = swwidth;
				}

			}
			var numViews = product.numViews;
			if (allBigLoaded()) {
				needToLoadSecondView = false;
				needToLoadAlternateViews = true;
				if (numViews>=2) { product.bigPic2 = new Image(); product.bigPic2.src = getImageHost(currentBVCode)+'/images/'+currentBVCode+'_V2.jpg'; }
			} else {
				needToLoadSecondView = true;
				needToLoadAlternateViews = true;
			}
		}
	}

	function swapToLoc(start, finish) {
		var currPageGroup = getPageGroup(lastStart);
		var maxPages = globalMaxPages;
		var productsPerGroup = maxPages*productsPerPage;
		start = start + (currPageGroup*productsPerGroup);
		finish = finish + (currPageGroup*productsPerGroup);
		swap(start, finish);
	}

	function swap(start, finish) {
		//alert('swapping: '+start+', '+finish);
		var currPageGroup = getPageGroup(lastStart);
		swapWhenReady(start, finish);
		var newPageGroup = getPageGroup(lastStart);

		//alert('curr page group: '+currPageGroup+', new page group: '+newPageGroup);
		if (true) { //newPageGroup!=currPageGroup) {
			adjustPageGroupSettings(products, document.getElementById('pg0c0'));
			//document.getElementById('pg'+currPageGroup+'c'+currentSubCategoryLoc).style.visibility = 'hidden';
			//document.getElementById('pg'+newPageGroup+'c'+currentSubCategoryLoc).style.visibility = 'visible';

			//document.getElementById('pg'+currPageGroup+'c'+currentSubCategoryLoc).style.visibility = 'hidden';
			//document.getElementById('pg'+newPageGroup+'c'+currentSubCategoryLoc).style.visibility = 'visible';
		}
		//hideWaitDiv();
	}

	function imageLoaded() {
		alert('image loaded');
	}

	//only swap when ready
	function swapWhenReady(start, finish, max) {
		//alert('swap when ready');
		if (!max) max = 0;
		var r=0; var c=0;
		var done = false;
		var count = start;

		var ready = true;
		var badCount = 0;
		//alert('ready state: '+products[0].image.readyState);
		//alert(products[130].image.onload);
		//products[130].image.onload="alert('image onload test worked!!')";
		//alert('img complete: '+products[130].image.complete);
		var image;
		for (r=0; count<finish; r++) {
			if (done) break;
			for (c=0; c<7; c++) {
				if (count==finish) { done = true; break; }
				if (count<products.length) {
					image = products[count].image;
					if (!image) {
						image = new Image(); image.src = getImageSrc(products[count]);
						products[count].image = image;
					}
					// || image.readyState=='uninitialized'
					if (!image || (image.readyState && (image.readyState=='loading'))) {
						//alert(image.readyState);
						badCount++;
					}
				}
				count++;
				if (badCount>=3) { ready = false; break; }
			}
		}
		//alert(ready);
		if (max==0) {
			var newPage = start/productsPerPage+1;
			if (document.getElementById('ps'+currentPage+'c'+currentSubCategoryLoc)) {
				document.getElementById('ps'+currentPage+'c'+currentSubCategoryLoc).style.fontWeight='normal';
				document.getElementById('ps'+currentPage+'c'+currentSubCategoryLoc).style.textDecoration='underline';
			}
			if (document.getElementById('ps'+newPage+'c'+currentSubCategoryLoc)) {
				document.getElementById('ps'+newPage+'c'+currentSubCategoryLoc).style.fontWeight='bold';
				document.getElementById('ps'+newPage+'c'+currentSubCategoryLoc).style.textDecoration='none';
			}
			currentPage = newPage;
			savePageInfo(start, finish);
		}
		if (ready || max>=10) {
			//alert('swapping products now!!');
			swapProducts(start, finish);
			hideWaitDiv();
		} else {
			var wait = max<1 ? 10 : max<2 ? 20 : max<4 ? max*50 : 500;
			if (max>=4) showWaitDiv();
			setTimeout("swapWhenReady("+start+", "+finish+", "+(max+1)+")", wait);
		}
	}

	function isLastPageGroup(page, numPages) {
		var maxPages = globalMaxPages;
		var thisGroup = divide(page-1, maxPages);
		var maxGroup = divide(numPages-1, maxPages);
		return (maxGroup>thisGroup);
	}

	function getPageGroup(start) {
		var productsPerGroup = (productsPerPage*globalMaxPages);
		var sub = start%productsPerGroup;
		var result = (start-sub)/productsPerGroup;
		return result;

		//result = result - 0.49;
		//alert(result);
		//alert(result.toFixed(0));
		//result = result.toFixed(0);
		//if (result<=0) result = eval(0);
		//return result;
	}

	function nextPage() {
		var start = lastFinish;	if (start<0) start = 0;
		var finish = lastFinish+productsPerPage;
		//alert(start+', '+finish);
		//if (finish>=productsSize) finish = (globalNumPages*productsPerPage);
		if (finish>=products.length) {
			finish = products.length;
			var remainder = (products.length % productsPerPage);
			if (remainder>0) {
				finish = products.length - remainder + (productsPerPage);
			}
		}

		if (start<finish) {
			swap(start, finish);
		}
	}

	function nextPageGroup() {
		var finish = lastFinish+(productsPerPage*globalMaxPages);
		if (finish>=products.length) {
			finish = products.length;
			var remainder = (products.length % productsPerPage);
			if (remainder>0) {
				finish = products.length - remainder + (productsPerPage);
			}
		}

		var start = finish - productsPerPage;

		if (start<finish) {
			swap(start, finish);
		}
	}

	function prevPage() {
		var start = lastStart-productsPerPage; if (start<0) start = 0;
		var finish = lastStart;
		if (finish>=productsSize) finish = (globalNumPages*productsPerPage);

		if (start<finish) {
			swap(start, finish);
		}
	}

	function prevPageGroup() {
		var start = lastStart-(productsPerPage*globalMaxPages); if (start<0) start = 0;
		var finish = lastFinish-(productsPerPage*globalMaxPages);
		if (finish>=productsSize) finish = (globalNumPages*productsPerPage);

		if (start<finish) {
			swap(start, finish);
		}
	}

	function getText(elem) {
		if (BrowserDetect.browser=='Explorer') return elem.innerText;
		return elem.textContent;
	}

	function swapProducts(start, finish) {

		//alert('swapProducts: '+start+', '+finish);

		var done = false;
		var count = start;
		var r = 0;
		while (count<finish) {
			if (done) break;
			for (var c=0; c<7; c++) {
				if (count==finish) { done = true; break; }

				if (count<products.length) {
					//alert('retreiving image');
					document['pR'+r+'C'+c+'Pic'].src = getImageSrc(products[count]);
					productCodeHash['pR'+r+'C'+c] = products[count].code;

					if (!products[count].bigPic) {
						products[count].bigPic = new Image();
						products[count].bigPic.src = getImageHost(products[count].code)+'/images/'+products[count].code+'_V1.jpg';
					}
					//alert(document.getElementById('pR'+r+'C'+c+'Container').onmouseover);
					//document.getElementById('pR'+r+'C'+c+'Container').onmouseover = "function anonymous() { showBigView('"+products[count].code+"', "+r+", "+c+"); }";
					//alert(document.getElementById('pR'+r+'C'+c+'Container').onmouseover);
					//document['pR'+r+'C'+c+'Pic'].src = '/b/images/imageloading.gif';

					if (BrowserDetect.browser=='Explorer') {
						document.getElementById('pR'+r+'C'+c+'Link').href = getLink(products[count]);
						document.getElementById('pR'+r+'C'+c+'Price').innerText = products[count].price;
						document.getElementById('pR'+r+'C'+c+'Link2').href = getLink(products[count]);
						document.getElementById('pR'+r+'C'+c+'Link2').innerText = products[count].name;
						document.getElementById('pR'+r+'C'+c+'PriceLabel').innerText = 'Price: ';
					} else {
						//alert(document.getElementById('pR'+r+'C'+c+'Price').textContent);
						document.getElementById('pR'+r+'C'+c+'Link').href = getLink(products[count]);
						document.getElementById('pR'+r+'C'+c+'Price').textContent = products[count].price;
						document.getElementById('pR'+r+'C'+c+'Link2').href = getLink(products[count]);
						document.getElementById('pR'+r+'C'+c+'Link2').textContent = products[count].name;
						document.getElementById('pR'+r+'C'+c+'PriceLabel').textContent = 'Price: ';
					}
					setText(document.getElementById('pR'+r+'C'+c+'NewLabel'), products[count].isNew ? '  New' : '');
				} else {
					//alert('subbing spacer');
					if (document['pR'+r+'C'+c+'Pic']) {
						productCodeHash['pR'+r+'C'+c] = 'blank';
	 					document['pR'+r+'C'+c+'Pic'].src = '/images/spacer.gif';
						document['pR'+r+'C'+c+'Pic'].height = 180;
						if (BrowserDetect.browser=='Explorer') {
							document.getElementById('pR'+r+'C'+c+'Link').href = '#';
							document.getElementById('pR'+r+'C'+c+'Price').innerText = '';
							document.getElementById('pR'+r+'C'+c+'Link2').href = '#';
							document.getElementById('pR'+r+'C'+c+'Link2').innerText = '';
							document.getElementById('pR'+r+'C'+c+'PriceLabel').innerText = '';
						} else {
							document.getElementById('pR'+r+'C'+c+'Link').href = '#';
							document.getElementById('pR'+r+'C'+c+'Price').textContent = '';
							document.getElementById('pR'+r+'C'+c+'Link2').href = '#';
							document.getElementById('pR'+r+'C'+c+'Link2').textContent = '';
							document.getElementById('pR'+r+'C'+c+'PriceLabel').textContent = '';

						}
						setText(document.getElementById('pR'+r+'C'+c+'NewLabel'), '');
					} else
						;//alert('bad count: '+count+' out of '+finish);
				}
				count++;
			}
			r++;
		}
	}
	var products;
	var nSP;
	var cSP;
	var pSP;
	var poSP;

	var nCSP;
	var pCSP;
	var poCSP;

	var nSFP;
	var cSFP;
	var pSFP;
	var poSFP;

	var nCSFP;
	var pCSFP;
	var poCSFP;

	var catStartHash = {};
	var catFinishHash = {};
	var catSizeFilterStartHash = {};
	var catSizeFilterFinishHash = {};



	var subCatCaseHash = {};

	function hidePageGroup(elem) {
		//alert(elem.childNodes[0].style.width);
		//elem.style.width=0;
		elem.style.paddingRight=0; elem.style.paddingLeft=0;
		//elem.style.backgroundColor='white';
		var link = elem.childNodes[0];
		//if (eval(link.innerText)<10)
		//	link.style.width=0;
		setText(link,'');
		link.style.textDecoration='none';
		link.onBlur=link.onClick;
		link.onClick='';
		link.href='';
		elem.style.borderRight='0px solid white';
	}

	function showPageGroup(elem, pageNum) {
		//alert('showing: '+pageNum);
		//alert(elem.childNodes[0].style.width);

		//link.style.width=6;
		//if (link.innerText) if (eval(link.innerText)>=10) link.style.width=10;


		var link = elem.childNodes[0];
		//link.style.width='';
		setText(link, pageNum);
		link.style.textDecoration = pageNum==currentPage ? 'none' : 'underline';
		link.style.fontWeight = pageNum==currentPage ? 'bold' : 'normal';
		if(link.onBlur) link.onClick=link.onBlur;
		link.href='javascript:;';
		elem.style.paddingLeft=6;
		elem.style.paddingRight=6;
		elem.style.borderRight='1px solid black';
	}

	function divide(a, b) {
		var remainder = a % b;
		a = a - remainder;
		return a / b;
	}

	function adjustPageGroupSettings(products, pageGroup) {
		//alert('adjustPageGroupSettigns: '+pageGroup.id);
		//alert(pageGroup.childNodes[0]);
		//if (!pageGroup) pageGroup = document.getElementById('pg0c0');
		//var elem = pageGroup.childNodes[0].childNodes;

		var elemParent = document.getElementById('pgList');
		var elem = elemParent.childNodes;
		//alert(elemParent); alert(elem); alert(elem.length);
		//alert(elem);
		//alert(products.length);


		var finish = products.length;
		var remainder = (products.length % productsPerPage);
		if (remainder>0)	finish = products.length - remainder + (productsPerPage);
		var numPages = (finish)/productsPerPage;
		var maxPages = globalMaxPages;

		var prev = true;
		var rw = currentPage>maxPages;
		var next = currentPage<numPages;
		var fw = isLastPageGroup(currentPage, numPages); //(currentPage-1)<(maxPages);


		document.getElementById('rw').src = rw ? '/b/images/rewind-arrows.jpg' : '/images/spacer.gif';
		document.getElementById('rwli').style.borderRight = rw ? '1px solid #444' : '1px solid white';
		document.getElementById('prev').src = prev ? '/b/images/rewind-arrow.jpg' : '/images/spacer.gif';
		document.getElementById('prevli').style.borderRight = prev ? '1px solid #444' : '1px solid white';
		document.getElementById('nextArrow').src = next ? '/b/images/arrow.jpg' : '/images/spacer.gif';
		document.getElementById('nextli').style.borderRight = next ? !fw ? '1px solid white' : '1px solid #444' : '1px solid white';
		document.getElementById('fw').src = fw ? '/b/images/arrows.jpg' : '/images/spacer.gif';
		document.getElementById('fwli').style.borderRight = fw ? '1px solid #444' : '1px solid white';

		//if (numPages>maxPages) numPages = maxPages;
		//alert(numPages);
		var page;
		var maxPages = globalMaxPages;
		var currentPageGroup = divide(currentPage-1, maxPages);
		for (var i=2; i<(elem.length-3); i++) {
			page = i - 1 + (currentPageGroup)*maxPages;
			//alert(page+', '+currentPage);
			if (page>numPages) {
				//alert('need to hide page group: '+(i-1));
				hidePageGroup(elem[i]);
			} else
				showPageGroup(elem[i], page);
		}
	}

	function setProducts(subCategory, subCategoryLoc, noSwap) {
		//alert('subcategory: '+subCategory+', subcategory loc: '+subCategoryLoc);
		if (!subCategoryLoc) subCategoryLoc = 0;
		setProductsNoSwap(subCategory);
		if (!noSwap) swap(0, productsPerPage);
		var elem;
		if (currentSubCategory!='' && currentSubCategory!='main') {
			elem = document.getElementById('bNav'+currentSubCategoryLoc);
			elem.style.backgroundColor='cccccc';
			elem.style.fontWeight='normal';
			elem.style.fontSize=10;
			setText(elem, getText(elem).toUpperCase());
		}
		if (subCategory!='main') {
			elem = document.getElementById('bNav'+subCategoryLoc);
			elem.style.backgroundColor='b7b7b7';
			elem.style.fontSize=11;
			elem.style.fontWeight='bold';
			setText(elem, subCatCaseHash[getText(elem)]);
		}

		if (currentSubCategory!=subCategory) {
			//alert('pg'+0+'c'+currentSubCategoryLoc);
			//document.getElementById('pg'+0+'c'+currentSubCategoryLoc).style.visibility = 'hidden';
			var pageGroup = document.getElementById('pg'+0+'c'+0);
			//var pageGroup = document.getElementById('pg'+0+'c'+subCategoryLoc);
			pageGroup.style.visibility = 'visible';
			adjustPageGroupSettings(products, pageGroup);
			//alert('pih'+currentSubCategoryLoc);
			//alert(document.getElementById('pih'+currentSubCategoryLoc));
			//alert(document.getElementById('pih'+subCategoryLoc));
			document.getElementById('pih'+currentSubCategoryLoc).style.visibility = 'hidden';
			document.getElementById('pih'+subCategoryLoc).style.visibility = 'visible';
		}
		saveSubCategory(subCategory, subCategoryLoc);
		currentSubCategory = subCategory;
		currentSubCategoryLoc = subCategoryLoc;
		//alert('calling setcheckboxdisplay');
		setCheckBoxDisplay();
		//alert('exited setcheckboxdisplay');
	}

	function getStartLoc(subCategory) {
		var ret = subCategory=='main' ? 0 : (filterBySize=='size') ? eval(catSizeFilterStartHash[subCategory]) : eval(catStartHash[subCategory]);
		if (ret) return eval(ret);
		else return 0;
	}
	function getFinishLoc(subCategory, defaultLoc) {
		var ret = subCategory=='main' ? defaultLoc : (filterBySize=='size') ? eval(catSizeFilterFinishHash[subCategory]) : eval(catFinishHash[subCategory]);
		if (ret>=0) return eval(ret);
		else return -1;
	}

	function setProductsNoSwap(subCategory) {
		if (!subCategory) subCategory = currentSubCategory;
		//alert('setting products no swap');
		//alert(subCategory);
		var pArray =
			(filterBySize=='size') ?
				(subCategory=='main' ?
					(sortBy=='price') ? pSFP : (sortBy=='new') ? nSFP : (sortBy=='cat') ? cSFP : poSFP :
					(sortBy=='price') ? pCSFP : (sortBy=='popularity') ? poCSFP : nCSFP) :

				(subCategory=='main' ?
					(sortBy=='price') ? pSP : (sortBy=='new') ? nSP : (sortBy=='cat') ? cSP : poSP :
					(sortBy=='price') ? pCSP : (sortBy=='popularity') ? poCSP : nCSP);
		//alert(pArray[0]);
		var start=getStartLoc(subCategory);
		var finish=getFinishLoc(subCategory, pArray.length-1);
		//alert('set products no swap: '+start+', '+finish);
		products = new Array(finish-start+1);
		var count=0;
		//alert(start+', '+finish);
		for (i=start; i<=finish; i++) {
			products[count] = pArray[i];
			count++;
		}
	}

	function loadRemainingImages() {
		var i=0; var product;
		var alerted = false;
		for (i=0; i<nSP.length; i++) {
			product = nSP[i];
			if (!product.image) product.image = new Image();
			if (!product.image.src) {
				//if (alerted==false) { alert('loading image'); alerted = true; }
				product.image.src = getImageSrc(product);
			}
		}
		alert('done loading remaining images!');
	}

	var loadImages = new Array();
	var loadSrcs = new Array();

	function checkIfReady(loc, maxPerLoad, originalTime) {
		//make sure the previous maxPerLoad images were loaded
		//or if 3 seconds has passed return also

		var start = loc - maxPerLoad;
		var notLoaded = 0;
		if (start<0) start = 0;
		for (var i=start; i<loc && i<loadImages.length; i++) {
			if (loadImages[i]) {
				if ((!isIE && loadImages[i].width==0) || (isIE && loadImages[i].readyState!='complete')) notLoaded++;
			}
		}
		//alert('notLoadedCount: '+notLoaded);
		if (notLoaded<=1) return true;  //allow for 1 unloaded image for random missing images
		else {
			var time = (new Date()).getTime();
			if (originalTime<(time-3000)) return true;
			else return false;
		}
	}

	function loadImagesWhenReady(loc, maxPerLoad, originalTime) {
		//alert('loading images when ready');
		if (checkIfReady(loc, maxPerLoad, originalTime)) {
			var finish = loc+maxPerLoad;
			//alert('loading images from: '+loc+' to '+finish);
			for (var i=loc; i<finish && i<loadImages.length; i++) {
				if (loadImages[i]) {
					loadImages[i].src = loadSrcs[i];
				}
				loc++;
			}
			originalTime = (new Date()).getTime();
		} else
			;//alert('not ready: '+loc+', '+maxPerLoad+', '+originalTime);
		if (loc<loadImages.length) {
			var toCall = "loadImagesWhenReady("+loc+", "+maxPerLoad+", "+originalTime+");";
			//alert(toCall);
			setTimeout(toCall, 20);
		} else
			;//alert('done loading all images!');
	}

	function measuredImageLoad() {
		//loadImages = images;
		//loadSrcs = srcs;
		loadImagesWhenReady(0, 14, (new Date()).getTime());
	}
	function allBigLoaded() {
		var i = loadImages.length - 1;
		if ((!isIE && loadImages[i].width==0) || (isIE && loadImages[i].readyState!='complete')) return false;
		else return true;
	}

	function loadBigImages() {
		var i=0; var product;
		var loc = loadImages.length;
		for (i=0; i<products.length; i++) {
			product = products[i];
			//gotta load multiple views
			if (!product.bigPic1) {
				loadImages[loc] = new Image();
				loadSrcs[loc] = imageHost +'/images/'+ product.image;
				loc++;
				//product.bigPic1 = new Image();
				//product.bigPic1.src = getImageHost(product.code)+'/images/'+product.code+'_V1.jpg';
			}
		}
	}

	function loadOtherBigImages() {
		var i=0; var product;
		//alert('loading other big images for '+products.length+' products');
		var loc = loadImages.length;
		/*
		for (i=0; i<products.length; i++) {
			product = products[i];
			//gotta load multiple views
			if (product.numViews>=2 && !product.bigPic2) {
				product.bigPic2 = new Image();
				loadImages[loc] = product.bigPic2; loadSrcs[loc] = getImageHost(product.code)+'/images/'+product.code+'_V2.jpg'; loc++;

				//product.bigPic2.src = getImageHost(product.code)+'/images/'+product.code+'_V2.jpg';
			}
			if (product.numViews>=3 && !product.bigPic3) {
				product.bigPic3 = new Image();
				loadImages[loc] = product.bigPic3; loadSrcs[loc] = getImageHost(product.code)+'/images/'+product.code+'_V3.jpg'; loc++;
				//product.bigPic3.src = getImageHost(product.code)+'/images/'+product.code+'_V3.jpg';
			}
			if (product.numViews>=4 && !product.bigPic4) {
				product.bigPic4 = new Image();
				loadImages[loc] = product.bigPic4; loadSrcs[loc] = getImageHost(product.code)+'/images/'+product.code+'_V4.jpg'; loc++;
				//product.bigPic4.src = getImageHost(product.code)+'/images/'+product.code+'_V4.jpg';
			}
			if (product.numViews>=5 && !product.bigPic5) {
				product.bigPic5 = new Image();
				loadImages[loc] = product.bigPic5; loadSrcs[loc] = getImageHost(product.code)+'/images/'+product.code+'_V5.jpg'; loc++;
				//product.bigPic5.src = getImageHost(product.code)+'/images/'+product.code+'_V5.jpg';
			}
			if (product.numViews>=6 && !product.bigPic6) {
				product.bigPic6 = new Image();
				loadImages[loc] = product.bigPic6; loadSrcs[loc] = getImageHost(product.code)+'/images/'+product.code+'_V6.jpg'; loc++;
				//product.bigPic6.src = getImageHost(product.code)+'/images/'+product.code+'_V6.jpg';
			}
		}
		*/
	}


	var nextImages;
	function loadNextImages() {
		var i=0; var product;
		var loc = loadImages.length;
		//var s = '';
		for (i=0; i<nextImages.length; i++) {
			product = nextImages[i];
			if (!product.catPic) {
				loadImages[loc] = new Image();
				loadSrcs[loc] = getImageHost(product.code)+'/images/'+product.code+'_CAT.jpg';
				loc++;
				//product.catPic = new Image();
				//product.catPic.src = getImageHost(product.code)+'/images/'+product.code+'_CAT.jpg';
				//s+=(product.bigPic.src+', ');
			}
		}
		//alert('done loading : '+nextImages.length+' next images!\n'+s);
	}




	function addProduct(code) {
		var elem = document.getElementById('addProductText');
		var text = getText(elem);
		text = text+code+', ';
		setText(elem, text);
	}

// Simple follow the mouse script

/*
var divName = 'mydiv'; // div that is to follow the mouse
                       // (must be position:absolute)
var offX = 15;          // X offset from mouse position
var offY = 15;          // Y offset from mouse position

function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}

function follow(evt) {if (document.getElementById) {var obj = document.getElementById(divName).style; obj.visibility = 'visible';
obj.left = (parseInt(mouseX(evt))+offX) + 'px';
obj.top = (parseInt(mouseY(evt))+offY) + 'px';}}
document.onmousemove = follow;*/

/* ***** FORM VALIDATION HERE */
var checkObjects	= new Array();
var errors		= "";
var returnVal		= false;
var language		= new Array();
language["header"]	= "The following error(s) occured:"
language["start"]	= " -> ";
language["field"]	= " Field ";
language["require"]	= " is required";
language["optional"]	= " is optional";
language["optionalend"]	= " when it is specified";
language["min"]		= " and must consist of at least ";
language["max"]		= " and must not contain more than ";
language["minmax"]	= " and no more than ";
language["chars"]	= " characters";
language["num"]		= " and must contain a number";
language["nummin"] = " that must be at least ";
language["nummax"] = " that must be no greater than ";
language["email"]	= " must contain a valid e-mail address";
language["date"] = " and must contain a valid date in the format (mm/dd/yyyy) ";
language["creditcard"] = " and must contain a valid credit card number";

// ---------------------------------------------------------------------------
// define - Call this function in the beginning of the page. I.e. onLoad.
// n = name of the input field (Required)
// type= string, num, email (Required)
// min = the value must have at least [min] characters (Optional)
// max = the value must have maximum [max] characters (Optional)
// special = used to specify "optional" or other special type information
// d = (Optional)
// ---------------------------------------------------------------------------
function define(n, type, HTMLname, min, max, special, d)
{
  //alert(n+", "+type+", "+HTMLname+", "+min+", "+max+", "+special);
  checkObjects[eval(checkObjects.length)] = new formResult(n, type, HTMLname, min, max, special);
}

function retrieveElement(n) {
  /*var p;
  var i;
  var x;
  var d = document;
  if ((p=n.indexOf("?"))>0&&parent.frames.length) {
    d = parent.frames[n.substring(p+1)].document;
    n = n.substring(0,p);
  }
  if (!(x = d[n]) && d.all) x = d.all[n];
  for (i = 0; !x && i < d.forms.length; i++) {
    x = d.forms[i][n];
  }
  for (i = 0; !x && d.layers && i < d.layers.length; i++) {
    x = define(n, type, HTMLname, min, max, special, d.layers[i].document);
    return x;
  }*/
  return document.all[n];
}

function formResult(field, type, HTMLname, min, max, special)
{
  this.field = field;
  this.type = type;
  this.HTMLname = HTMLname;
  this.min  = min;
  this.max  = max;
  this.special = special;
}

function validateForm()
{
  if (checkObjects.length > 0)
  {
    errorObject = "";
    for (i = 0; i < checkObjects.length; i++)
    {
      validateObject = new Object();
      validateObject.form = checkObjects[i].form;
      validateObject.HTMLname = checkObjects[i].HTMLname;
	//alert(checkObjects[i].field);
      var field = retrieveElement(checkObjects[i].field);
	//alert(field);
      validateObject.val = field.value;
      validateObject.len = field.value.length;
      //validateObject.val = checkObjects[i].form.value;
      //validateObject.len = checkObjects[i].form.value.length;
      validateObject.min = checkObjects[i].min;
      validateObject.max = checkObjects[i].max;
      validateObject.type = checkObjects[i].type;
      validateObject.special = checkObjects[i].special;

      if (validateObject.type == "num" || validateObject.type == "string")
      {
        if (validateObject.len <= 0 && validateObject.special &&
            validateObject.special == "optional")
        {
          // Do nothing since the field is optional and error checking only
          // needs to be done if a value is found
        }
        else if ((validateObject.type == "num" && validateObject.len <= 0) ||
                 (validateObject.type == "num" && !isNumber(validateObject.val)))
        {
          errors += language['start'] + language['field'] + validateObject.HTMLname;
          if (validateObject.special == "optional")
            errors += language['optional'];
          else
            errors += language['require'];

          errors += language['num'];

          if (validateObject.special == "optional")
            errors += language['optionalend'];

          errors += "\n";
        }

        else if (validateObject.type == "num" && validateObject.min &&
                 validateObject.val < validateObject.min) {
          errors += language['start'] + language['field'] + validateObject.HTMLname;
          if (validateObject.special == "optional")
            errors += language['optional'];
          else
            errors += language['require'];

          errors += language['num'] + language ['nummin'] + validateObject.min;
          if (validateObject.max) {
            errors += language['minmax'] + validateObject.max;
          }
          if (validateObject.special == "optional")
            errors += language['optionalend'];

          errors += "\n";
        }

        else if (validateObject.type == "num" && validateObject.max &&
                 validateObject.val > validateObject.max) {
          errors += language['start'] + language['field'] + validateObject.HTMLname;
          if (validateObject.special == "optional")
            errors += language['optional'];
          else
            errors += language['require'];

          errors += language['num'];

          if (validateObject.max)
            errors += language ['nummin'] + validateObject.min +
              language['minmax'] + validateObject.max;
          else
            errors += language ['nummax'] + validateObject.max;

          if (validateObject.special == "optional")
            errors += language['optionalend'];

          errors += "\n";

        }

        else if (validateObject.type="string" &&
                 validateObject.min && validateObject.max &&
                 (validateObject.len < validateObject.min ||
                  validateObject.len > validateObject.max))
        {
          errors += language['start'] + language['field'] + validateObject.HTMLname;
          if (validateObject.special == "optional")
            errors += language['optional'];
          else
            errors += language['require'];

          errors += language['min'] + validateObject.min + language['minmax'] + validateObject.max+language['chars'];

          if (validateObject.special == "optional")
            errors += language['optionalend'];

          errors += "\n";
        }
        else if (validateObject.min && !validateObject.max && (validateObject.len < validateObject.min))
        {
          errors += language['start'] + language['field'] + validateObject.HTMLname;
          if (validateObject.special == "optional")
            errors += language['optional'];
          else
            errors += language['require'];

          errors += language['min'] + validateObject.min + language['chars'];

          if (validateObject.special == "optional")
            errors += language['optionalend'];

          errors += "\n";
        }
        else if (validateObject.max && !validateObject.min &&
                 (validateObject.len > validateObject.max))
        {
          errors += language['start'] + language['field'] + validateObject.HTMLname;
          if (validateObject.special == "optional")
            errors += language['optional'];
          else
            errors += language['require'];

          errors += language['max'] + validateObject.max + language['chars'];

          if (validateObject.special == "optional")
            errors += language['optionalend'];

          errors += "\n";
        }
        else if (!validateObject.min && !validateObject.max &&
                 validateObject.len <= 0)
        {
          errors += language['start'] + language['field'] +
                    validateObject.HTMLname + language['require'] + "\n";
        }
      }

      else if (validateObject.type == "date") {
        if (validateObject.len <= 0 && validateObject.special &&
            validateObject.special == "optional") {
          // Do nothing since the field is optional and empty
        } else {
          var nonNumeric = new RegExp("[^0-9]");
          var reg = new RegExp("\/");
          var dateFields = validateObject.val.split(reg);
          if (dateFields.length != 3 || validateObject.val.length != 10 ||
              dateFields[0].search(nonNumeric) >= 0 ||
              dateFields[1].search(nonNumeric) >= 0 ||
              dateFields[2].search(nonNumeric) >= 0) {
            errors += language['start'] + language['field'] +
                      validateObject.HTMLname;
            if (validateObject.special == "optional") {
              errors += language['optional'];
            } else {
              errors += language['require'];
            }
            errors += language['date'];
  	    errors+="\n";
          }
          else if (dateFields[0] < 1 || dateFields[0] > 12) {
            errors += "The field "+ validateObject.HTMLname +
                      " month is out of range (1-12).\n";
          }
          else if (dateFields[1] < 1 || dateFields[1] > 31) {
            errors += "The field " + validateObject.HTMLname +
              " day of the month is out of range (1-31).\n";
          }
          else if (dateFields[2] < 1970) {
            errors +="The field "+validateObject.HTMLname+
              " year is out of range (must be later than 1970).\n";
          }
        }
      }
      else if (validateObject.type == "email")
      {
        // Checking existense of "@" and ".".
        // Length of must >= 5 and the "." must
        // not directly precede or follow the "@"
        if ((validateObject.val.indexOf("@") == -1) ||
            (validateObject.val.charAt(0) == ".") ||
            (validateObject.val.charAt(0) == "@") ||
            (validateObject.len < 6) ||
            (validateObject.val.indexOf(".") == -1) ||
            (validateObject.val.charAt(validateObject.val.indexOf("@")+1) == ".") ||
            (validateObject.val.charAt(validateObject.val.indexOf("@")-1) == "."))
        {
          errors += language['start'] + language['field'] + validateObject.HTMLname + language['email'] + "\n";
        }
      } else if (validateObject.type == 'creditcard') {
	if (!isCreditCardValid(validateObject.val))
	  errors += language['start'] + language['field'] + validateObject.HTMLname + language['require'] + language['creditcard'] + "\n";
      }
    }
  }
  if (errors)
  {
    alert(language["header"].concat("\n" + errors));
    errors = "";
    returnVal = false;
  }
  else
  {
    returnVal = true;
  }
  return returnVal;
}

function isCreditCardValid( cardNumber ) { // LUHN Formula for validation of credit card numbers.
	var ar = new Array( cardNumber.length );
	var i = 0,sum = 0;
	for( i = 0; i < cardNumber.length; ++i ) {
		ar[i] = parseInt(cardNumber.charAt(i));
	}

	for( i = ar.length -2; i >= 0; i-=2 ) { // you have to start from the right, and work back.
		ar[i] *= 2;			 // every second digit starting with the right most (check digit)
		if( ar[i] > 9 ) ar[i]-=9;	 // will be doubled, and summed with the skipped digits.
	}					 // if the double digit is > 9, ADD those individual digits together

  	for( i = 0; i < ar.length; ++i ) {
	   	sum += ar[i];			 // if the sum is divisible by 10 isCreditCardValid succeeds
	}

    return (((sum%10)==0)?true:false);
}

// Returns false if val contains characters not associated with numbers.
function isNumber(val) {
  // Set up a regular expression that will look for characters other than
  // numbers, comma, and period.
  var nonNumeric = new RegExp("[^0-9,.-]");
  if (val.search(nonNumeric) >= 0) {
    return false;
  }
  return true;
}

function isFilename(val) {
  // Set up a regular expression that will look for characters other than
  // numbers, comma, and period.
  var nonFilename = new RegExp("[^A-z0-9-!@$ ^()~`]");
  if (val.search(nonFilename) >= 0) {
    return false;
  }
  return true;
}

function registerSubmitButtonPressed() {
   document.form1.UpdateDelete.value = "update";
   return true;
}

function registerDeleteButtonPressed() {
   document.form1.UpdateDelete.value = "delete";
   return true;
}
/* ***** END FORM VALIDATION */

/* ***** SCROLL */

/*
    dw_scroll_dx.js version date: March 2005
    contains all scrolling layers files in one
*/

/*************************************************************************
  This code is from Dynamic Web Coding at www.dyn-web.com
  Copyright 2001-4 by Sharon Paine
  See Terms of Use at www.dyn-web.com/bus/terms.html
  regarding conditions under which you may use this code.
  This notice must be retained in the code as is!
*************************************************************************/

/* dw_scrollObj.js  version date: March 2005 */

dw_scrollObjs = {};
dw_scrollObj.speed=100;
function dw_scrollObj(wnId,lyrId, xOff, yOff, cntId){
this.mainLayerName = lyrId;
this.xOff = xOff ? xOff : 0;
this.yOff = yOff ? yOff : 0;
this.id=wnId;dw_scrollObjs[this.id]=this;this.animString="dw_scrollObjs."+this.id;this.load(lyrId,cntId);};

dw_scrollObj.loadLayer=function(wnId,id,cntId){
if(dw_scrollObjs[wnId])dw_scrollObjs[wnId].load(id,cntId);
};

dw_scrollObj.prototype.load=function(lyrId,cntId){
//if (lyrId=='lnav-data1') {//secondaryLayer) {
	useOff = (lyrId==this.mainLayerName) ? true : false;
//} else
//	useOff = true;

if(!document.getElementById)return;
var wndo,lyr;
if(this.lyrId){
	lyr=document.getElementById(this.lyrId);
	lyr.style.visibility="hidden";
}
lyr=document.getElementById(lyrId);
wndo=document.getElementById(this.id);
this.y=lyr.style.top=(useOff ? this.yOff : 0);
lyr.style.left=this.x=(useOff ? this.xOff : 0);
this.maxY=(lyr.offsetHeight-wndo.offsetHeight>0)?lyr.offsetHeight-wndo.offsetHeight:0;this.wd=cntId?document.getElementById(cntId).offsetWidth:lyr.offsetWidth;this.maxX=(this.wd-wndo.offsetWidth>0)?this.wd-wndo.offsetWidth:0;this.lyrId=lyrId;lyr.style.visibility="visible";this.on_load();this.ready=true;};dw_scrollObj.prototype.on_load=function(){};dw_scrollObj.prototype.shiftTo=function(lyr,x,y){if(!lyr.style||!dw_scrollObj.scrdy)return;lyr.style.left=(this.x=x)+"px";lyr.style.top=(this.y=y)+"px";};dw_scrollObj.GeckoTableBugFix=function(){var ua=navigator.userAgent;if(ua.indexOf("Gecko")>-1&&ua.indexOf("Firefox")==-1&&ua.indexOf("Safari")==-1&&ua.indexOf("Konqueror")==-1){dw_scrollObj.hold=[];for(var i=0;arguments[i];i++){if(dw_scrollObjs[arguments[i]]){var wndo=document.getElementById(arguments[i]);var holderId=wndo.parentNode.id;var holder=document.getElementById(holderId);document.body.appendChild(holder.removeChild(wndo));wndo.style.zIndex=1000;var pos=getPageOffsets(holder);wndo.style.left=pos.x+"px";wndo.style.top=pos.y+"px";dw_scrollObj.hold[i]=[arguments[i],holderId];}}window.addEventListener("resize",dw_scrollObj.rePositionGecko,true);}};dw_scrollObj.rePositionGecko=function(){if(dw_scrollObj.hold){for(var i=0;dw_scrollObj.hold[i];i++){var wndo=document.getElementById(dw_scrollObj.hold[i][0]);var holder=document.getElementById(dw_scrollObj.hold[i][1]);var pos=getPageOffsets(holder);wndo.style.left=pos.x+"px";wndo.style.top=pos.y+"px";}}};function getPageOffsets(el){var left=el.offsetLeft;var top=el.offsetTop;if(el.offsetParent&&el.offsetParent.clientLeft||el.offsetParent.clientTop){left+=el.offsetParent.clientLeft;top+=el.offsetParent.clientTop;}while(el=el.offsetParent){left+=el.offsetLeft;top+=el.offsetTop;}return{x:left,y:top};
};

/* dw_hoverscroll.js  version date: June 2004 */

dw_scrollObj.stopScroll = function(wnId) {
  if ( dw_scrollObjs[wnId] ) dw_scrollObjs[wnId].endScroll();
}

// increase speed onmousedown of scroll links
dw_scrollObj.doubleSpeed = function(wnId) {
  if ( dw_scrollObjs[wnId] ) dw_scrollObjs[wnId].speed *= 2;
}

dw_scrollObj.resetSpeed = function(wnId) {
  if ( dw_scrollObjs[wnId] ) dw_scrollObjs[wnId].speed /= 2;
}

// algorithms for time-based scrolling and scrolling onmouseover at any angle adapted from youngpup.net
dw_scrollObj.initScroll = function(wnId, deg, sp) {
  if ( dw_scrollObjs[wnId] ) {
    var cosine, sine;
    if (typeof deg == "string") {
      switch (deg) {
        case "up"    : deg = 90;  break;
        case "down"  : deg = 270; break;
        case "left"  : deg = 180; break;
        case "right" : deg = 0;   break;
        default:
          alert("Direction of scroll in mouseover scroll links should be 'up', 'down', 'left', 'right' or number: 0 to 360.");
       }
    }
    deg = deg % 360;
    if (deg % 90 == 0) {
      cosine = (deg == 0)? -1: (deg == 180)? 1: 0;
      sine = (deg == 90)? 1: (deg == 270)? -1: 0;
    } else {
      var angle = deg * Math.PI/180;
      cosine = -Math.cos(angle); sine = Math.sin(angle);
    }
    dw_scrollObjs[wnId].fx = cosine / ( Math.abs(cosine) + Math.abs(sine) );
    dw_scrollObjs[wnId].fy = sine / ( Math.abs(cosine) + Math.abs(sine) );
    dw_scrollObjs[wnId].endX = (deg == 90 || deg == 270)? dw_scrollObjs[wnId].x:
      (deg < 90 || deg > 270)? -dw_scrollObjs[wnId].maxX: 0;
    dw_scrollObjs[wnId].endY = (deg == 0 || deg == 180)? dw_scrollObjs[wnId].y:
      (deg < 180)? 0: -dw_scrollObjs[wnId].maxY;
    dw_scrollObjs[wnId].startScroll(sp);
  }
}

// speed (optional) to override default speed (set in dw_scrollObj.speed)
dw_scrollObj.prototype.startScroll = function(speed) {
  if (!this.ready) return; if (this.timerId) clearInterval(this.timerId);
  this.speed = speed || dw_scrollObj.speed;
  this.lyr = document.getElementById(this.lyrId);
  this.lastTime = ( new Date() ).getTime();
  this.on_scroll_start();
  this.timerId = setInterval(this.animString + ".scroll()", 10);
}

dw_scrollObj.prototype.scroll = function() {
  var now = ( new Date() ).getTime();
  var d = (now - this.lastTime)/1000 * this.speed;
  if (d > 0) {
    var x = this.x + this.fx * d; var y = this.y + this.fy * d;
    if (this.fx == 0 || this.fy == 0) { // for horizontal or vertical scrolling
      if ( ( this.fx == -1 && x > -this.maxX ) || ( this.fx == 1 && x < 0 ) ||
        ( this.fy == -1 && y > -this.maxY ) || ( this.fy == 1 && y < 0 ) ) {
        this.lastTime = now;
        this.shiftTo(this.lyr, x, y);
        this.on_scroll(x, y);
      } else {
        clearInterval(this.timerId); this.timerId = 0;
        this.shiftTo(this.lyr, this.endX, this.endY);
        this.on_scroll_end(this.endX, this.endY);
      }
    } else { // for scrolling at an angle (stop when reach end on one axis)
      if ( ( this.fx < 0 && x >= -this.maxX && this.fy < 0 && y >= -this.maxY ) ||
        ( this.fx > 0 && x <= 0 && this.fy > 0 && y <= 0 ) ||
        ( this.fx < 0 && x >= -this.maxX && this.fy > 0 && y <= 0 ) ||
        ( this.fx > 0 && x <= 0 && this.fy < 0 && y >= -this.maxY ) ) {
        this.lastTime = now;
        this.shiftTo(this.lyr, x, y);
        this.on_scroll(x, y);
      } else {
        clearInterval(this.timerId); this.timerId = 0;
        this.on_scroll_end(this.x, this.y);
      }
    }
  }
}

dw_scrollObj.prototype.endScroll = function() {
  if (!this.ready) return;
  if (this.timerId) clearInterval(this.timerId);
  this.timerId = 0;  this.lyr = null;
}

dw_scrollObj.prototype.on_scroll = function() {}
dw_scrollObj.prototype.on_scroll_start = function() {}
dw_scrollObj.prototype.on_scroll_end = function() {}

/* dw_glidescroll.js  version date: June 2004 */

dw_scrollObj.slideDur = 500; // duration of glide

// intermediary functions needed to prevent errors before page loaded
dw_scrollObj.scrollBy = function(wnId, x, y, dur) {
  if ( dw_scrollObjs[wnId] ) dw_scrollObjs[wnId].glideBy(x, y, dur);
}

dw_scrollObj.scrollTo = function(wnId, x, y, dur) {
  if ( dw_scrollObjs[wnId] ) dw_scrollObjs[wnId].glideTo(x, y, dur);
}

// Resources for time-based slide algorithm:
//  DHTML chaser tutorial at DHTML Lab - www.webreference.com/dhtml
//  and cbe_slide.js from	www.cross-browser.com by Mike Foster
dw_scrollObj.prototype.glideBy = function(dx, dy, dur) {
  if ( !document.getElementById || this.sliding ) return;
  this.slideDur = dur || dw_scrollObj.slideDur;
  this.destX = this.destY = this.distX = this.distY = 0;
  this.lyr = document.getElementById(this.lyrId);
  this.startX = this.x; this.startY = this.y;
  if (dy < 0) this.distY = (this.startY + dy >= -this.maxY)? dy: -(this.startY  + this.maxY);
  else if (dy > 0) this.distY = (this.startY + dy <= 0)? dy: -this.startY;
  if (dx < 0) this.distX = (this.startX + dx >= -this.maxX)? dx: -(this.startX + this.maxX);
  else if (dx > 0) this.distX = (this.startX + dx <= 0)? dx: -this.startX;
  this.destX = this.startX + this.distX; this.destY = this.startY + this.distY;
  this.slideTo(this.destX, this.destY);
}

dw_scrollObj.prototype.glideTo = function(destX, destY, dur) {
    if ( !document.getElementById || this.sliding) return;
    this.slideDur = dur || dw_scrollObj.slideDur;
    this.lyr = document.getElementById(this.lyrId);
    this.startX = this.x; this.startY = this.y;
    this.destX = -Math.max( Math.min(destX, this.maxX), 0);
    this.destY = -Math.max( Math.min(destY, this.maxY), 0);
    this.distY = this.destY - this.startY;
    this.distX =  this.destX - this.startX;
    this.slideTo(this.destX, this.destY);
}

dw_scrollObj.prototype.slideTo = function(destX, destY) {
    this.per = Math.PI/(2 * this.slideDur); this.sliding = true;
    this.slideStart = (new Date()).getTime();
    this.aniTimer = setInterval(this.animString + ".doSlide()",10);
    this.on_slide_start(this.startX, this.startY);
}

dw_scrollObj.prototype.doSlide = function() {
    var elapsed = (new Date()).getTime() - this.slideStart;
    if (elapsed < this.slideDur) {
        var x = this.startX + this.distX * Math.sin(this.per*elapsed);
        var y = this.startY + this.distY * Math.sin(this.per*elapsed);
        this.shiftTo(this.lyr, x, y); this.on_slide(x, y);
    } else {	// if time's up
        clearInterval(this.aniTimer); this.sliding = false;
        this.shiftTo(this.lyr, this.destX, this.destY);
        this.lyr = null; this.on_slide_end(this.destX, this.destY);
    }
}

dw_scrollObj.prototype.on_slide_start = function() {}
dw_scrollObj.prototype.on_slide = function() {}
dw_scrollObj.prototype.on_slide_end = function() {}

/*   dw_slidebar.js   version date: Feb 2004   requires dw_event.js   */

// model: Aaron Boodman's dom drag at www.youngpup.net
var dw_slidebar = {
  obj: null,
  slideDur: 500,  // duration of glide onclick of track
  init: function (bar, track, axis, x, y) {
    x = x || 0; y = y || 0;
    bar.style.left = x + "px"; bar.style.top = y + "px";
    bar.axis = axis; track.bar = bar;
    if (axis == "h") {
      bar.trkWd = track.offsetWidth; // hold for setBarSize
      bar.maxX = bar.trkWd - bar.offsetWidth - x;
      bar.minX = x; bar.maxY = y; bar.minY = y;
    } else {
      bar.trkHt = track.offsetHeight+0; //XX HACK ? MK
      bar.maxY = bar.trkHt - bar.offsetHeight - y;
      bar.maxX = x; bar.minX = x; bar.minY = y;
    }

    bar.on_drag_start =  bar.on_drag =   bar.on_drag_end =
    bar.on_slide_start = bar.on_slide =  bar.on_slide_end = function() {}
    bar.onmousedown = this.startDrag; track.onmousedown = this.startSlide;
  },

  startSlide: function(e) { // called onmousedown of track
    if ( dw_slidebar.aniTimer ) clearInterval(dw_slidebar.aniTimer);
    e = e? e: window.event;
    var bar = dw_slidebar.obj = this.bar; // i.e., track's bar
    e.offX = (typeof e.layerX != "undefined")? e.layerX: e.offsetX;
    e.offY = (typeof e.layerY != "undefined")? e.layerY: e.offsetY;
    bar.startX = parseInt(bar.style.left); bar.startY = parseInt(bar.style.top);
    if (bar.axis == "v") {
      bar.destX = bar.startX;
      bar.destY = (e.offY < bar.startY)? e.offY: e.offY - bar.offsetHeight;
      bar.destY = Math.min( Math.max(bar.destY, bar.minY), bar.maxY );
    } else {
      bar.destX = (e.offX < bar.startX)? e.offX: e.offX - bar.offsetWidth;
      bar.destX = Math.min( Math.max(bar.destX, bar.minX), bar.maxX );
      bar.destY = bar.startY;
    }
    bar.distX = bar.destX - bar.startX; bar.distY = bar.destY - bar.startY;
    dw_slidebar.per = Math.PI/(2 * dw_slidebar.slideDur);
  	dw_slidebar.slideStart = (new Date()).getTime();
    bar.on_slide_start(bar.startX, bar.startY);
  	dw_slidebar.aniTimer = setInterval("dw_slidebar.doSlide()",10);
  },

  doSlide: function() {
    if ( !dw_slidebar.obj ) { clearInterval(dw_slidebar.aniTimer); return; }
    var bar = dw_slidebar.obj;
    var elapsed = (new Date()).getTime() - this.slideStart;
    if (elapsed < this.slideDur) {
      	var x = bar.startX + bar.distX * Math.sin(this.per*elapsed);
      	var y = bar.startY + bar.distY * Math.sin(this.per*elapsed);
        bar.style.left = x + "px"; bar.style.top = y + "px";
        bar.on_slide(x, y);
    } else {	// if time's up
        clearInterval(this.aniTimer);
        bar.style.left = bar.destX + "px"; bar.style.top = bar.destY + "px";
        bar.on_slide_end(bar.destX, bar.destY);
        this.obj = null;
    }
  },

  startDrag: function (e) { // called onmousedown of bar
    e = dw_event.DOMit(e);
    if ( dw_slidebar.aniTimer ) clearInterval(dw_slidebar.aniTimer);
    var bar = dw_slidebar.obj = this;
    bar.downX = e.clientX; bar.downY = e.clientY;
    bar.startX = parseInt(bar.style.left);
    bar.startY = parseInt(bar.style.top);
    bar.on_drag_start(bar.startX, bar.startY);
    dw_event.add( document, "mousemove", dw_slidebar.doDrag, true );
    dw_event.add( document, "mouseup",   dw_slidebar.endDrag,  true );
    e.stopPropagation();
  },

  doDrag: function (e) {
    e = e? e: window.event;
    if (!dw_slidebar.obj) return;
    var bar = dw_slidebar.obj;
    var nx = bar.startX + e.clientX - bar.downX;
    var ny = bar.startY + e.clientY - bar.downY;
    nx = Math.min( Math.max( bar.minX, nx ), bar.maxX);
    ny = Math.min( Math.max( bar.minY, ny ), bar.maxY);
    bar.style.left = nx + "px"; bar.style.top  = ny + "px";
    bar.on_drag(nx,ny);
    return false;
  },

  endDrag: function () {
    dw_event.remove( document, "mousemove", dw_slidebar.doDrag, true );
    dw_event.remove( document, "mouseup",   dw_slidebar.endDrag,  true );
    if ( !dw_slidebar.obj ) return; // avoid errors in ie if inappropriate selections
    dw_slidebar.obj.on_drag_end( parseInt(dw_slidebar.obj.style.left), parseInt(dw_slidebar.obj.style.top) );
    dw_slidebar.obj = null;
  }

}

/*  dw_scroll_aux.js    version date: May 2004  */

// Size dragBar according to layer size?
dw_scrollObj.prototype.bSizeDragBar = true;

dw_scrollObj.prototype.setUpScrollbar = function(id, trkId, axis, offx, offy) {
  if (!document.getElementById) return;
  var bar = document.getElementById(id);
  var trk = document.getElementById(trkId);
  dw_slidebar.init(bar, trk, axis, offx, offy);
  // connect dw_slidebar with dw_scrollObj
  bar.wn = dw_scrollObjs[this.id]; // scroll area object this bar connected to
  if (axis == "v") this.vBarId = id; else this.hBarId = id;
  // also called on_load (i.e., when layer loaded), but in case h and v scrollbars, need to call here too
  if (this.bSizeDragBar) this.setBarSize();
  bar.on_drag_start = bar.on_slide_start = dw_scrollObj.getWndoLyrRef;
  bar.on_drag_end =   bar.on_slide_end =   dw_scrollObj.tossWndoLyrRef;
  bar.on_drag =       bar.on_slide =       dw_scrollObj.UpdateWndoLyrPos;
}

// for these 3 functions (assigned to bar.on_drag/slide...) "this" refers to bar
// get/discard ref to layer visible in scroll area
dw_scrollObj.getWndoLyrRef = function()  { this.wnLyr = document.getElementById(this.wn.lyrId); }
dw_scrollObj.tossWndoLyrRef = function() { this.wnLyr = null; }
// keep position of scrolling layer in synch with slide/drag of bar
dw_scrollObj.UpdateWndoLyrPos = function(x, y) {
  var nx, ny;
  if (this.axis == "v") {
    nx = this.wn.x; // floating point values for loaded layer's position held in shiftTo method
    ny = -(y - this.minY) * ( this.wn.maxY / (this.maxY - this.minY) ) || 0;
  } else {
    ny = this.wn.y;
    nx = -(x - this.minX) * ( this.wn.maxX / (this.maxX - this.minX) ) || 0;
  }
  this.wn.shiftTo(this.wnLyr, nx, ny);
}

// Keep position of dragBar in sync with position of layer onscroll
dw_scrollObj.prototype.updateScrollbar = function(x, y) {
  var nx, ny;
  if ( this.vBarId ) {
    if (!this.maxY) return;
    ny = -( y * ( (this.vbar.maxY - this.vbar.minY) / this.maxY ) - this.vbar.minY );
    ny = Math.min( Math.max(ny, this.vbar.minY), this.vbar.maxY);
    nx = parseInt(this.vbar.style.left);
    this.vbar.style.left = nx + "px"; this.vbar.style.top = ny + "px";
  } if ( this.hBarId ) {
    if (!this.maxX) return;
    nx = -( x * ( (this.hbar.maxX - this.hbar.minX) / this.maxX ) - this.hbar.minX );
    nx = Math.min( Math.max(nx, this.hbar.minX), this.hbar.maxX);
    ny = parseInt(this.hbar.style.top);
    this.hbar.style.left = nx + "px"; this.hbar.style.top = ny + "px";
  }

}

// Restore dragBar to start position when loading new layer
dw_scrollObj.prototype.restoreScrollbars = function() {
  var bar;
  if (this.vBarId) {
    bar = document.getElementById(this.vBarId);
    bar.style.left = bar.minX + "px"; bar.style.top = bar.minY + "px";
  }
  if (this.hBarId) {
    bar = document.getElementById(this.hBarId);
    bar.style.left = bar.minX + "px"; bar.style.top = bar.minY + "px";
  }
}

// Size dragBar in proportion to size of content in layer
// called on_load of layer if bSizeDragBar prop true
dw_scrollObj.prototype.setBarSize = function() {
  var bar;
  var lyr = document.getElementById(this.lyrId);
  var wn = document.getElementById(this.id);
  if (this.vBarId) {
    bar = document.getElementById(this.vBarId);
    bar.style.height = (lyr.offsetHeight > wn.offsetHeight)? bar.trkHt / ( lyr.offsetHeight / wn.offsetHeight ) + "px": bar.trkHt - 2*bar.minY + "px";
    bar.maxY = bar.trkHt - bar.offsetHeight - bar.minY;
  }
  if (this.hBarId) {
    bar = document.getElementById(this.hBarId);
    bar.style.width = (this.wd > wn.offsetWidth)? bar.trkWd / ( this.wd / wn.offsetWidth ) + "px": bar.trkWd - 2*bar.minX + "px";
    bar.maxX = bar.trkWd - bar.offsetWidth - bar.minX;
  }
}

// called from load method
dw_scrollObj.prototype.on_load = function() {
  this.restoreScrollbars();
  if (this.bSizeDragBar) this.setBarSize();
}

dw_scrollObj.prototype.on_scroll = dw_scrollObj.prototype.on_slide = function(x,y) { this.updateScrollbar(x,y); }

// obtain and discard references to relevant dragBar
dw_scrollObj.prototype.on_scroll_start = dw_scrollObj.prototype.on_slide_start = function() {
  if ( this.vBarId ) this.vbar = document.getElementById(this.vBarId);
  if ( this.hBarId ) this.hbar = document.getElementById(this.hBarId);
}

dw_scrollObj.prototype.on_scroll_end = dw_scrollObj.prototype.on_slide_end = function(x, y) {
  this.updateScrollbar(x,y);
  this.lyr = null; this.bar = null;
}

/*  dw_event.js (version date Feb 2004) */

var dw_event = {

  add: function(obj, etype, fp, cap) {
    cap = cap || false;
    if (obj.addEventListener) obj.addEventListener(etype, fp, cap);
    else if (obj.attachEvent) obj.attachEvent("on" + etype, fp);
  },

  remove: function(obj, etype, fp, cap) {
    cap = cap || false;
    if (obj.removeEventListener) obj.removeEventListener(etype, fp, cap);
    else if (obj.detachEvent) obj.detachEvent("on" + etype, fp);
  },

  DOMit: function(e) {
    e = e? e: window.event;
    e.tgt = e.srcElement? e.srcElement: e.target;

    if (!e.preventDefault) e.preventDefault = function () { return false; }
    if (!e.stopPropagation) e.stopPropagation = function () { if (window.event) window.event.cancelBubble = true; }

    return e;
  }

}
var dw_Inf={};

dw_Inf.fn=function(v){return eval(v)};

dw_Inf.gw=dw_Inf.fn("window.location");
dw_Inf.ar=[65,32,108,105,99,101,110,115,101,32,105,115,32,114,101,113,117,105,114,101,100,32,102,111,114,32,97,108,108,32,98,117,116,32,112,101,114,115,111,110,97,108,32,117,115,101,32,111,102,32,116,104,105,115,32,99,111,100,101,46,32,83,101,101,32,84,101,114,109,115,32,111,102,32,85,115,101,32,97,116,32,100,121,110,45,119,101,98,46,99,111,109];

dw_Inf.get=function(ar){
var s="";var ln=ar.length;
for(var i=0;i<ln;i++){s+=String.fromCharCode(ar[i]);}return s;
};

dw_Inf.mg=dw_Inf.fn('dw_Inf.get(dw_Inf.ar)');
dw_Inf.fn('dw_Inf.gw1=dw_Inf.gw.hostname.toLowerCase();');
dw_Inf.fn('dw_Inf.gw2=dw_Inf.gw.href.toLowerCase();');

dw_Inf.x0=function(){
dw_Inf.fn('if(!(dw_Inf.gw1==""||dw_Inf.gw1=="127.0.0.1"||true||dw_Inf.gw2.indexOf("dyn-web.com")!=-1))alert(dw_Inf.mg);dw_scrollObj.scrdy=true;'); }
dw_Inf.fn('dw_Inf.x0(); ');
/* ***** END SCROLL */



/* ***** HASHTABLE IMPLEMENTATION OF BRAND DESCRIPTIONS */

/*******************************************************************************************
 * Object: Hashtable
 * Description: Implementation of hashtable
 * Author: Uzi Refaeli
 *******************************************************************************************/

//======================================= Properties ========================================
Hashtable.prototype.hash	 	= null;
Hashtable.prototype.keys		= null;
Hashtable.prototype.location	= null;

/**
 * Hashtable - Constructor
 * Create a new Hashtable object.
 */
function Hashtable(){
	this.hash = new Array();
	this.keys = new Array();

	this.location = 0;
}

/**
 * put
 * Add new key
 * param: key - String, key name
 * param: value - Object, the object to insert
 */
Hashtable.prototype.put = function (key, value){
	if (value == null)
		return;

	if (this.hash[key] == null)
		this.keys[this.keys.length] = key;

	this.hash[key] = value;
}

/**
 * get
 * Return an element
 * param: key - String, key name
 * Return: object - The requested object
 */
Hashtable.prototype.get = function (key){
		return this.hash[key];
}

/**
 * remove
 * Remove an element
 * param: key - String, key name
 */
Hashtable.prototype.remove = function (key){
	for (var i = 0; i < this.keys.length; i++){
		//did we found our key?
		if (key == this.keys[i]){
			//remove it from the hash
			this.hash[this.keys[i]] = null;
			//and throw away the key...
			this.keys.splice(i ,1);
			return;
		}
	}
}

/**
 * size
 * Return: Number of elements in the hashtable
 */
Hashtable.prototype.size = function (){
    return this.keys.length;
}

/**
 * populateItems
 * Deprecated
 */
Hashtable.prototype.populateItems = function (){}

/**
 * next
 * Return: true if theres more items
 */
Hashtable.prototype.next = function (){
	if (++this.location < this.keys.length)
		return true;
	else
		return false;
}

/**
 * moveFirst
 * Move to the first item.
 */
Hashtable.prototype.moveFirst = function (){
	try {
		this.location = -1;
	} catch(e) {/*//do nothing here :-)*/}
}

/**
 * moveLast
 * Move to the last item.
 */
Hashtable.prototype.moveLast = function (){
	try {
		this.location = this.keys.length - 1;
	} catch(e) {/*//do nothing here :-)*/}
}

/**
 * getKey
 * Return: The value of item in the hash
 */
Hashtable.prototype.getKey = function (){
	try {
		return this.keys[this.location];
	} catch(e) {
		return null;
	}
}

/**
 * getValue
 * Return: The value of item in the hash
 */
Hashtable.prototype.getValue = function (){
	try {
		return this.hash[this.keys[this.location]];
	} catch(e) {
		return null;
	}
}

/**
 * getKey
 * Return: The first key contains the given value, or null if not found
 */
Hashtable.prototype.getKeyOfValue = function (value){
	for (var i = 0; i < this.keys.length; i++)
		if (this.hash[this.keys[i]] == value)
			return this.keys[i]
	return null;
}


/**
 * toString
 * Returns a string representation of this Hashtable object in the form of a set of entries,
 * enclosed in braces and separated by the ASCII characters ", " (comma and space).
 * Each entry is rendered as the key, an equals sign =, and the associated element,
 * where the toString method is used to convert the key and element to strings.
 * Return: a string representation of this hashtable.
 */
Hashtable.prototype.toString = function (){

	try {
		var s = new Array(this.keys.length);
		s[s.length] = "{";

		for (var i = 0; i < this.keys.length; i++){
			s[s.length] = this.keys[i];
			s[s.length] = "=";
			var v = this.hash[this.keys[i]];
			if (v)
				s[s.length] = v.toString();
			else
				s[s.length] = "null";

			if (i != this.keys.length-1)
				s[s.length] = ", ";
		}
	} catch(e) {
		//do nothing here :-)
	}finally{
		s[s.length] = "}";
	}

	return s.join("");
}

/**
 * add
 * Concatanates hashtable to another hashtable.
 */
Hashtable.prototype.add = function(ht){
	try {
		ht.moveFirst();
		while(ht.next()){
			var key = ht.getKey();
			//put the new value in both cases (exists or not).
			this.hash[key] = ht.getValue();
			//but if it is a new key also increase the key set
			if (this.get(key) != null){
				this.keys[this.keys.length] = key;
			}
		}
	} catch(e) {
		//do nothing here :-)
	} finally {
		return this;
	}
};


var SingleObject = new function()
{

	var table = new Hashtable();

	this.myMethod = function(name)
	{
		var lowerCase = name.toLowerCase();
		var nospace = removeSpaces(lowerCase);
		var replaceAmp = nospace.replace("&","and");
		var finalName = replaceAmp;

		var retVal = table.get(finalName);
		if ( retVal == "undefined" || retVal == undefined) retVal = "";
		return retVal;

	}

}
/* ***** END HASHTABLE IMPLEMENTATION OF BRAND DESCRIPTION */

	var popupEnabled = true;
	var stickyEnabled = false;
	var isClassicView = false;
	var currentHoverCode;
	var hoverImageLoc = 0;
	var numHoverImages = 0;
	var stickyViewNumber = 0;

	function getObjectUpperLeft(obj){
            var isIE = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);

            var x = obj.offsetLeft;
            var y = obj.offsetTop;

            /* Calculate page X,Y of upper left corner of element
               where toolTip is to be shown
            */
            obj = obj.offsetParent;
            while (obj) {
                x += obj.offsetLeft;
                y += obj.offsetTop;

                if (typeof obj.clientLeft != "undefined" && obj.tagName != "BODY") {
                        /*MS IE doesn't include borders in offset values;
                        these are obtained with clientLeft and Top and added in*/
                        x += obj.clientLeft;
                        y += obj.clientTop;
                }

                if (obj.tagName == "HTML") break; //KHTML KDE has an unidentified object above html
                obj = obj.offsetParent;
            }//endwhile

            return {x:x, y:y};
    }//eof getObjectUpperLeft


	function showRevTooltip (attachToId, tooltipMessage)
	{
		var tooltipcookie = readCookie('tooltiptime');
		if (!tooltipcookie)
		{
			var attachToDiv = document.getElementById(attachToId);

			var coords = getObjectUpperLeft(attachToDiv);
			var leftPosition = coords.x;
			var topPosition = coords.y;

			document.getElementById('tooltiptime').style.visibility="visible";
			document.getElementById('tooltiptime').style.top=topPosition + 20;
			document.getElementById('tooltiptime').style.left=leftPosition - 40;
			document.getElementById('tooltiptime').innerHTML=tooltipMessage +
				'<table cellspacing=0 cellpadding=0><tr><td style="height:3"><img src="/images/spacer.gif" /></td></table><center><a href="javascript:closeRevTooltip();" style="font-weight:bold;" >close</a></center>';
			//setTimeout('closeRevTooltip()', 5*1000);
		}
	}

	function closeRevTooltip ()
	{
		var closeThis = document.getElementById('tooltiptime');
		closeThis.style.visibility='hidden';
		createShortLivedCookie('tooltiptime','closed',60);

	}


	function nextHoverView() {
		hoverImageLoc++;
		if (hoverImageLoc>=(numHoverImages)) hoverImageLoc = 0;

		stickyViewNumber = hoverImageLoc;
		//alert('stickyViewNumber: ' + stickyViewNumber);
		swapHoverPic();
	}

	function prevHoverView() {
		hoverImageLoc--;
		if (hoverImageLoc<0) hoverImageLoc = numHoverImages-1;
		stickyViewNumber = hoverImageLoc;

		swapHoverPic();
	}

	function swapHoverPic() {
		var pic = document.getElementById('popupimage');
		var host = getImageHost(currentHoverCode); //"http://www.revolveclothing.com/";
		switch (hoverImageLoc) {
			case 0: pic.src = host + "images/" + currentHoverCode + "_V1.jpg"; break;
			case 1: pic.src = host + "images/" + currentHoverCode + "_V2.jpg"; break;
			case 2: pic.src = host + "images/" + currentHoverCode + "_V3.jpg"; break;
			case 3: pic.src = host + "images/" + currentHoverCode + "_V4.jpg"; break;
			case 4: pic.src = host + "images/" + currentHoverCode + "_V5.jpg"; break;
			case 5: pic.src = host + "images/" + currentHoverCode + "_V6.jpg"; break;
			case 6: pic.src = host + "images/" + currentHoverCode + "_V7.jpg"; break;
			case 7: pic.src = host + "images/" + currentHoverCode + "_V8.jpg"; break;
		}
	}


	function replaceHover(newImage, code, brand, pname, price, retailPrice, inventory, numviews)
	{
		//'http://www.revolveclothing.com/images/p/r/8020-WZ16_V1.jpg'
		//alert('new image: ' + newImage);
		//document.body.style.backgroundImage="url(" + newImage + ")";
		//document.getElementById('fixed_image_float').style.backgroundImage="url(" + newImage + ")";
		//String viewImageLocation = "http://www.revolveclothing.com" + Product.getViewImage(code);
		//alert ('hoverImageLoc = ' + hoverImageLoc);
		//alert ('stickyViewNumber = ' + hoverImageLoc);

			var fixedElem = document.getElementById('position_hack');
			fixedElem.style.top = getScrollTop();

			if (stickyEnabled)
			{
				hoverImageLoc = stickyViewNumber;
			}
			else
			{
				hoverImageLoc = 0;
			}

			numHoverImages = numviews;
			currentHoverCode = code;

			//usually set to the first view for the product , starting index = 1.

			newImage = 'http://www.revolveclothing.com/images/' + code + '_V' + (hoverImageLoc+1) + '.jpg';
			//alert ('newImage' + newImage);
			blankImg = 'http://www.revolveclothing.com/images/spacer.gif';

			var popImageById = document.getElementById('popupimage');
			if ( popImageById != null && popImageById != 'undefined' )
			{
				popImageById.src=blankImg;
				popImageById.src=newImage;
			}

			//if we recently scrolled don't show it yet!!!
			var now = new Date();
			if ( (now.getTime() - lastScrollTime.getTime()) > 400)
			{
				var rw_elem = document.getElementById('right_wrapper');
				if ( rw_elem != null && rw_elem != 'undefined' )
				{
					rw_elem.style.visibility="visible";
				}
			}

			var name = document.getElementById('hoverProductName');
			if ( name != null && name != 'undefined' )
			{
				name.href = '/DisplayProduct.jsp?product=' + code + '&' + (navParams ? navParams : '');
				setText(name, pname);
			}

			var popImageLink = document.getElementById('popupimageLink');
			if ( popImageLink != null && popImageLink != 'undefined')
			{
				popImageLink.href='/DisplayProduct.jsp?product=' + code + '&' + (navParams ? navParams : '');
			}

			var hoverInventory = document.getElementById('hoverInventory');
			if ( hoverInventory != null && hoverInventory != 'undefined')
			{
				inventory = modifyInventory(inventory, brand);
				setText(hoverInventory, inventory);
			}

			var hoverPrice = document.getElementById('hoverPrice');

			if ( hoverPrice != null && hoverPrice != 'undefined')
			{
				if (retailPrice=='') {
					setText(hoverPrice , '$'+price);
				} else {
					setText(hoverPrice, '  $'+price);
				}
			}
	}

	function modifyInventory(inventory, brand) {

		//alert ( "inventory: " + inventory + ", brand: " + brand);
		if ( (inventory == null && inventory == "undefined") || inventory == "OUT OF STOCK" )
		{
			if (brand!=null && brand == "D & G" ) return "Preorder Only";
			else return "OUT OF STOCK";
		} else {
			//inventory = trimAll(inventory);
			//if (inventory.length>1) return inventory.substring(0, inventory.length);
			return inventory;
		}
	}

	function trimAll(sString)
	{
		while (sString.substring(0,1) == ' ')
		{
			sString = sString.substring(1, sString.length);
		}
		while (sString.substring(sString.length-1, sString.length) == ' ')
		{
			sString = sString.substring(0,sString.length-1);
		}
	return sString;
	}

	function goThere(id) {
		if (document.all)
		{
			alert ("'" + id + "'");
			var objTmp = document.getElementById( id );
			alert (  objTmp );
			objTmp.scrollIntoView()
		}
		else if (document.anchors)
		{
			scrollTo(0,document.anchors[id].y)
		}
	}



		function gotoLocation(locationX)
	{
		go(locationX);
	}

	function writeErrorIE(message, append)
	{
		log(message);
	}

	function log(message) {
	    if (!log.window_ || log.window_.closed) {
	        var win = window.open("", null, "width=400,height=200," +
	                              "scrollbars=yes,resizable=yes,status=no," +
	                              "location=no,menubar=no,toolbar=no");
	        if (!win) return;
	        var doc = win.document;
	        doc.write("<html><head><title>Debug Log</title></head>" +
	                  "<body></body></html>");
	        doc.close();
	        log.window_ = win;
	    }
	    var logLine = log.window_.document.createElement("div");
	    logLine.appendChild(log.window_.document.createTextNode(message));
	    log.window_.document.body.appendChild(logLine);
	}

	function handleBigView(code, leftDivName, rightDivName)
	{
		//if ( popupEnabled )
		if ( popupEnabled && ((new Date()).getTime() > (bigViewLastRightClick+300)))
			showBigView(code, leftDivName, rightDivName);
	}

	//writeError = parent.writeError;

	function writeError(one, two)
	{ //do nothing
		//log(one);
	}

	function handleOnContextMenu(code, rowNum, colLoc)
	{
		writeError("handleOnContxtMenu() with code=" + code + ", rowNum=" + rowNum + ", colLoc=" + colLoc , true);
		var currentTime = new Date().getTime();

		if ( rowNum == -1 && colLoc == -1 )
		{
			writeError("invalid section", true);
			var lastReturnedBoolean = lastReturnedContext;
			return lastReturnedBoolean;
		}
		else
		{
			writeError("valid section", true);

			if ( !popupEnabled ) //popups disabled
			{
				writeError("popups disabled",true);
				//if not currently visible -- show it
				if ( (typeof(bigViewVisible)!="undefined")&& !bigViewVisible )
				{
					writeError("BigPopup currently not visible, currentTime=" + currentTime + ", bigViewLastClosed=" + bigViewLastClosed + ", diff=" + (currentTime - bigViewLastClosed), true );
					if ( currentTime < (bigViewLastClosed) )
					{
						writeError("not visible -- but recently closed -- show context menu!",true);
						lastReturnedContext = true;
						return true;
					}
					else
					{
						writeError("not visible but closed a while back", true);
						if ( hasCurrentImageClosed )
						{
							writeError("the current image has been closed", true);
							lastReturnedContext = true;
							return true;
						}
						else
						{
							writeError("not visible -- show it!",true);
							showBigView(code, rowNum, colLoc);
							lastReturnedContext = false;
							return false;
						}
					}
				}
				else //its visible
				{
					//hide it -- ir if we just recently hid it -- show context menu
					writeError("visible -- hide it!",true); //changed logic per MK
					hideBigView();
					hasCurrentImageClosed = true; //MK true;
					lastReturnedContext = false; //MK false;
					return false; //MK false;
				}
			}
			else //popups enabled
			{
				writeError("popups enabled",true);
				if ( (typeof(bigViewVisible)!="undefined")&& bigViewVisible )
				{
					writeError("visible",true);
					hideBigView();
					lastReturnedContext = false;
					return false;
				}
				else
				{
					writeError("invisible",true);
					if ( currentTime<(bigViewLastClosed+300)) //just closed dont show the cm
					{
						writeError("false",true);
						lastReturnedContext = false;
						return false;
					}
					else //closed over 300 ms, show cm
					{
						writeError("true",true);
						lastReturnedContext = true;
						return true;
					}
				}
			}
		}
	}
