document.write('<script type="text/javascript" src="/resources/modal_dialog.js"><\/script>');
document.write('<script type="text/javascript" src="/resources/fancy_form_styler.js"><\/script>');

/* fix for ie6 image flickering */
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}

var Vars = {
  isAdmin: false,
  gaEnabled : false,
  https : "https:" == document.location.protocol,
  backgroundImage: null,
	backgroundImagePosition: "floating", //alternative is flush
  zIndex: 201, /* for lightbox indexing */
	bodyHeight: 471,
	currentPageHeight: 0,
	printedPageHeight: 800,
  pageElements: {
    body: null,
    pageBox: null,
    pageContainer: null,
    newsContainer: null,
    footerContainer: null
  },
	startTime: (new Date()),
	elapsedTime: function() {
		return(new Date() - Vars.startTime);
	},
  load: function() {
    this.pageElements.body = $$('body')[0];
    this.pageElements.pageBox = $('page-box');
    this.pageElements.watermark = $('watermark');
    this.pageElements.pageContainer = $('page-container');
    this.pageElements.newsBox = $('news-box');
    this.pageElements.newsOpenBtn = $('newsOpenBtn');
    this.pageElements.newsContainer = $('news-container');
    this.pageElements.footerContainer = $('footer-container');
		this.pageElements.ordersLink = 	$('myordershref');
		this.pageElements.projectsLink = 	$('myprojectshref');
    this.client.init();
  },
	client: {
    init: function () {
        Vars.client.browser = Vars.client.searchString(Vars.client.dataBrowser) || "An unknown browser";
        Vars.client.version = Vars.client.searchVersion(navigator.userAgent)
            || Vars.client.searchVersion(navigator.appVersion)
            || "an unknown version";
        Vars.client.OS = Vars.client.searchString(Vars.client.dataOS) || "an unknown OS";
        Vars.client.isIE = (Vars.client.browser=='Explorer');
        Vars.client.isIE6 = (Vars.client.browser=='Explorer' && Vars.client.version < 7);
        Vars.client.isIE7 = (Vars.client.browser=='Explorer' && Vars.client.version < 8 && Vars.client.version > 6);
				Vars.client.isMacFF2 = (Vars.client.browser=='Firefox' && Vars.client.version < 3 && Vars.client.OS=='Mac');
				Vars.client.isSafari = (Vars.client.browser=='Safari');
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            Vars.client.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(Vars.client.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+Vars.client.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"
        }
    ]
  }
}

debug(Vars.elapsedTime() + 'ms: main.js loaded');

function getRoomPlanner() {
	PublicDwr.getRoomPlannerURL(function(response) {
		if (response.hasMessages){
			showDwrMessages(response.messages);
		}
		else if (response.data.roomPlannerURL!=null){
			var roomPlannerWindow = window.open(response.data.roomPlannerURL, 'roomPlannerWindow');
			setTimeout (function() {
					roomPlannerWindow.focus();
				}, 250);
		}
	});
}

function disableSelection(element) {
	element.onselectstart = function() { return false; }
	element.unselectable = "on";
	element.style.MozUserSelect = "none";
}

function fixLayout(/* lockBottom */)
{
  // only because to do this in css is close to (or definitely) impossible
  if(!Vars.pageElements.pageContainer)
    return;
	if(Vars.client.isIE6) {
		$('page-body').setStyle({'height':Math.max(Vars.bodyHeight, $('page-body').scrollHeight)+'px'});
	}
	
	Vars.pageElements.pageBox.select('.menu-box .menu > li').invoke('addClassName','menu-item');
	
	var contHeight = Vars.pageElements.pageContainer.getHeight();
  var winWidth = document.all && !window.opera ? document.documentElement.clientWidth : window.innerWidth; 
  // fix the watermark position
  var contOffset = Vars.pageElements.pageContainer.cumulativeOffset();
	var bgOffset = {top:contOffset.top,left:contOffset.left};
	if(Vars.backgroundImagePosition=='floating') {
		bgOffset.left -= 155;
	}
	if(Vars.backgroundImagePosition=='flush') {
		bgOffset.top += 76;
	}
	
  if(Vars.backgroundImage)
    Vars.pageElements.body.setStyle({backgroundPosition:(bgOffset.left+'px '+bgOffset.top+'px')});

	if(Vars.pageElements.watermark)
		Vars.pageElements.watermark.setStyle({left:(contOffset.left+700)+'px'});
}

