
Event.observe(window, 'load', function(){
	window.isLoaded = true;
	if(window.Shadowbox){
		window.Shadowbox.init({
			assetURL:"/skin1/scripts/shadowbox/",
			overlayOpacity:.5
		});
	}
}, false);

document.observe("dom:loaded", function(){
  
  // add "search" text to search box
  var searchText = "search...";
  if ($('q').value == "")
  {
    $('q').value = searchText;
    $('q').addClassName('grey');
  }
  
  $('q').observe('click', function(e){
    if ($('q').value == searchText)
    {
      $('q').value = "";
      $('q').removeClassName('grey');
    }
    
  });
  
  
	$$("#catBrandBrowser h3 a").each(function(a){
		Event.observe(a, 'click', function(e){
			var thisTabClass = ($(a.parentNode.parentNode).hasClassName('brand') ? 'brand' : 'category');
			if(thisTabClass == 'brand'){
				$('catBrandBrowser').removeClassName('category-active');
				$('catBrandBrowser').addClassName('brand-active');
				document.cookie = "selectedBrowserTab=brand; path=/"; //expires=" + .toUTCString() + "; 
			}
			else {
				$('catBrandBrowser').removeClassName('brand-active');
				$('catBrandBrowser').addClassName('category-active');
				document.cookie = "selectedBrowserTab=category; path=/"; //expires=" + .toUTCString() + "; 
			}
			
			
			
			//if($('catBrandBrowser').hasClassName(''))
			
			/*
			var thisDiv = a.parentNode.parentNode; //$(a.parentNode.parentNode).removeClassName('');
			$(thisDiv.parentNode).childElements().each(function(div){
				if(thisDiv == div){
					$(div).addClassName('active-tab');
				}
				else {
					$(div).removeClassName('active-tab');
				}
			});
			*/
			Event.stop(e);
			return false;
		});
	});
	
	if($('chooseLoginBtn')){
		/*function showLoginForm(){
			$('quickAccountInfo').addClassName('doing-login');
			$('username').focus();
			return false;
		}*/
		$('chooseLoginBtn').onclick = function(){
			$('quickAccountInfo').addClassName('doing-login');
			$('username').focus();
			return false;
		};
		//$('chooseLoginBtn').onkeypress = showLoginForm;
		/*$('chooseLoginBtn').onkeypress = function(e){
			e = e || window.event;
			var key = e.keyCode || e.which;
			if(key == 32)
				showLoginForm();
		};*/
	}
	/*if($('chooseRegisterBtn')){
		$('chooseRegisterBtn').onclick = function(event){
			window.location = this.href;
			return false;
		};
	}*/
	if($('cancelLoginBtn')){
		$('cancelLoginBtn').onclick = function(){
			$('quickAccountInfo').removeClassName('doing-login');
			return false;
		}
	}
	
	
	if($('productResultDetail')){
		$$('#productsList li.productItem').each(function(li){
			var a = $(li).select("a.productLink")[0];
			var productID = li.getAttribute('data-product-id');
			$(a).observe('click', function(e){
				if(e.preventDefault)
					e.preventDefault();
				e.returnValue = false;
			});
			
			var tellMeWhen = $(li).select("span.tellMeWhen a")[0];
			if(tellMeWhen){
				tellMeWhen.observe('click', function(e){
					if(e.stopPropagation)
						e.stopPropagation();
					e.cancelBubble = true;
				});
			}
			
			$(li).observe('mouseover', function(e){
				$(li).addClassName('hover');
				
				if(!window.isLoaded) //Account for Firefox issue
					return;
				window.onscroll();
				
				if(productImagesByID[productID] && productImagesByID[productID].productImage){
					$('productResultDetailImg').src = "/loading_product_image.gif";
					$('productResultDetailImg').src = productImagesByID[productID].productImage;
					$('productResultDetailTitle').innerHTML = productImagesByID[productID].title;
					$('productResultDetailSKU').innerHTML = productImagesByID[productID].sku;
					$('productResultDetailDesc').innerHTML = productImagesByID[productID].description;
					
					//$('productResultDetail').addClassName('populated');
					//$('productResultDetail').style.visibility = "visible";
					$('productResultDetail').style.display = "block";
				}
				else {
					//hide
					//$('productResultDetail').removeClassName('populated');
					//$('productResultDetail').style.visibility = "hidden";
					$('productResultDetail').style.display = "none";
				}
			});
			$(li).observe('mouseout', function(){
				$(li).removeClassName('hover');
				//$('productResultDetail').removeClassName('populated');
				//$('productResultDetail').style.visibility = "hidden";
				$('productResultDetail').style.display = "none";
			});
			$(li).observe('click', function(e){
				window.location = a.href;
			});
		});
		/*$$('#productsList a.productLink')[0].onmouseover();*/ /* DEBUG */
		
		//Reposition productResultDetail when scrolling below the fold
		//if(/\bshowall\b/.test(window.location.search)){
			//console.info('good');
			//Event.observe(window, 'scroll', function(){
			
			window.setProductsListContainerTop = function(){
				window.productsListContainerTop = $('productsListContainer').offsetTop;
				var offsetParent = $('productsListContainer').offsetParent;
				while(offsetParent){
					window.productsListContainerTop += offsetParent.offsetTop;
					offsetParent = offsetParent.offsetParent;
				}
			}
			window.setProductsListContainerTop();
			
			var productResultDetail = $('productResultDetail');
			
			window.isOldMSIE = (/MSIE [1-6]/.test(navigator.userAgent));
			
			function getPageYOffset(){
				if (self.pageYOffset) // all except Explorer
					return self.pageYOffset;
				else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
					return document.documentElement.scrollTop;
				else if (document.body) // all other Explorers
					return document.body.scrollTop;
			}
			
			//productResultDetail.style.top = "0px";
			
			window.lastPageYOffset = 0;//getPageYOffset();
			window.onscroll = function(e){
				var thisPageYOffset = getPageYOffset();
				if(thisPageYOffset != window.lastPageYOffset){
					if(thisPageYOffset+30 > window.productsListContainerTop){
						if(window.isOldMSIE)
							productResultDetail.style.top = (thisPageYOffset - window.productsListContainerTop + 30) + 'px';
						else
							productResultDetail.addClassName('fixedPosition');
					}
					else {
						if(window.isOldMSIE)
							productResultDetail.style.top = 0;
						else
							productResultDetail.removeClassName('fixedPosition');
					}
					window.lastPageYOffset = thisPageYOffset;
				}
			};
			
			
		//}
		
	}
	
	/* Product detail page ****************************************/
	if($('mainProductImageContainer')){
		//Find the tallest detail/variant image
		window.tallestProductImage = window.productOriginalHeight;
		if(window.detailedImages){
			detailedImages.each(function(img){
				window.tallestProductImage = Math.max(window.tallestProductImage, Math.round(250*img[2]/img[1])); ///*height*//*width*/
			});
		}
		if(window.variants){
			variants.each(function(v){
				if(v && v[0][2].width){
					window.tallestProductImage = Math.max(window.tallestProductImage, Math.round(250*v[0][2].height/v[0][2].width));
				}
			});
		}
		var div = $('mainProductImageContainer');
		div.style.height = Math.floor(window.tallestProductImage) + "px";
		
		var table = $('mainProductImageContainer').select('table')[0];
		if(table){
			table.style.height = Math.floor(window.tallestProductImage) + "px";
		}
		
		//div.style.position = "relative";
		//var img = $('product_thumbnail').parentNode;
		//img.style.position = "absolute";
		//img.style.top = "50%";
		//img.style.marginTop = (-window.tallestProductImage/2) + "px";
		
		//Change the detail image when hovering
		$('productImageViewer').select('.otherProductImages img').each(function(img){
			img.onmouseover = function(){
				if(!window.$)
					return;
				
				$(img.parentNode).select('.selected').each(function(i){
					$(i).removeClassName('selected');
				});
				
				$('product_thumbnail').src = "/loading_product_image.gif";
				$('product_thumbnail').src = img.src.replace(/_tiny/, "_large");
				if(img.id == 'product_thumbnail_tiny'){
					if($('product_thumbnail').src.replace(/_large(?=\/)/, '') == product_image.src && product_image.width > 0 && product_image.height > 0){
						product_thumbnail.width = 250; //MERINGUE
						product_thumbnail.height = product_image.height * (250/product_image.width); //MERINGUE
						//product_thumbnail.width = product_image.width;
						//product_thumbnail.height = product_image.height;
					}
					else {
						product_thumbnail.width = 250;
						product_thumbnail.height = window.productOriginalHeight; //product_image.height * (250/window.productOriginalWidth); //MERINGUE;
						//$('product_thumbnail').width = window.productOriginalWidth;
						//$('product_thumbnail').height = window.productOriginalHeight;
					}
				}
				else {
					var ops = detailedImages[img.id.replace(/\D/g, "")];
					if(ops){
						$('product_thumbnail').width = 250;
						$('product_thumbnail').height = 250*ops[2]/ops[1];
					}
				}	
				$(img).addClassName('selected');
			};
		});
		
	}
	
	if($('add2wlLink')){
		$('add2wlLink').observe('click', function(e){
			this.href = this.href.replace(/amount=(\d+)/, 'amount=' + $F('product_avail'));
		});
	}
	
	if($('eMailAFriendLink')){
		$('eMailAFriendLink').observe('click', function(e){
			$('eMailAFriend').addClassName('open');
			e.stop();
		});
		$('eMailAFriend').select('a.cancel')[0].observe('click', function(e){
			$('eMailAFriend').removeClassName('open');
			e.stop();
		});
	}
	if($('tellMeWhenLink')){
		//$('tellMeWhenLink').observe('click', function(e){
		//	$('tellMeWhen').addClassName('open');
		//	e.stop();
		//});
		//$('tellMeWhen').select('a.cancel')[0].observe('click', function(e){
		//	$('tellMeWhen').removeClassName('open');
		//	e.stop();
		//});
	}
	if($('product_add_btn')){
		$('product_add_btn').observe("mouseover", function(e){
			//this.src = "skin1/images/product_btns/add_btn_over.gif";
			$(this).addClassName('hover'); //for MSIE
		});
		$('product_add_btn').observe("mouseout", function(e){
			//this.src = "skin1/images/product_btns/add_btn.gif";
			$(this).removeClassName('hover'); //for MSIE
		});
	}
	if($('allBrandsLink') && $('categoryBrands')){
		$('allBrandsLink').observe('click', function(){
			$('categoryBrands').display = "block";
			new Effect.Highlight('categoryBrands', {startcolor:"#FEEBED",restorecolor:'#FFFFFF'});
		});
		
	}
	
	
	/*** Add Product Variant images to vertical column *****************************/
	(function(){
		var colorOptionID;
		$$('#productOptionsContainer label').find(function(label){
			if(/color/i.test(label.firstChild.nodeValue)){
				var select = label.getElementsByTagName('select')[0];
				colorOptionID = select.id.replace(/^po/,'');
				return true;
			}
			return false;
		});
		if(!colorOptionID)
			return;

		var images = [];
		var isMissingImage = false;

		$A($('po' + colorOptionID).options).find(function(option){
			for(var x in variants){
				for(var y in variants[x][1]){
					
					if(variants[x][1][y] == option.value){
						if(!variants[x][0][2].src){
							if(images[0])
								images.push(images[0]);
							else {
								isMissingImage = true;
								return true;
							}
						}
						else
							images.push(variants[x][0][2]);
						return false;
					}
				}
				
			}
			return false;
		});
		if(isMissingImage)
			return;
		if(images.length <= 1)
			return;
		
		var div = document.createElement('div');
		div.id = 'variantColorImageList';
		div.innerHTML = "<div class='title'>Colors:</div>";
		
		for(var i = 0; i < images.length; i++){
			if(!images[i])
				continue;
			var option = $('po' + colorOptionID).options[i];
			var img = document.createElement('img');
			img.src = images[i].src.replace(/images\/(\w)[^\/]*/, "images/$1_tiny");
			img.alt = option.text;
			
			var a = document.createElement('a');
			a.href = "javascript:void(0)";
			a.title = option.text;
			a.appendChild(img);
			
			a.associatedOption = option;
			a.onclick = function(){
				this.associatedOption.selected = true;
				check_options();
			};
			
			div.appendChild(a);
		}
		
		$('productImageViewer').parentNode.insertBefore(div, $('productImageViewer').nextSibling);
		$('productDetailContainer').addClassName('hasColorSelector');
		


		
	})();

	//Set up shadowbox***********************************************
	//if(window.Shadowbox){
	//	window.Shadowbox.init({
	//		assetURL:"/skin1/scripts/shadowbox/",
	//		overlayOpacity:.5
	//	});
	//}

    // set up all anchor elements with a 'movie' class to work with Shadowbox
    /*Shadowbox.setup($$('a.movie'), {
        gallery:            'My Movies',
        autoplayMovies:     true
    });*/

	
/**************************************************************
 * cross-browser CSS3 column lists implementation prototype
 * Weston Ruter, 2007-10-24
 ***************************************************************/
//assumption that IE8/Opera10 will support CSS3 columns;
//  Gecko and Webkit already support CSS3 columns
//if(/MSIE [1-7]|Opera\/[1-9]/.test(navigator.userAgent)){

var columnedEls = $$('ul.css3-columns, ol.css3-columns'); //document.getElementsByClassName ? document.getElementsByClassName('ul.css3-columns') :
if(columnedEls.length){
	var firstLI = columnedEls[0].getElementsByTagName('li')[0];
	if(firstLI.offsetWidth > columnedEls[0].offsetWidth / 2){ //determine if CSS3 colmns are supported
		columnedEls.each(function(container){ //better if sniffed from style rule selectors
			container.style.columnCount = 0; //disable if by chance it has been implemented
			
			var children = $(container).immediateDescendants();
			
			var matches = container.className.match(/\bcolumn-count-(\d+)/);
			var columnCount = parseInt(matches[1]); /* should be sniffed from style rules */
			
			var columnItemCount = Math.ceil((children.length)/columnCount);
			var itemHeight = children[0].offsetHeight;
			var columnWidth = Math.floor(container.offsetWidth/columnCount);
			var containerHeight = itemHeight*columnItemCount;
			
			for(var colNum = 0; colNum < columnCount; colNum++){
				var colEl = document.createElement('div');
				colEl.style.cssText = "float:left; width:" + columnWidth + "px";
				for(var i = colNum*columnItemCount; i < (colNum+1)*columnItemCount && i < children.length; i++){
					colEl.appendChild(children[i].parentNode.removeChild(children[i]));
				}
				container.appendChild(colEl);
			}
			//container.style.height = (containerHeight) + "px";
			//container.parentNode.style.clear = "both";
			var clearFloat = document.createElement('div');
			clearFloat.style.clear = "both";
			container.parentNode.insertBefore(clearFloat, container.nextSibling);
		});
	}
}
//}
});



function validateNewsletterForm(form){
	if(form.checkValidity)
		return;
	
	if(!form.email_address.value){
		alert("You must supply your email address.");
		form.email_address.focus();
		return false;
	}
	if(!form.email_address.value.match(/.+@.+/)){
		alert("You must supply a valid email address.");
		form.email_address.focus();
		return false;
	}
	if(!form.first_name.value){
		alert("You must supply your first name.");
		form.first_name.focus();
		return false;
	}
	if(!form.last_name.value){
		alert("You must supply your last name.");
		form.last_name.focus();
		return false;
	}
	return true;
}


