// KSP Product Page JavaScript

if(ksp) {
}else{
	var ksp={};
}
document.observe('dom:loaded',function(e){
	// Create instance of Product
 	ksp.product = new ksp.Product(ksp.productJSON);
	// Color Swatches
	if($('colorblock')) {
		$("colorblock").select("li").each(function(v) {
			if(v.down("a").className != 'oneColor'){
				v.colorId = (v.id).substring((v.id).lastIndexOf('_')+1);
				v.down("a").href = "javascript:void(0);";
				v.product = ksp.product;
				v.observe("click",function() {
					if(!this.hasClassName('unavailable')) {
						this.product.changeColor(v.colorId);													 
					}
				}.bind(v));
				v.observeProductColorChange = function(product) {
					if(this.colorId == product.colorId) {
						this.selected = true;
						this.addClassName('selected');
					} else {
						this.selected = false;
						this.removeClassName('selected');
					}
				}
				ksp.product.addColorChangeListener(v);

				v.observeProductSizeChange = function(product) {
					var availableColors = product.getAvailableColors();
					var colorAvailable = false;
					for(var i=0; i<availableColors.length; i++) {
						if(availableColors[i].id == this.colorId) {
							colorAvailable = true;
							this.removeClassName('unavailable')
							this.setStyle({opacity: 1})
							break;
						}
					}
					if(!colorAvailable) {
						this.addClassName('unavailable');
						this.removeClassName('selected');
						this.setStyle({opacity: .3})
					}
				}
				ksp.product.addSizeChangeListener(v);
			}
		});
	}
	
	
	// Alternate Views 
	var altViewContainer = $("alt-img");
	var sizeChartHolder = '';
	if (altViewContainer) {
		// if the size chart exists, save it to add as the last <li>
		if($('size-chart')) {
			sizeChartHolder = $('size-chart');
		}
		altViewContainer.observeProductColorChange = function(product) {
			var altViews = product.getCurrentColorSliceValue().alternateViews;
			var ul = new Element("ul",{'id':'moreViews'});
			for(viewId in altViews) {
				var img = new Element("img",{"src":altViews[viewId].thumbnailImageURL,"alt":"alternate product view"});
				var a = new Element("a",{"href":"javascript:ksp.product.changeView('"+viewId+"');"});
				var li = new Element("li",{"id":viewId});
				a.insert(img);
				li.insert(a);
				ul.insert(li);
			}


			// if the size chart existed for this product, add it as the last <li>
			if(sizeChartHolder) { ul.insert(sizeChartHolder); }
			this.update(ul)
		}
		ksp.product.addColorChangeListener(altViewContainer);
	}
	


	var loader = $(document.body).e('div', 'bottom', {className:'loader'});
	var embeddedZoom = new Df.EmbeddedZoom('mainProductImageWrapper', {
		loader: loader,
		moveEvent: 'drag'
	});
	


	var mainProductImage = $("mainProductImage");
	if(mainProductImage) {
		mainProductImage.hide();
	}

	
	
	
	embeddedZoom.observeProductViewChange = function(product){
		var prodSlice = product.getCurrentColorSliceValue();
		var currentView = product.getCurrentView();
		if(currentView!=null && currentView.mainImageURL!='') {			
			var imageHash = {
				base: currentView.mainImageURL
			};
			if(currentView.enhancedImageURL) {
				imageHash.zoom =	currentView.enhancedImageURL;
				$('enhImgLink').addClassName('active');
			}
			else {
				$('enhImgLink').removeClassName('active');
			}
		}else{
			var imageHash = {
				//base: ksp.product.mainImageURL
				base: "/images/imgnotavail.jpg"
			};
			if(ksp.product.enhancedImageURL) {
				imageHash.zoom =	ksp.product.enhancedImageURL;
				$('enhImgLink').addClassName('active');
			}
			else {
				$('enhImgLink').removeClassName('active');
			}
		}
		this.load(imageHash);
	};
	ksp.product.addViewChangeListener(embeddedZoom);

	var enhImgLink = $('enhImgLink');
	if(enhImgLink) {
		enhImgLink.embeddedZoom = embeddedZoom;
		enhImgLink.observe('click', function(e){		
			this.embeddedZoom.element.fire(':zoomTo', {decimal: Math.abs(embeddedZoom.decimal - 1)});
		});
	}


	if ($('availMsg')) {
		$('availMsg').observeProductSkuChange = function(product) {
			if (product.skuId != null && product.skuId != '') {
				var sku =  product.getSkuById(product.skuId);
				var skuFlag = null;
				if(sku) {
					skuFlag = sku.avail;
				}
				
				if(skuFlag !=null && skuFlag.indexOf('ADVANCE_SALE')>-1) {
					if(sku.nextExpectedDate!='') {
						var dateParts = sku.nextExpectedDate.split("-");
						if(dateParts.length>2) {
							var expectedDate = new Date(dateParts[0],dateParts[1]-1,dateParts[2]);
							this.update(sku.availabilityMessage + ' ' + (parseInt(expectedDate.getMonth())+1) + "/"+expectedDate.getDate()+"/"+expectedDate.getFullYear());
							this.style.display = 'block';
						}
					}
				} else if(skuFlag !=null && skuFlag.indexOf('RELEASE_DATE')>-1) {
						var dateParts = sku.releaseAfterDate.split("-");
						if(dateParts.length>2) {
							var expectedDate = new Date(dateParts[0],dateParts[1]-1,dateParts[2]);
							this.update(sku.availabilityMessage + ' ' + (parseInt(expectedDate.getMonth())+1) + "/"+expectedDate.getDate()+"/"+expectedDate.getFullYear());
							this.style.display = 'block';
						}
				}
				else {
					this.style.display = 'none';
				}
			} else {
				this.style.display = 'none';
			}
		}
		ksp.product.addSkuChangeListener($('availMsg'));
	}


	if($('priceDesc')) {
		$('priceDesc').observeProductSkuChange = function(product) {
			
			this.basePriceDisplay = ''
			this.priceSeparator = ''
			this.priceDisplay = ''
			this.finalDisplayPrice = ''
			
			if(product.productPriceDisplay.indexOf('SKU') > -1) {
				var priceData = ksp.buildPriceOrRange(this, product)
					
				if(priceData.skuBasePriceMin == priceData.skuBasePriceMax || priceData.skuBasePriceMax == 0) {
					this.basePriceDisplay = priceData.skuBasePriceMin
				} else {
					this.basePriceDisplay = priceData.skuBasePriceMin + ' - ' + priceData.skuBasePriceMax;
				}
				
				if(priceData.skuPriceMin == priceData.skuPriceMax || priceData.skuPriceMax == 0) {
					this.priceDisplay = priceData.skuPriceMin
				} else {
					this.priceDisplay = priceData.skuPriceMin + ' - ' + priceData.skuPriceMax;
				}
			} else {
				this.basePriceDisplay = product.priceData.basePrice
				this.priceDisplay = product.priceData.price
			}
			
			// what about if price and base price are the same?
			if(this.basePriceDisplay == this.priceDisplay) {	
				this.basePriceDisplay = ''
			}

			// assemble display price based on assigned variables
			if(this.basePriceDisplay != '' && !Object.isUndefined(this.basePriceDisplay)) {
				this.productFinalDisplayPrice = '<del>' + this.basePriceDisplay + '</del>'
				this.productFinalDisplayPrice += this.priceSeparator
				this.productFinalDisplayPrice += '<span class="salePrice"><em>' + this.priceDisplay + ' sale</em></span>'
			} else {
				this.productFinalDisplayPrice = this.priceDisplay
			}
			
			$('priceDesc').innerHTML = this.productFinalDisplayPrice
		}
		ksp.product.addSkuChangeListener($('priceDesc'))
	}


	// HTML size drop down
	if ($('productsize')) {
		$("productsize").select("li").each(function(v) {
			v.sizeId = (v.id).substring((v.id).lastIndexOf('_')+1);
			v.down("a").href = "javascript:void(0);";
			v.product = ksp.product;
			v.observe("click",function() {
				if(!this.hasClassName('unavailable')) {
					this.product.changeSize(v.sizeId);													 
				}
			}.bind(v));
			v.observeProductSizeChange = function(product) {
				if(this.sizeId == product.sizeId) {
					this.selected = true;
					if(!this.hasClassName('selected')) {
						this.addClassName('selected');
					}
				} else {
					this.selected = false;
					if(this.hasClassName('selected')) {
						this.removeClassName('selected');
					}
				}
			}
			ksp.product.addSizeChangeListener(v);
			v.observeProductColorChange = function(product) {
				var availableSizes = product.getAvailableSizes();
				var sizeAvailable = false;
				for(var i=0; i<availableSizes.length; i++) {
					if(availableSizes[i].id == this.sizeId) {
						sizeAvailable = true;
						if(this.hasClassName('unavailable')) {
							this.removeClassName('unavailable');
						}
						break;
					}
				}
				if(!sizeAvailable) {
					if(!this.hasClassName('unavailable')) {
						this.addClassName('unavailable');
					}
					if(this.hasClassName('selected')) {
						this.removeClassName('selected');
					}
				}
			}
			ksp.product.addColorChangeListener(v);
		});
	}

	
	if($("prod_0")) {
		$("prod_0").observeProductSkuChange = function(product) {
			if((product.productId != '' && product.productId != null) && (product.skuId != '' && product.skuId != null)) {
				this.value = product.productId + '|' + product.skuId;
			}else{
				this.value = '';
			}
		}
		ksp.product.addSkuChangeListener($("prod_0"));
	}

	if($("errMsg")) {
		$("errMsg").observeProductSkuChange = function(product) {
			if((product.productId != '' && product.productId != null) && (product.skuId != '' && product.skuId != null)) {
				$("errMsg").innerHTML = ''
				$("errMsg").setStyle({display: 'none'})
			}
		}
		ksp.product.addSkuChangeListener($("errMsg"));
	}


	// make tips from glossary terms
	if($$('.glossaryRegion')[0]){
		new Ajax.Request('../services/glossary.jsp', {
			method: 'get',
			onComplete: function(x){
				var node = $$('.glossaryRegion')[0]
				var html = node.innerHTML
				var hash = {}

				try{
					$(document.body).insert(x.responseText.replace(/^[\s|\S]+?<dl>([\s|\S]+?)<\/dl>[\s|\S]+$/i, '<dl style="display:none" id="ksp_glossary_list">$1</dl>'))
					$('ksp_glossary_list').select("dt").each(function(v){
						html = html.replace(new RegExp('\\b(' + v.innerHTML + ')\\b', 'gi'), '<span class="gloss">$1</span>') 
						hash[v.innerHTML] = v.next('dd').innerHTML
					})
					node.innerHTML = html

					$$('.gloss').each(function(v){
						new Df.Tip(v, {
							treatAsMenu: true,
							yOffset: -7,
							xOrientation: 'right',
							yOrientation: 'top',
							pointerOrientation: 'top',
							animate: {
								opacity:1
							},
							data: '<div class="innerHolder"><h3>' + v.innerHTML + '</h3><p>' + hash[v.innerHTML] + '</p></div>'
						}).holder.setStyle({opacity:0})
					})
				}catch(e){
				}
			},
			onFailure: function(x, e){alert('failure ' + e.message)},
			onException: function(x, e){alert('exception ' + e.message)}
		})
	}
	
	
	// reposition the color text centered under each associated swatch
	if($('colorblock')){
		var swatchCount = 0
		var overallOffset = 14
		var maxSwatchesForTxtCentering = 6

		$$('li[id^="swatch_"]').each(function(v) { 
			farRightSwatchOffset = 0
			swatchCount ++
			
			var sol = v.down('a').cumulativeOffset().left
			var tol = v.down('div').cumulativeOffset().left
			var tw = v.down('div').offsetWidth

			if(swatchCount > maxSwatchesForTxtCentering) {
				v.down('div').setStyle({left: ((sol - tol) - tw + (overallOffset * 2)) + 'px'})
			} else {
				v.down('div').setStyle({left: ((sol - tol) - (tw / 2) + overallOffset) + 'px'})
			}
		})
	}

	//  ON LOAD STUFF
	if(ksp.product.availableColors.length >= 1) {
		ksp.product.changeColor(ksp.product.availableColors[0].id);
	}
	
	// added to handle the kateSimple scenario where size and color arrays are empty
	else if(ksp.product.availableColors.length == 0 && ksp.product.skus.length == 1 && ksp.product.skus[0].size == 'no size') {
		ksp.product.changeSku(ksp.product.skus[0].sku_id)
		if(ksp.product.defaultViewId!='') {
			ksp.product.changeView(ksp.product.defaultViewId);
		}
	}
	
	else if(ksp.product.availableSizes.length == 1) {
		ksp.product.changeSku(ksp.product.availableSizes[0].id);
		if(ksp.product.defaultViewId!='') {
			ksp.product.changeView(ksp.product.defaultViewId);
		}
	}

	if($('qty_0')){
		$('qty_0').observe('click', function(){ 
			$('errMsg').innerHTML = '' 
			$('errMsg').setStyle({display: 'none'}) 
		})
		$('qty_0').observe('change', function(){ 
			$('errMsg').innerHTML = '' 
			$('errMsg').setStyle({display: 'none'}) 
		})
	}
	
	//remove href and add listeners if javascript is on, otherwise the hard-coded href will work
	if($('shareLink')) {
		$('shareLink').href = 'javascript: void(0)'
		$('shareLink').observe('click', function() {
			var x = addthis_sendto();
			return x;
		})
		$('shareLink').observe('mouseover', function() {
			return addthis_open(this, '', '[URL]', '[TITLE]')
		})
		$('shareLink').observe('mouseout', function() {
			addthis_close()
		})
	}
	
	
	ksp.preloadImages("thumbnailImageURL");


});
Event.observe(window,"load", function() {
	ksp.preloadImages("mainImageURL");
//	ksp.preloadImages("enhancedImageURL");
	
});
ksp.preloadImages = function(imageType) {
	var imageLoaderDiv = new Element("div",{"style":"height:0px;overflow:hidden;"});
	document.body.insert(imageLoaderDiv);
	var altViews = ksp.product.alternateViews;
	for(viewId in altViews) {
		if(altViews[viewId][imageType]!='') {
			var img = new Element("img",{"src":altViews[viewId][imageType]});
			imageLoaderDiv.insert(img);
		}
	}
	for(var i = 0; i < ksp.product.availableColors.length; i++) {
		altViews = ksp.product.availableColors[i].alternateViews;
		for(viewId in altViews) {
			if(altViews[viewId][imageType]!='') {
				var img = new Element("img",{"src":altViews[viewId][imageType]});
				imageLoaderDiv.insert(img);
			}
		}
	}
}