function setupPage()
{
  /* Background Image */
  if(Vars.backgroundImage)
    Vars.pageElements.body.setStyle({background:'url(' + Vars.backgroundImage + ') 0px 0px no-repeat'});

  /* Drop Down Menus */
  var currentDDM;
  var lastDDM;
  var hideDDMTimer = null;

  $$('.ddm').each(function(ddm) {

    Event.observe($(ddm),'mouseover',function(event){
      // Get the element from where event is generated
      var elem = $(Event.element(event));

      hideDDMCancel();
      currentDDM = elem.up('.ddm');
      if(currentDDM!=lastDDM && typeof(lastDDM)!="undefined")
        hideDDM(lastDDM);
      lastDDM = currentDDM;

      // We're over the anchore - let's use the LI as the bsae
      if(elem.nodeName=='A')
        elem = elem.up('li');

      // Be sure that it under our unordered list
      if (elem && elem.descendantOf(ddm) && elem.nodeName=='LI')
      {
        // Stop the bubling of the event
        Event.stop(event);

        // Get the child elements of the already expanded menu, which is not parent of currently selected menu or a child of it */
        var oldElem=$$('.selected_item').findAll(function(e){
          return !elem.descendantOf(e) && e!=elem
        });

        // Hide them all
        oldElem.each(function(e){
          e.select('ul').invoke('hide');
          e.removeClassName('selected_item');
        });

        // Add this special tracking class name
        if(!elem.firstDescendant().hasClassName('dropDownAnchor'))
          elem.addClassName('selected_item');
        
        elem.ancestors().each(function(ancs) {
          if(ancs.nodeName=='UL' && ancs.hasClassName('ddm'))
            throw $break;
          if(ancs.nodeName=='LI' && !(elem.up(1).nodeName=='UL' && elem.up(1).hasClassName('ddm')))
          {
            ancs.addClassName('selected_item');
            ancs.down('a').addClassName('selected_item');
          }
        });

        // Collect the UL i.e child menu container and display it
        var ul = elem.down('ul');
        if (ul)
        {
          ul.setStyle({'display':'block'});
          if(typeof(ul.down('div.bg'))=="undefined")
          {
            var ulDimensions = ul.getDimensions();
            ul.insert({top:'<li style="padding:0px;height:0px;margin:0px;"><div class="bg" style="width:'+ulDimensions.width+'px;height:'+ulDimensions.height+'px"></div></li>'});
          }
        }
      }
    });
    
    Event.observe($(ddm),'mouseout',function(event){
      // Get the element from where event is generated
      var elem = $(Event.element(event));
      // Figure out which menu where on
      hideDDMTimout(elem.up('.ddm'));
    });
  });

  function hideDDMTimout(ddm) {
    hideDDMTimer = (ddm == undefined) ? null : setTimeout (function() { hideDDM(ddm) }, 500);
  }
  
  function hideDDM(ddm) {
    hideDDMCancel();
    ddm.select('ul').invoke('hide');
  }
  
  function hideDDMCancel() {
    clearTimeout(hideDDMTimer);
  }

  /* Side Menus - note each li must have a content div */
  $$('div.accordion .menu > li').each(function(sm, index) {
    var contentDiv = sm.down('div.content');
    // menu doesn't have a content div - exit
    if(!contentDiv)
      return;
    
    // div isn't visible - show it for a split sec and grab the height
    if(!sm.hasClassName('selected_item')) {
	    sm.addClassName('selected_item');
	    sm.contentHeight = contentDiv.getHeight();
	    sm.removeClassName('selected_item');
			if(Vars.client.isIE6)
				contentDiv.hide();
	  } else {
	    sm.contentHeight = contentDiv.getHeight();
//			contentDiv.setStyle({'overflow':'visible','height':sm.contentHeight+'px'});
			contentDiv.setStyle({'height':sm.contentHeight+'px'});
		}

    Event.observe($(sm),'click',function(event){
			// make sure there's no other effects happening on the page
      if (Effect.Queue.effects.length > 0) return;
      
      // Get the element from where event is generated
      var elem = $(Event.element(event));

      // if we're clicking somewhere in the content div then don't do anything
      if(elem.up('div.content'))
				return;
			
			// if we're not directly on the LI then we need to search up the tree
      if(!elem.ancestors()[0].hasClassName('menu'))
        elem = elem.up('.menu li');
      
      if(elem.hasClassName('selected_item'))
        return;
			
      elem.singleParade = elem.hasClassName('singleparadenopadding');
      elem.noPadding = elem.hasClassName('nopadding') || elem.singleParade;

			// Stop the bubling of the event
      Event.stop(event);
      
			var contentDiv = elem.down('div.content');

			// Hide them all
      $$('.menu .selected_item').each(function(e){
				if(!e.down('h1')) {
	        new Effect.Morph(e,{style:'padding-top:3px;' + (e.noPadding ? 'padding-bottom:4px;' : 'padding-bottom:0px;') + (e.singleParade ? 'margin-bottom:4px;' : ''),delay:0.2,duration:0.3,
						beforeStart:function() {
							e.setStyle({'paddingTop':'10px'})
						}
					});
	        new Effect.Morph(e.down('a'),{style:'color:#999;font-size:13px;',delay:0.2,duration:0.3,
						beforeStart:function() {
							e.down('a').setStyle({'fontSize':'18px'})
						}
					});
				}
        new Effect.Morph(e.down('div.content'),{style:'height:0px;',delay:0.2,duration:0.3,
					beforeStart:function() {
						e.removeClassName('selected_item');
						e.down('div.content').setStyle({'overflow':'hidden'})
						if(Vars.client.isIE6)
							e.down('div.content').hide();
					}
				});
      });
			
			if(!elem.down('h1')) {
	      new Effect.Morph(elem,{style:'padding-top:10px;' + (elem.noPadding ? 'padding-bottom:0px;' : 'padding-bottom:18px;') + (elem.singleParade ? 'margin-bottom:0px;' : ''),delay:0.2,duration:0.3});
	      new Effect.Morph(elem.down('a'),{style:'color:#333;font-size:18px;',delay:0.2,duration:0.3});
			}
      
			// Check height - the height changes from the first detection in some cases in FF - not sure why
			contentDiv.setStyle({left:'-6000px',height:'100%'});
			if(contentDiv.getHeight() != elem.contentHeight)
				elem.contentHeight = contentDiv.getHeight();
			contentDiv.setStyle({left:'0',height:'0'});

			new Effect.Morph(contentDiv,{style:'height:'+elem.contentHeight+'px;',delay:0.2,duration:0.3,
				afterFinish:function() {
					elem.addClassName('selected_item');
					contentDiv.setStyle({'overflow':'visible'});
					if(Vars.client.isIE6) {
						contentDiv.show();
						$('page-body').setStyle({'height':Math.max(Vars.bodyHeight, $('page-body').scrollHeight)+'px'});
					}
				},
				afterUpdate: function() {
					if(Vars.client.isIE6)
						$('page-body').setStyle({'height':Math.max(Vars.bodyHeight, $('page-body').scrollHeight)+'px'});
				}
			});
    });
  });

  /* Kind of like the accordion except it doesn't cause the other open items to close */
	/* used in corp_bios and client services */
  $$('div.accorditoggle .menu > li').each(function(sm, index) {
    var contentDiv = sm.down('div.content');
    // menu doesn't have a content div - exit
    if(!contentDiv)
      return;
    
    // div isn't visible - show it for a split sec and grab the height
    if(!sm.hasClassName('selected_item')) {
	    sm.addClassName('selected_item');
	    sm.contentHeight = contentDiv.getHeight();
	    sm.removeClassName('selected_item');
	  } else {
	    sm.contentHeight = contentDiv.getHeight();
		}
		
		if(Vars.client.isIE6) {
			sm.headerHeight = sm.down('h3').getHeight();
			if(sm.down('h3').down('span'))
				sm.headerHeight += 16;
			sm.setStyle({'height':sm.headerHeight+'px'});
		}
		
		/* adds page-breaks so that long pages print nicely */
		/*
		Vars.currentPageHeight += sm.contentHeight;
		if(Vars.currentPageHeight > Vars.printedPageHeight) {
			Vars.currentPageHeight = 0;
			//sm.addClassName('pagebreak');
			if(sm.contentHeight > Vars.printedPageHeight) {
				var smHeight = 0;
				sm.down('.content').childElements().each(function(smElem) {
					smHeight += smElem.getHeight();
					if(smHeight > Vars.printedPageHeight) {
						smHeight = 0;
						//smElem.insert({before:'<div class="pagebreak"></div>'}); 
					}
				});
				debug(smHeight);
			}
		}
		*/

		Event.observe($(sm),'click',function(event){
      // make sure there's no other effects happening on the page
      if (Effect.Queue.effects.length > 0) return;
      
			// Get the element from where event is generated
      var elem = $(Event.element(event));

      // if we're clicking somewhere in the content div then don't do anything
      if(elem.up('div.content'))
				return;
			
			// if we're not directly on the LI then we need to search up the tree
      if(!elem.ancestors()[0].hasClassName('menu'))
        elem = elem.up('.menu li');
      
      // Stop the bubling of the event
      Event.stop(event);
			
			var contentDiv = elem.down('div.content');

      if(elem.hasClassName('selected_item')) {
	      // Hide it
				if(!elem.down('h1')) {
	        new Effect.Morph(elem,{style:'padding-top:3px;padding-bottom:0px;',duration:0.3});
	        new Effect.Morph(elem.down('a'),{style:'color:#999;font-size:13px;',duration:0.3});
				}
        new Effect.Morph(contentDiv,{style:'height:0px;',duration:0.3
					,beforeStart:function() {
						elem.removeClassName('selected_item');
					}
					,afterFinish:function() {
						//contentDiv.setStyle({overflow:'hidden'});
						elem.down('.togglea').setStyle({'background':'url(/images/menu-toggle-on.gif) 0px 0px no-repeat'});
					},
					afterUpdate: function() {
						if(Vars.client.isIE6) {
							$('page-body').setStyle({'height':Math.max(Vars.bodyHeight, $('page-body').scrollHeight)+'px'});
							elem.setStyle({'height':(contentDiv.getHeight()+elem.headerHeight)+'px'});
						}
					}
				});
			} else {
				// Check height - the height will change if things have been loaded
				// into the content div since the div was first loaded
				contentDiv.setStyle({left:'-6000px',height:'100%'});
				if(contentDiv.getHeight() > elem.contentHeight)
					elem.contentHeight = contentDiv.getHeight();
				contentDiv.setStyle({left:'0',height:'0'});

	      // Show it
				if(!elem.down('h1')) {
					new Effect.Morph(elem,{style:'padding-top:8px;padding-bottom:16px;',delay:0.2,duration:0.3});
					new Effect.Morph(elem.down('a'),{style:'color:#333;font-size:16px;',delay:0.2,duration:0.3});
				}
				new Effect.Morph(contentDiv,{style:'height:'+elem.contentHeight+'px;',delay:0.2,duration:0.3,
					afterFinish:function() {
						//contentDiv.setStyle({overflow:'visible'});
						elem.addClassName('selected_item');
						elem.down('.togglea').setStyle({'background':'url(/images/menu-toggle-off.gif) 0px 0px no-repeat'});
					},
					afterUpdate: function() {
						if(Vars.client.isIE6) {
							$('page-body').setStyle({'height':Math.max(Vars.bodyHeight, $('page-body').scrollHeight)+'px'});
							elem.setStyle({'height':(contentDiv.getHeight()+elem.headerHeight)+'px'});
						}
					}
				});
			}
    });
  });

  /* News Expand/Contract */
  if(Vars.pageElements.newsContainer==undefined )
    return;
		
  var newsList = Vars.pageElements.newsContainer.down('ul');
    
  if(!newsList)
    return;
    
  var newsItems = newsList.select('li');
	
	if(newsItems.length > 2) {
		var newsItemWidth = (newsItems[0].getWidth() + 27);
		var newsListWidth = (newsItems.length - 2) * newsItemWidth;
		var currentNewsPosition = 0;
	  Event.observe('newsscrollleft', 'click', function() {
	    if (Effect.Queue.effects.length > 0) return;
/*
			if((currentNewsPosition - newsItemWidth) < 0) {
				currentNewsPosition -= newsItemWidth;
				newsList.setStyle({left:currentNewsPosition+"px"});
				newsList.insert({top:newsItems[newsItems.length-1].remove()});
				newsItems = newsList.select('li');
			} else {
				currentNewsPosition -= newsItemWidth;
			}
			new Effect.Move(newsList, { x: newsItemWidth});
*/
			new Effect.Move(newsList, { x: newsItemWidth});
			currentNewsPosition -= newsItemWidth;
			if(currentNewsPosition >= newsListWidth) {
				$('newsscrollright').hide();
			} else {
				$('newsscrollright').show();
			}
			if(currentNewsPosition > 0) {
				$('newsscrollleft').show();
			} else {
				$('newsscrollleft').hide();
			}

			return false;
		});
	  Event.observe('newsscrollright', 'click', function() {
	    if (Effect.Queue.effects.length > 0) return;
/*
			if((currentNewsPosition + newsItemWidth) >= newsListWidth) {
				newsList.insert({top:newsItems[0].remove()});
				newsItems = newsList.select('li');
			}
*/
			new Effect.Move(newsList, { x: -newsItemWidth});
			currentNewsPosition += newsItemWidth;
			if(currentNewsPosition >= newsListWidth) {
				$('newsscrollright').hide();
			} else {
				$('newsscrollright').show();
			}
			if(currentNewsPosition > 0) {
				$('newsscrollleft').show();
			} else {
				$('newsscrollleft').hide();
			}

			return false;
		});
		$('newsscrollleft').hide();
	} else {
		Vars.pageElements.newsContainer.select('#newsscrollleft','#newsscrollright').invoke('hide');
	}
		
	if(Vars.pageElements.newsOpenBtn==undefined)
		return;

  var newsContainerHeight = Vars.pageElements.newsContainer.getHeight();

  var openNews = function() {
    // make sure there's no other effects happening on the page
    if (Effect.Queue.effects.length > 0) return;
    
		Vars.pageElements.newsBox.setStyle({'display':'block'});
		//afterUpdate:function() { fixLayout(true); }
		var left = Vars.pageElements.newsOpenBtn.cumulativeOffset();
    new Effect.Morph(Vars.pageElements.newsBox,{style:'height:'+newsContainerHeight+'px;',duration:0.4, afterUpdate: function() {
			var top = Vars.pageElements.newsOpenBtn.cumulativeOffset()[1];
			window.scrollTo(left, top);
		}});
    Vars.pageElements.newsOpenBtn.innerHTML = 'close news';
    Event.stopObserving('newsOpenBtn', 'click', openNews);
    Event.observe('newsOpenBtn', 'click', closeNews);
    PublicDwr.setNewsEventsState(true);
  }
  var closeNews = function() {
    // make sure there's no other effects happening on the page
    if (Effect.Queue.effects.length > 0) return;

    new Effect.Morph(Vars.pageElements.newsBox,{style:'height:0px;',duration:0.4, /* afterUpdate:function() { fixLayout(true); }, */ afterFinish: function() { Vars.pageElements.newsBox.setStyle({'display':'none'}); } });
    Vars.pageElements.newsOpenBtn.innerHTML = 'news + events';
    Event.stopObserving('newsOpenBtn', 'click', closeNews);
    Event.observe('newsOpenBtn', 'click', openNews);
    PublicDwr.setNewsEventsState(false);
  }
	if(Vars.pageElements.newsBox.hasClassName('open')) {
    Vars.pageElements.newsOpenBtn.innerHTML = 'close news';
	  Event.observe('newsOpenBtn', 'click', closeNews);
	} else {
	  Event.observe('newsOpenBtn', 'click', openNews);
	}
	
}

function debug(s) {
  if (typeof window.console != "undefined") {
    window.console.log(s);
  }
}

function main()
{
  debug(Vars.elapsedTime() + 'ms: running main()');
  Vars.load();
  debug(Vars.elapsedTime() + 'ms: Vars.load()');
  setupPage();
  debug(Vars.elapsedTime() + 'ms: setupPage()');
  fixLayout();
  debug(Vars.elapsedTime() + 'ms: fixLayout()');

  if(typeof(window.console)=="undefined")
  {
    window.console = {
      log:function(arg)
      {
        //alert(arg); 
      }
    };
  }

  if(typeof(dwr)!='undefined')
    dwr.util.setEscapeHtml(false);
  
	debug(Vars.elapsedTime() + 'ms: dwr.util.setEscapeHtml()');

  if (typeof(init) == 'function') // old style init
    init();
	
	debug(Vars.elapsedTime() + 'ms: init()');

  if (typeof(AdminCMSGeneric) == 'object')
    AdminCMSGeneric.init();
	
	debug(Vars.elapsedTime() + 'ms: AdminCMSGeneric.init()');
  
	if(Form.Dynamic)
		Form.Dynamic.prettyEverything();

	debug(Vars.elapsedTime() + 'ms: Form.Dynamic.prettyEverything()');
  
  if (Vars.gaEnabled && _gat) {
    pageTracker = _gat._getTracker("UA-4935652-1"); 
    pageTracker._initData(); 
    pageTracker._trackPageview();
    
    for (var i=0; i<pageTrackerInits.length; i++)
        pageTrackerInits[i](pageTracker);
  }
}

Event.observe(document, 'dom:loaded', main);
//Event.observe(window, 'load', main);
Event.observe(window, 'resize', fixLayout);

/* all the various overlays and their relevant code/DWRs/etc */