ksp.buildPriceOrRange = function(elem, product) {
	var skuBasePriceMin = 0
	var skuBasePriceMax = 0
	var skuPriceMin = 0
	var skuPriceMax = 0
	
	var skuBasePrice = null
	var skuPrice = null

	elem.currentColorSkus = new Array();
	elem.currentColorSkus = product.getAvailableSkus();

	for(var j = 0; j < elem.currentColorSkus.length; j++) {
		skuBasePrice = elem.currentColorSkus[j].basePrice
		skuPrice = elem.currentColorSkus[j].price

		if(skuBasePriceMin == 0 && skuBasePrice) {
			skuBasePriceMin = skuBasePrice
		} else if(skuBasePrice) {
			if(skuBasePrice < skuBasePriceMin) {  
				skuBasePriceMin = skuBasePrice
			}
		}

		if(skuBasePriceMax == 0 && skuBasePrice) {
			skuBasePriceMax = skuBasePrice
		} else if(skuBasePrice) {
			if(skuBasePrice > skuBasePriceMax) {  
				skuBasePriceMax = skuBasePrice
			}
		}

		if(skuPriceMin == 0 && skuPrice) {
			skuPriceMin = skuPrice
		} else if(skuPrice){
			if(skuPrice < skuPriceMin) {  
				skuPriceMin = skuPrice
			}
		}

		if(skuPriceMax == 0 && skuPrice) {
			skuPriceMax = skuPrice
		} else if(skuPrice){
			if(skuPrice < skuPriceMax) {  
				skuPriceMax = skuPrice
			}
		}
	}
	
	return {'skuBasePriceMin':skuBasePriceMin, 'skuBasePriceMax':skuBasePriceMax, 'skuPriceMin':skuPriceMin, 'skuPriceMax':skuPriceMax}
}