function itemSummaryOverlay(itemId) {

	this.itemSummaryOverlayDiv = new Overlay({
			w:560, h:420,
			border:false, renderflush:true, allowscroll:false, modal:true, canClose:true, destroyOnClose:true, zIndex: 497,
			title:'',
			content:'<div class="overlaycontent" id="summaryOverlayDiv"><div style="width:500px;margin-left:10px;"><div class="popup-silo-product">one moment... retrieving product information.</div></div></div>'
	});

	PublicDwr.getItemSummary(itemId, function(itemDetails) {
		if($('summaryOverlayDiv')) {
			$('summaryOverlayDiv').innerHTML = '\
				<div style="width:540px;margin-left:10px;">\
					<div class="popup-silo-product">\
						<img src="'+ s7mediaUrl(itemDetails.product.paradeImage) +'?hei=230&wid=230&align=0,0&sharpen=0&fmt=png-alpha" width="230" height="230">\
					</div>\
					<div class="popup-silo-product">\
						<h3><a href="/product?productId='+itemDetails.product.productId+'">'+itemDetails.product.name+'</a></h3>\
						<div class="sku">item# '+itemDetails.product.rootNumber+'</div>\
						<div class="price">'+(itemDetails.suppressPrice ? '' : ((itemDetails.priceIsConstant ? '' : 'starting at ') + '$' + itemDetails.prettyStartingPrice))+'</div>\
						'+ (itemDetails.product.romanceCopy != null ? '<p>'+ itemDetails.product.romanceCopy +'</p>' : '') +'\
						'+ (itemDetails.dimensions.description ? itemDetails.dimensions.description : '') +'\
						'+ (itemDetails.product.bullets ? itemDetails.product.bullets : '') +'\
					</div>\
				</div>';
		}
	});

}

function printMyProjectReferral(referralId) {
	var designerMessagesPrint = window.open(
		'/designer_messages_print?referralId=' + referralId, 'designerMessagesPrint',
		'toolbar=no,menubar=no,width=900,height=610,scrollbars=yes,resizable=no'
	);
	//debug('printMyProjectReferral:'+referralId);
	setTimeout (function() {
			designerMessagesPrint.focus();
		}, 250);
}

function myProjectAddToCart(productId) {
	var addProductToCartWindow = window.open(
		'/product?popup=true&productId=' + productId, 'addProductToCart',
		'toolbar=no,menubar=no,status=no,width=575,height=600,scrollbars=yes,resizable=no'
	);
	setTimeout (function() {
			addProductToCartWindow.focus();
		}, 250);
}

function closeMyProject() {
	myprojectOverlay.hide();
  //if(Vars.client.isMacFF2)
  if(Vars.client.OS=='Mac')
		$('page-floater').show();
  if(!Vars.client.isIE)
  	window.onbeforeunload = null;
}

function launchMyProject(boardId) {
    // Clear the flyout.
    destroyMyProjects();
    
	// user needs flash 7 or greated to launch my projects
	// users with versions less than v9 will be expressInstalled
	// to the latest version from Adobe.
	if(swfobject.getFlashPlayerVersion().major < 7) {
		this.dialog = new Overlay({
				w:400, h:150,
				modal:true, canClose:true, destroyOnClose:true,
				title: "flash player not detected",
				content: "the latest version of Flash is required, please <a href='http://get.adobe.com/flashplayer/'>click here</a> to download"
		});
	} else {
		// hide the my projects drop down menu
		if(this.myprojectsOverlay) {
			this.myprojectsOverlay.hide();
			this.myprojectsOverlay.destroy();
			Vars.pageElements.projectsLink.previous('.dropdown').hide();
		}
		
		// destroy the my projects overlay if it exists already for some reason - it shouldn't
    if(this.myprojectOverlay) {
        if(!this.myprojectOverlay.destroyed) {
            this.myprojectOverlay.hide();
            this.myprojectOverlay.destroy();
        }
    }
    
		// create my projects overlay and display
    this.myprojectOverlay = new Overlay({
        w:"100%", h:"100%", x:0, y:0,
        custom:true, allowscroll:false, modal:true, canClose:false, destroyOnClose:false, zIndex: 497
    });
		//content:'<div class="overlaycontent" id="myProjectOverlayDiv">the latest version of Flash is required, please <a href="http://get.adobe.com/flashplayer/">click here</a> to download.</div>'
    var flashvars = {location:"/flash/myprojects/"};
    var params = {allowscriptaccess:"always",wmode:"opaque"};
    var images = "EthanAllenGlobal/03-2322,EthanAllenGlobal/03-2327,EthanAllenGlobal/03-2382";
    swfobject.embedSWF("/flash/myprojects/EthanAllenDesigner.swf?boardId=" + boardId, this.myprojectOverlay.contentId, "100%", "100%", "9.0.28", null, flashvars, params);
		this.myprojectOverlay.overlay = $(this.myprojectOverlay.contentId);
		
//		if(Vars.client.isMacFF2)
    if(Vars.client.OS=='Mac')
			$('page-floater').hide();

    if(!Vars.client.isIE) {
			window.onbeforeunload = function() {
				return "You're leaving My Projects. You will lose any unsaved work. Is that your intention?";
			}
		}
	}
}

function launchECatalogDirect(sku, spread) {
  launchECatalog(sku, undefined, undefined, spread);
}

function launchECatalog(sku, w, h, spread) {
		var _w = typeof(w) == 'undefined' ? 950 : w;
		var _h = typeof(h) == 'undefined' ? 575 : h;
		var _cleanspread = typeof(spread) == 'undefined' ? '' : 'initialFrame='+spread+'&';
    this.eCatalogOverlay = new Overlay({
        w:_w, h:_h,
        border:false, renderflush:true, allowscroll:false, modal:true, canClose:true, destroyOnClose:true, zIndex: 497,
        title:'',
        content:'<div class="overlaycontent" id="eCatalogOverlayDiv"></div>\
									<form name="frmState" method="post" action="http://s7d3.scene7.com/s7ondemand/misc/email2friend.jsp" target="emailfriend">\
									<input type="hidden" name="currentState" value="">\
									<input type="hidden" name="company" value="EthanAllenGlobal">\
									<input type="hidden" name="sku" value="'+sku+'">\
									<input type="hidden" name="imageServerRoot" value="http://s7d3.scene7.com">\
									<input type="hidden" name="templateType" value="brochure">\
									<input type="hidden" name="viewerType" value="flash">\
									<input type="hidden" name="urlParams" value="&config=EthanAllenGlobal/'+sku+'">\
								 </form>'
    });
		var params = {allowscriptaccess:"always",wmode:"transparent"}
		swfobject.embedSWF("http://s7d3.scene7.com/is-viewers/flash/genericbrochure.swf?"+_cleanspread+"serverUrl=http://s7d3.scene7.com/is/image/&image=EthanAllenGlobal/" + sku + "&backgroundColor=0xffffff&config=EthanAllenGlobal/" + sku + "&instanceName=" + sku + "&contentRoot=http://s7d3.scene7.com/skins/&searchEngineUrl=http://s7search1.scene7.com/s7search/search&email=true", "eCatalogOverlayDiv", _w, _h, "9.0.28", null, null, params);
}

function launchRoomViewer(image, initialFrame, w, h) {
		var _w = typeof(w) == 'undefined' ? 885 : w;
		var _h = typeof(h) == 'undefined' ? 594 : h;
    this.roomViewerOverlay = new Overlay({
        w:_w, h:_h,
        border:false, renderflush:true, allowscroll:false, modal:true, canClose:true, destroyOnClose:true, zIndex: 497,
        title:'',
        content:'<div class="overlaycontent" id="roomViewerOverlayDiv"></div>'
    });
		var params = {allowscriptaccess:"always",wmode:"transparent"}
		swfobject.embedSWF("http://s7d3.scene7.com/is-viewers/flash/genericzoom.swf?serverUrl=http://s7d3.scene7.com/is/image&image=" + image + "&initialFrame=" + initialFrame + "&skin=EthanAllenGlobal/SWFs/shop by room SWFs/ProductZoomFG_popup.swf&contentRoot=http://s7d3.scene7.com/skins/&hotSpotBorderAlpha=0&hotSpotTextColor=0x333333&hotSpotTextFillAlpha=60&persistence=0&turnTime=0&zoomScl=100&hotSpotEnable=false&modifier=op_sharpen%3d1", "roomViewerOverlayDiv", _w, _h, "9.0.28", null, null, params);
}

function watchImage(url, w, h) {
    this.eSWFOverlay = new Overlay({
        w:400, h:400,
        border:false, renderflush:true, allowscroll:false, modal:true, canClose:true, destroyOnClose:true, zIndex: 497,
        title:'',
        content:'<img src="'+url+'?wid=400&hei=400">'
    });
}

function watchSWF(url, w, h) {
    this.eSWFOverlay = new Overlay({
        w:864, h:486,
        border:false, renderflush:true, allowscroll:false, modal:true, canClose:true, destroyOnClose:true, zIndex: 497,
        title:'',
        content:'<div class="overlaycontent" id="eSWFOverlayDiv"></div>'
    });
		var params = {allowscriptaccess:"always",wmode:"transparent"}
		swfobject.embedSWF(url, "eSWFOverlayDiv", 864, 486, "9.0.28", null, null, params);
}

function watchFilm(url, w, h) {
    this.eVideoOverlay = new Overlay({
        w:864, h:486,
        border:false, renderflush:true, allowscroll:false, modal:true, canClose:true, destroyOnClose:true, zIndex: 497,
        title:'',
        content:'<div class="overlaycontent" id="eVideoOverlayDiv"></div>'
    });
		var params = {allowscriptaccess:"always",wmode:"transparent"}
		swfobject.embedSWF("http://s7d3.scene7.com/is-viewers/flash/videoplayer.swf?vidPaneSize=864,486&vidPaneColor=0xFFFFFF&viewSize=864,486&backgroundColor=0xFFFFFF&vidPause=false&vidPlayToggle=true&vidSndEnable=true&vidSndMute=false&vpbEnable=true&vpbBarBgColor=0xFF8C40&vpbBarLoadedColor=0xCCCCCC&vpbBarThickness=3&help=&skin=SWFs/skins/videoTEST_FG.swf,SWFs/skins/videoTEST_BG.swf&toolTips=true&movie=" + url + "&method=prog&contentRoot=http://s7d3.scene7.com/skins/EthanAllenGlobal/", "eVideoOverlayDiv", 864, 486, "9.0.28", null, null, params);
}

function updateCart(cart) {
    _saveCart(cart);
    if(cart && this.myordersOverlay) {
        Vars.pageElements.ordersLink.previous('.dropdown').hide();
        this.myordersOverlay.hide();
        this.myordersOverlay.destroy();
        this.myordersOverlay = null;
    }
}

function myOrder(cart) {
	if (cart)
		updateCart(cart);

	if(this.myprojectsOverlay) {
		this.myprojectsOverlay.hide();
		Vars.pageElements.projectsLink.previous('.dropdown').hide();
	}
	
	if(this.myordersOverlay) {
		if(!this.myordersOverlay.destroyed && !this.myordersOverlay.isShowing) {
			Vars.pageElements.ordersLink.previous('.dropdown').show();
			this.myordersOverlay.show();
			return;
		} else if(this.myordersOverlay.isShowing) {
			Vars.pageElements.ordersLink.previous('.dropdown').hide();
			this.myordersOverlay.hide();
			return;
		}
	}
	
	Vars.pageElements.ordersLink.previous('.dropdown').show();

	var offset = Vars.pageElements.ordersLink.cumulativeOffset();
	
	hideOrderBg = function() {
		Vars.pageElements.ordersLink.previous('.dropdown').hide();
	}
	
	this.myordersOverlay = new Overlay({
		w:270, h:100, x: (offset.left - 140), y: (offset.top + 16),
		border:false, renderflush:true, allowscroll:false, modal:false, canClose:false, destroyOnClose:false, zIndex: 198,
		hidecallback: hideOrderBg,
		title:'',
		content: '<div id="my-order-dropdown" class="overlaycontent">\
								<div id="my-order-dropdown-bg" class="my-order-dropdown-bg" style="display:none;"></div>\
								<div id="my-order-dropdown-content" class="content-silo dropdowncontent">Loading...</div>\
							</div>'
	});
	
	if (!Vars.cart) {
		// Populate the my orders drop down.
		PublicDwr.getCart(function(cart) {
            _saveCart(cart);
			renderCart(cart);
		});
	} else {
		renderCart(Vars.cart);
	}

	// set a timer to hide the cart if the myOrder drop down has been auto opened
	if (cart) {
		var self = this;
    this.hideCartTimer = setTimeout (function() {
			Event.stopObserving(self.myordersOverlay.overlay, 'mouseover', self.cancelOrderOverlayTimout.bindAsEventListener(self));
			self.myordersOverlay.hide();
		}, 10000);
		Event.observe(this.myordersOverlay.overlay, 'mouseover', this.cancelOrderOverlayTimout.bindAsEventListener(this));
	}
}

function cancelOrderOverlayTimout() {
	clearTimeout(this.hideCartTimer);
}

function _saveCart(cart) {
    Vars.cart = cart;
    var count = $("myordercount");
    if (count)
        $set(count, "&nbsp;("+ (cart ? cart.items.length : 0) +")");
}

function renderCart(cart) {
	// the overlay was closed before the data came back - destroy the overlay
	if(!myordersOverlay.isShowing) {
		myordersOverlay.destroy();
		return;
	}
	$('my-order-dropdown-content').innerHTML = '';
	
	// if no items then show the default board message:
	if(!cart || cart.items.length == 0) {
		$('my-order-dropdown-content').innerHTML = Vars.commonCopy.myOrderEmptyCartCopy;
		return false;
	}

	tempHtml = '';
	if(cart.items.length > 0) {
		tempHtml = '<div id="my-order" class="minicart">\
					<div>\
                      <table>';
        for (var i=0; i<cart.items.length; i++) {
            var cartitem = cart.items[i];
            tempHtml += '<tr>\
              <td class="image"><img src="'+ s7mediaUrl(cartitem.itemImage) +'?hei=50&wid=50&align=0,-1&sharpen=0"/></td>\
              <td class="product">\
                '+cartitem.itemName+'\
                <div class="sku">item# '+cartitem.rootNumber+'</div>\
                <div class="qty">qty: <span class="count">'+cartitem.quantity+'</span></div>\
              </td>\
              <td class="price">$'+(cartitem.itemTotal.prettyValue)+'</td>\
            </tr>';
            
            // Limit of 6
            if (i >= 5) {
                tempHtml += '<tr><td colspan="3">'+ (cart.items.length - i - 1) +' more...</td></tr>';
                break;
            }
        }
		tempHtml += '</table>\
                     <div class="cartlink"><a href="/shopping_cart">full cart details</a></div>\
                     <div class="subtotal">subtotal: <span class="amount">$' + cart.itemTotal.prettyValue + '</span></div>\
                     <div class="checkout"><input type="button" value="checkout now" class="button" style="width:auto" onclick="window.location=\'/shopping_cart\'" /></div>';
					if (Vars.commonCopy.myOrderPointsPromoCopy) {
            tempHtml += '<div id="my-order-dropdown-tout1" class="tout" style="height:auto;padding-bottom:0px;">';
						if(Vars.commonCopy.myOrderPointsPromoBkgd)
	            tempHtml += '<div style="position:absolute;top:0;left:0;width:270px;height:80px;overflow:visible;background:url('+s7mediaUrl(Vars.commonCopy.myOrderPointsPromoBkgd)+') 0px 0px no-repeat;"></div>';
						tempHtml += '\
                       	<div style="position:relative;width:190px;">\
												 	<h3>'+ Vars.commonCopy.myOrderPointsPromoCopy +'</h3>\
												 	<a href="'+ Vars.commonCopy.myOrderPointsPromoLinkUrl +'" style="color:#fff">'+ Vars.commonCopy.myOrderPointsPromoLinkText +'</a><br/><br/>\
											 	</div>\
											</div>';
					}
        
        tempHtml += '\
											<div id="my-order-dropdown-tout2" class="tout" style="height:auto;'+(Vars.commonCopy.myOrderPointsPromoCopy?'margin-top:0px;':'')+'">\
                       <h3>'+ Vars.commonCopy.myOrderDesignReviewCopy +'</h3>\
                       <a href="'+ Vars.commonCopy.myOrderDesignReviewLinkUrl +'">'+ Vars.commonCopy.myOrderDesignReviewLinkText +'</a>\
                     </div>\
                   </div>\
                 </div>';
		$('my-order-dropdown-content').insert({bottom:tempHtml});
		//$('my-order-dropdown-tout').setStyle('height:'+$('my-order-dropdown-tout').getHeight()+'px');
		//<div class="slidertrack trackhorizontal"><div class="sliderhandle handlehorizontal"></div></div>\
	}
	myordersOverlay.setSize(270, $('my-order-dropdown-content').getHeight() - 20);}

function destroyMyProjects() {
    if (this.myprojectsOverlay) {
        Vars.pageElements.projectsLink.previous('.dropdown').hide();
        this.myprojectsOverlay.hide();
        this.myprojectsOverlay.destroy();
        this.myprojectsOverlay = null;
    }
}

function myProjects() {
	debug('myProjects()');

	if(this.myordersOverlay) {
		this.myordersOverlay.hide();
		Vars.pageElements.ordersLink.previous('.dropdown').hide();
	}
	if(this.myprojectsOverlay) {
		if(!this.myprojectsOverlay.destroyed && !this.myprojectsOverlay.isShowing) {
			Vars.pageElements.projectsLink.previous('.dropdown').show();
			this.myprojectsOverlay.show();
			return;
		} else if(this.myprojectsOverlay.isShowing) {
			Vars.pageElements.projectsLink.previous('.dropdown').hide();
			this.myprojectsOverlay.hide();
			return;
		}
	}
	
	Vars.pageElements.projectsLink.previous('.dropdown').show();
	
	var offset = Vars.pageElements.projectsLink.cumulativeOffset();
	
	hideProjectBg = function() {
		Vars.pageElements.projectsLink.previous('.dropdown').hide();
	}
	
	this.myprojectsOverlay = new Overlay({
		w:270, h:100, x: (offset.left - 140), y: (offset.top + 17),
		zIndex: 199, border:false, renderflush:true, allowscroll:false, modal:false, canClose:false, destroyOnClose:false,
		hidecallback: hideProjectBg,
		title:'',
		content: '<div id="my-proj-dropdown" class="overlaycontent">\
								<div id="my-proj-dropdown-bg" class="my-proj-dropdown-bg" style="display:none;"></div>\
								<div id="my-proj-dropdown-content" class="content-silo dropdowncontent">Loading...</div>\
							</div>'
	});

	// Populate the my projects drop down.
	PublicDwr.getMyProjectsInfo(function(projects) {
				
		// the overlay was closed before the data came back - destroy the overlay
		if(!myprojectsOverlay.isShowing) {
			myprojectsOverlay.destroy();
			return;
		}
		//debug('projects data raw: ' + Object.toJSON(projects));

		$('my-proj-dropdown-content').innerHTML = '';
		
		if(projects.hasMessages) {
			$('my-proj-dropdown-content').innerHTML = projects.messages;
			return;
		}
		
		tempHtml = '';
		// if no boards then show the default board message:
		if(projects.data.boards.length > 0) {
			tempHtml = '<div id="my-boards" class="project-silo">\
						<div class="top-links">\
							<div class="left"><h2>my boards</h2></div>\
						</div>\
						<div class="carousel list">\
							<ul>\
								<li>\
									<ul>';
									  projects.data.boards.each(function(board) {
                                        tempHtml += '<li><a href="#" onclick="launchMyProject(' + board.inspirationBoardId + ');return false;"><img src="' + board.smallThumbUrl + '" width="170" height="110" /></a>';
                                        if (board.collaboration)
                                          tempHtml += '<br/><b>COLLABORATION</b>';
                                        tempHtml += '</li>';
										});
			tempHtml += '</ul>\
								</li>\
							</ul>\
						</div>\
						<div class="slidertrack trackhorizontal"><div class="sliderhandle handlehorizontal"></div></div>\
					</div>'
			$('my-proj-dropdown-content').insert({bottom:tempHtml});

			var boardsBrowser = $('my-boards');
			boardsBrowser.sliderTrack = boardsBrowser.down('.slidertrack');
			if(projects.data.boards.length > 1) {
				boardsBrowser.sliderHandle = boardsBrowser.down('.sliderhandle');
				boardsBrowser.list = boardsBrowser.down('ul');
				boardsBrowser.listWidth = (boardsBrowser.list.down('li ul').getWidth() - 10);
				boardsBrowser.slider = new Control.Slider(boardsBrowser.sliderHandle, boardsBrowser.sliderTrack, {
					axis: "horizontal",
					//range: $R(0, ul.offsetHeight),
					//sliderValue: 0,
					onSlide: function(value) {
						boardsBrowser.list.setStyle('left:' + (Math.floor(value/boardsBrowser.slider.maximum*(230-boardsBrowser.listWidth)) + 'px'));
					},
					onChange: function(value) {
						boardsBrowser.list.setStyle('left:' + (Math.floor(value/boardsBrowser.slider.maximum*(230-boardsBrowser.listWidth)) + 'px'));
					}
				});
			} else {
				boardsBrowser.sliderTrack.hide();
			}
			boardsBrowser.setStyle('height:'+boardsBrowser.getHeight()+'px');
		
		} else {
			$('my-proj-dropdown-bg').show();
            var cmtContent = projects.data.cmtContent;
			tempHtml = '<div id="my-projects" onclick="launchMyProject();">\
												<h2>'+ cmtContent.title +'</h2>' + cmtContent.copy + '\
												<a href="'+ cmtContent.linkUrl +'">'+ cmtContent.linkText +'</a>\
											</div>'
			$('my-proj-dropdown-content').insert({bottom:tempHtml});
		}

		if(projects.data.roomPlans.length > 0) {
			tempHtml = '<div id="my-rooms" class="project-silo">\
						<div class="top-links">\
							<div class="left"><h2>my rooms</h2></div>\
						</div>\
						<div class="carousel list">\
							<ul>\
								<li>\
									<ul>';
									  projects.data.roomPlans.each(function(room) {
											tempHtml += '<li><a href="' + room.URLToView + '" target="_blank"><img src="' + room.URLToThumbnail + '" width="170" height="110" /></a></li>';
										});
			tempHtml += '</ul>\
								</li>\
							</ul>\
						</div>\
						<div class="slidertrack trackhorizontal"><div class="sliderhandle handlehorizontal"></div></div>\
					</div>'
			$('my-proj-dropdown-content').insert({bottom:tempHtml});
			
			var roomsBrowser = $('my-rooms');
			roomsBrowser.sliderTrack = roomsBrowser.down('.slidertrack');
			if(projects.data.roomPlans.length > 1) {
				roomsBrowser.sliderHandle = roomsBrowser.down('.sliderhandle');
				roomsBrowser.list = roomsBrowser.down('ul');
				roomsBrowser.listWidth = (roomsBrowser.list.down('li ul').getWidth() - 10);
				roomsBrowser.slider = new Control.Slider(roomsBrowser.sliderHandle, roomsBrowser.sliderTrack, {
					axis: "horizontal",
					//range: $R(0, ul.offsetHeight),
					//sliderValue: 0,
					onSlide: function(value) {
						roomsBrowser.list.setStyle('left:' + (Math.floor(value/roomsBrowser.slider.maximum*(230-roomsBrowser.listWidth)) + 'px'));
					},
					onChange: function(value) {
						roomsBrowser.list.setStyle('left:' + (Math.floor(value/roomsBrowser.slider.maximum*(230-roomsBrowser.listWidth)) + 'px'));
					}
				});
			} else {
				roomsBrowser.sliderTrack.hide();
			}
			roomsBrowser.setStyle('height:'+roomsBrowser.getHeight()+'px');
		}
		
		var clippingsLength = projects.data.clippings.length;
		//debug(Object.toJSON(projects.data.clippings));
		if(clippingsLength > 0) {
			tempHtml = '<div id="my-clippings" class="project-silo">\
						<div class="top-links">\
							<div class="left"><h2>my clippings</h2></div>\
						</div>\
						<div class="carousel list">\
							<ul>\
								<li>\
									<ul>';
										projects.data.clippings.each(function(clip, index) {
											curclip = clip.component;
											if (curclip.clippedFabric)
												tempHtml += '<li><a href="/fabric?fabricId='+ curclip.fabric.fabricId +'"><img src="'+ s7mediaUrl(curclip.fabric.image) +'?crop=0,0,295,295&size=50,50" width="50" height="50" border="0" /></a></li>';
											else if (curclip.clippedProduct)
												tempHtml += '<li><a href="/product?productId='+ curclip.product.productId +'"><img src="'+ s7mediaUrl(curclip.product.paradeImage) +'?hei=50&wid=50" width="50" height="50" border="0" /></a></li>';
											else if (curclip.clippedImage) {
												tempHtml += '<li><img src="'+ s7mediaUrl(curclip.image) +'?hei=50&wid=50" width="50" height="50" border="0" /></li>';
											} else if (curclip.uploadedImage)
												tempHtml += '<li><img src="'+ curclip.thumbFilename +'" height="50" border="0" /></li>';
											if ((index+1) == Math.ceil(clippingsLength / 2))
												tempHtml += '</ul><ul>';
										});
										tempHtml += '</ul>\
								</li>\
							</ul>\
						</div>\
						<div class="slidertrack trackhorizontal"><div class="sliderhandle handlehorizontal"></div></div>\
					</div>';
			$('my-proj-dropdown-content').insert({bottom:tempHtml});

			var clippingsBrowser = $('my-clippings');
			clippingsBrowser.sliderTrack = clippingsBrowser.down('.slidertrack');
			if(clippingsLength > 8) {
				clippingsBrowser.sliderHandle = clippingsBrowser.down('.sliderhandle');
				clippingsBrowser.list = clippingsBrowser.down('ul');
				clippingsBrowser.listWidth = (clippingsBrowser.list.down('li ul').getWidth() - 10);
				clippingsBrowser.slider = new Control.Slider(clippingsBrowser.sliderHandle, clippingsBrowser.sliderTrack, {
					axis: "horizontal",
					//range: $R(0, ul.offsetHeight),
					//sliderValue: 0,
					onSlide: function(value) {
						clippingsBrowser.list.setStyle('left:' + (Math.floor(value/clippingsBrowser.slider.maximum*(230-clippingsBrowser.listWidth)) + 'px'));
					},
					onChange: function(value) {
						clippingsBrowser.list.setStyle('left:' + (Math.floor(value/clippingsBrowser.slider.maximum*(230-clippingsBrowser.listWidth)) + 'px'));
					}
				});
			} else {
				clippingsBrowser.sliderTrack.hide();
			}
			clippingsBrowser.setStyle('height:'+(clippingsBrowser.getHeight())+'px');
		}
		myprojectsOverlay.setSize(270, $('my-proj-dropdown-content').getHeight() - 21);
	});
}

var filterVars, categoryVars, openFilter, closeFilter;
function setupParade(pType /* 1: horizontaly filled data (default), 2: vertically filled data  */, viewportWidth, rightAdjust, onPressCallBack) {
	
	/* October 2009 - This function still drives the roll overs on the category
		 leaf pages. The 'parade' code is still in here to drive the mini parades
		 on other pages. (RV)
	*/

  if($('category')) {
    categoryVars = {height:Math.min($('category').getHeight() + 10)};
  }

  if($('fabrics')) {
    categoryVars = {height:Math.min($('fabrics').getHeight() + 10)};
  }

	$$('.paradeitem', '.paradeinfo').each(function(parade) {
		Event.observe(parade,'mouseover',function(event){
			var elem = $(Event.element(event)).up('li');
			if(hideParadeNext==elem)
				hideParadeCancel();
			Event.stop(event);
			if(!elem.adjusted) {
				var miniParade = true;
				var infoWidth = 110;
				var infoPadding = '';
				if(elem.down('.image img').getWidth()>75 || categoryVars)
				{
					miniParade = false;
					infoWidth = 160;
					infoPadding = 'margin-left:'+Math.round(((elem.getWidth() - infoWidth) / 2))+'px;';
				}
				else
				{
					//fix for mini parades price overlapping cart/add to my projects icons
					if(elem.down('.price'))
						elem.down('.price').setStyle('width:90px;');
					//if there's no price field then sku needs to be shortened
					else if(elem.down('.sku'))
						elem.down('.sku').setStyle('width:90px;');
				}
				//var infoWidth = Math.max(elem.down('.image img').getWidth(),170);
				elem.down('.paradeinfo').setStyle(infoPadding + 'width:'+infoWidth+'px;display:block;');
				elem.adjusted = true;
			}
			elem.down('.paradeinfo').setStyle('display:block');
		});
		Event.observe(parade,'mouseout',function(event){
			var elem = $(Event.element(event));
			hideParadeTimeout(elem.up('li'));
			Event.stop(event);
		});
	});

	var hideParadeNext;

	function hideParadeTimeout(paradeLi) {
		if(hideParadeNext)
			hideParade();
		hideParadeNext = paradeLi;
		hideParadeTimer = (paradeLi == undefined) ? null : setTimeout (function() { hideParade() }, 300);
	}
	
	function hideParade() {
		hideParadeNext.down('.paradeinfo').setStyle('display:none');
		hideParadeCancel();
	}

	function hideParadeCancel() {
		hideParadeNext = null;
		clearTimeout(hideParadeTimer);
	}

	if($('filterdropdown')) 
	{
		filterVars = {dropdown:$('filterdropdown'), bg:$('filterdropdownbg'), toggle:$('filtertoggle')};
    //filterVars.height = Math.min(filterVars.dropdown.getHeight() + 10, 390);
    filterVars.height = Math.min(filterVars.dropdown.getHeight() + 10);
    
    if(filterVars.height > 390)
    {
      $('page-body').setStyle({'height':(filterVars.height - 390 + Vars.bodyHeight)+'px'});
    }
    
		openFilter = function() {
			// make sure there's no other effects happening on the page
			if (Effect.Queue.effects.length > 0) return;
	
			new Effect.Morph(filterVars.dropdown,{style:'height:'+filterVars.height+'px;',duration:0.5});
			new Effect.Morph(filterVars.bg,{style:'height:'+(filterVars.height+25)+'px;',duration:0.5});
			Event.stopObserving(filterVars.toggle, 'click', openFilter);
			Event.observe(filterVars.toggle, 'click', closeFilter);
			filterVars.toggle.removeClassName('open').addClassName('close');
		}
		closeFilter = function() {
			// make sure there's no other effects happening on the page
			if (Effect.Queue.effects.length > 0) return;
			if (filterVars.toggle.hasClassName('open')) return;

			new Effect.Morph(filterVars.dropdown,{style:'height:0px;',duration:0.5});
			new Effect.Morph(filterVars.bg,{style:'height:25px;',duration:0.5});
			Event.stopObserving(filterVars.toggle, 'click', closeFilter);
			Event.observe(filterVars.toggle, 'click', openFilter);
			filterVars.toggle.removeClassName('close').addClassName('open');
		}
	
		Event.observe(filterVars.toggle, 'click', closeFilter);

		filterVars.dropdown.setStyle({display:'block',height:filterVars.height+'px'});
		filterVars.bg.setStyle({display:'block',height:(filterVars.height+25)+'px'});
	}
	
	if(categoryVars) {
		//categoryVars = {height:Math.min($('category').getHeight() + 10)};
    if(categoryVars.height > 390)
    {
      if(!filterVars || (filterVars && categoryVars.height > filterVars.height))
      $('page-body').setStyle({'height':(categoryVars.height - 370 + Vars.bodyHeight)+'px'});
    }
	}

	var parade = $('parade');
	
	if($('parade')) {
		if($('paradescrollleft')) {
			var paradeList = parade.down('ul').down('ul');
			var paradeItems = paradeList.select('li');
			
			if(paradeItems.length > 1) {
				var itemCount = 4;
				var paradeWidth = parade.getWidth();
				if(paradeWidth < 350)
					itemCount = 2;
				if(paradeWidth < 200)
					itemCount = 1;
				var paradeItemWidth = (paradeItems[0].getWidth());
				var paradeListWidth = (paradeItems.length - 2) * paradeItemWidth;
				var currentParadePosition = 0;
				Event.observe('paradescrollleft', 'click', function() {
					if (Effect.Queue.effects.length > 0) return;
					new Effect.Move(paradeList, { x: (paradeItemWidth * itemCount)});
					currentParadePosition -= (paradeItemWidth * itemCount);
					if(currentParadePosition >= paradeListWidth) {
						$('paradescrollright').hide();
					} else {
						$('paradescrollright').show();
					}
					if(currentParadePosition > 0) {
						$('paradescrollleft').show();
					} else {
						$('paradescrollleft').hide();
					}
				});
				Event.observe('paradescrollright', 'click', function() {
					if (Effect.Queue.effects.length > 0) return;
					new Effect.Move(paradeList, { x: -(paradeItemWidth * itemCount)});
					currentParadePosition += (paradeItemWidth * itemCount);
					if(currentParadePosition >= paradeListWidth) {
						$('paradescrollright').hide();
					} else {
						$('paradescrollright').show();
					}
					if(currentParadePosition > 0) {
						$('paradescrollleft').show();
					} else {
						$('paradescrollleft').hide();
					}
				});
				$('paradescrollleft').hide();
			} else {
				parade.select('#paradescrollleft','#paradescrollright').invoke('hide');
			}
		} else {
			//type 1 are the double column product lists which fill horizintally in two long rows
			//type 2 are the fabric lists which file vertically in columns
			var paradeType = pType == 2 ? 2 : 1;
			//the product lists need an extra 90 pixels of padding on their right hand sides to adjust for padding
			//the fabric lists need no padding because the bump right up to the edges
			var rightAdjust = typeof(rightAdjust) == 'undefined' ? (pType == 2 ? 0 : 30) : rightAdjust;
			var paradeBrowser = $('parade');
			paradeBrowser.sliderHandle = paradeBrowser.down('.sliderhandle');
			paradeBrowser.sliderTrack = paradeBrowser.down('.slidertrack');
			paradeBrowser.list = paradeBrowser.down('ul');
			paradeBrowser.listWidth = (paradeBrowser.list.down('li' + (paradeType == 1 ? ' ul' : '')).getWidth() - 10);
			viewportWidth = typeof(viewportWidth) == 'undefined' ? 770 : viewportWidth;
	
			if(typeof(onPressCallBack)!='undefined')
				Event.observe(paradeBrowser.sliderHandle, 'mousedown', onPressCallBack.bindAsEventListener(this));
	
			if((paradeBrowser.listWidth-rightAdjust) < viewportWidth)
			{
				paradeBrowser.sliderTrack.hide();
			}
			else
			{
				paradeBrowser.slider = new Control.Slider(paradeBrowser.sliderHandle, paradeBrowser.sliderTrack, {
					axis: "horizontal",
					//range: $R(0, ul.offsetHeight),
					//sliderValue: 0,
					onSlide: function(value) {
						paradeBrowser.list.setStyle('left:' + (Math.floor(value/paradeBrowser.slider.maximum*(viewportWidth-paradeBrowser.listWidth+rightAdjust)) + 'px'));
					},
					onChange: function(value) {
						// reset the listWidth on drop just in case it changed (sometimes the list gets longer as more items load into it)
						paradeBrowser.listWidth = (paradeBrowser.list.down('li' + (paradeType == 1 ? ' ul' : '')).getWidth() - 10);
						paradeBrowser.list.setStyle('left:' + (Math.floor(value/paradeBrowser.slider.maximum*(viewportWidth-paradeBrowser.listWidth+rightAdjust)) + 'px'));
					}
				});
			}
		}
	}
}

function doSubscribe() {
    new Subscribe();
}

function Subscribe() {
    var self = this;
    
    var content = '\
        <div class="form" style="width:auto;">\
          <div class="popup-silo-form">We\'d be happy to send you the latest scoop. Enter your email address below to be included.<br/><br/>\
            <div id="_sem_errorMessage" class="errorMessage" style="display:none;">\
              <h3>please check the following</h3>\
            </div>\
            <div class="input-box">\
              <label for="_sem_email">your email address</label>\
              <input type="text" id="_sem_email" />\
            </div>\
            <div class="input-box" style="width:120px;">\
              <label for="_sem_postalCode">zip</label>\
              <input type="text" id="_sem_postalCode" />\
            </div>\
            <div class="formbreakshort" style="width:240px;"></div>\
            <input type="button" value="submit" id="_sem_submitBtn"/>\
          </div>\
        </div>';
    
    this.dialog = new Overlay({
        w:282, h:320,
        modal:true, canClose:true, destroyOnClose:true,
        title:'sign up for email updates',
        content: content
    });
    
    this.submit = function() {
        PublicDwr.subscribe("_sem_", $get("_sem_email"), $get("_sem_postalCode"), function(response) {
            if (response.hasMessages)
                showDwrMessages(response.messages, "_sem_errorMessage");
            else {
            pageTracker._trackPageview('/vpv/goals/emailSignUp/success/');
                self.dialog.hide();
                
                new Overlay({
                    w:325, h:125,
                    modal:true, canClose:true, destroyOnClose:true,
                    title:'Thanks for signing up!',
                    content: "You'll be getting Ethan Allen updates and news before you know it."
                });
            }
        });
    };
    
    Form.Dynamic.prettyEverything();
    Event.observe($("_sem_submitBtn"), 'click', this.submit);
}
