<!--

// Create Global Namespace for our properties and methods.
var INCASE = window.INCASE || {};

Event.observe(window,'load', function() {
	
	INCASE.initExpansion();
	INCASE.navigation();
	
	$('product-tab').onclick = function() {
		INCASE.Cookie.set('sidebar-categories','expanded',360);
	}
	// $('collab-tab').onclick = function() {
	// 		INCASE.Cookie.set('sidebar-collabs','expanded',360);
	// 	}
	
	// Nifty("div.button","normal transparent");
	// Nifty("div.grnbttn_big","big transparent");
	
	initflickrLightbox();
	
	
});

INCASE.initExpansion = function() {
	if($$('h3.expanded, h3.contracted')) {
		$$('h3.expanded, h3.contracted').each(function(elm) {
			$(elm).onclick = function() {
				Effect.toggle($(elm).next(),'blind',{
					duration : .1,
					afterFinish: function() {
						if($(elm).next().visible()) {
							$(elm).removeClassName('contracted');
							$(elm).addClassName('expanded');
							INCASE.Cookie.set($(elm).next().id,'expanded',360);
						} else {
							$(elm).removeClassName('expanded');
							$(elm).addClassName('contracted');
							INCASE.Cookie.set($(elm).next().id,'contracted',360);
						}
					}
				});
			}
		});
	}
}


INCASE.Cookie = {
	set: function(name, value, daysToExpire) {
		var expire = '';
		if (daysToExpire != undefined) {
			var d = new Date();
			d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
			expire = '; expires=' + d.toGMTString();
		}
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire +'; path=/;');
	},
	get: function(name) {
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
		return (cookie ? unescape(cookie[2]) : null);
	},
	erase: function(name) {
		var cookie = INCASE.Cookie.get(name) || true;
		INCASE.Cookie.set(name, '', -1);
		return cookie;
	},
	accept: function() {
		if (typeof navigator.cookieEnabled == 'boolean') {
			return navigator.cookieEnabled;
		}
		INCASE.Cookie.set('_test', '1');
		return (INCASE.Cookie.erase('_test') === '1');
	}
}



INCASE.navigation = function() {
	
	if(document.all&&document.getElementById) {
		$$("#header>ul>li").each(function(li) {
			li.onmouseover = function() {
				li.addClassName('hover');
			}
			li.onmouseout = function() {
				li.removeClassName('hover');
			}
		});
	}
	
};


INCASE.wishlist = {
	removeItem: function(item,anchor) {
		var row = Element.findElement(anchor,"TR");
		var img = $(anchor).down();
		img.src = "/images/progress_drk.gif";
		
		var url = "/ajax/removeItemFromWishlist.php";
		var params = "itemId=" + item;
		new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onSuccess: function(res) {
					new Effect.Fade(row,{afterFinish: function(effect){
						Element.remove(effect.element);
					}});
				}.bind(this)
			}
		);
	}
};

INCASE.cart = {
	removeItem: function(item,anchor) {
			var row = Element.findElement(anchor,"TR");
			var img = $(anchor).down();
			img.src = "/images/progress.gif";
			
			var url = "/ajax/removeItemFromCart.php";
			var params = "itemId=" + item;
			new Ajax.Request(
				url,
				{
					method: 'post',
					parameters: params,
					onSuccess: function(res,json){
						// INCASE.checkout.needToRecalculate=true;
						// if ($('creditCardFields')) Effect.Fade('creditCardFields', { duration:.25 });
						// if ($('submitOrder')) Effect.Fade('submitOrder', { duration:.25 });
						// if (!INCASE.checkout.needToSelectShipping) Effect.Appear('needToRecalculate');
						new Effect.Fade(row,{afterFinish: function(effect){
								Element.remove(effect.element)
								if(!json.items) {
									$('cartitems').remove();
									if($('checkoutRow')) $('checkoutRow').remove();
									//$('cart_hint').hide();
									$('cartHeader').update('Your shopping cart is currently empty.');
									$('cartlink').setStyle('background-image','url(/images/icon-cart.gif)');
									itemsInCart = 0;
								} else {
									var pluralize = (json.items == 1) ? "" : "s";
									$('cartlink').update(json.items + ' item'+pluralize + " in cart "+formatCurrency(json.subTotal));
								}
								
								$('subtotal').update(formatCurrency(json.subTotal));
								if (!INCASE.checkout.needToSelectShipping) INCASE.checkout.setShipping();
								else if ($('total_detail')) $('total_detail').update(formatCurrency(json.subTotal));
							}
						});
					}.bind(this)
				}
			);
	},
	
	updateQty: function(item,offset) {
		var el  = $('qty_'+item);
		var qty = (el.innerHTML * 1) + offset;
		if(qty > 1) {
			$('qty-minus_'+item).show();
		} else {
			$('qty-minus_'+item).hide();
		}
		el.update(qty);
		var url = "/ajax/updateItemQty.php";
		var params = "itemId=" + item + "&qty=" + qty;
		new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onSuccess: function(res,json) {
					// INCASE.checkout.needToRecalculate=true;
					// if($('creditCardFields')) {
					// 	new Effect.Fade('creditCardFields', { duration:.25 });
					// 	new Effect.Fade('submitOrder', { duration:.25 });
					// }
					// if (!INCASE.checkout.needToSelectShipping) Effect.Appear('needToRecalculate');
					var pluralize = (json.items == 1) ? "" : "s";
					$('cartlink').update(json.items + ' item'+pluralize + " in cart "+formatCurrency(json.subTotal));
					$('subtotal').update(formatCurrency(json.subTotal));
					if (!INCASE.checkout.needToSelectShipping) INCASE.checkout.setShipping();
					else $('total_detail').update(formatCurrency(json.subTotal));
				}
			}
		);
		
	}
}

INCASE.account = {
	removeBillingAddress: function(id) {
		// remove address from dropdown
		for (var i=0; i<$('existingBilling').options.length; i++) {
			if (id==$('existingBilling').options[i].value) {
				$('existingBilling').options[i]=null;

				var url = '/ajax/deleteaddress.php';
				var params = 'id='+encodeURIComponent(id);
				new Ajax.Request(
					url,
					{
						method: 'get',
						parameters: params,
						onSuccess: function(res,json){
							if (json.error) {}
							else {}
						}
					}
				);
			}
		}
		// ajax request to remove billing address
	},
	removeShippingAddress: function(id) {
		// remove address from dropdown
		for (var i=0; i<$('existingShipping').options.length; i++) {
			if (id==$('existingShipping').options[i].value) {
				$('existingShipping').options[i]=null;

				var url = '/ajax/deleteaddress.php';
				var params = 'id='+encodeURIComponent(id);
				new Ajax.Request(
					url,
					{
						method: 'get',
						parameters: params,
						onSuccess: function(res,json){
							if (json.error) {}
							else {}
						}
					}
				);
			}
		}
		// ajax request to remove shipping address
	}
}

INCASE.checkout = {
/*
	createSalesOrder: function(radio) {
		var url = '/ajax/createsalesorder.php';
		var params = Form.serialize(radio.form);
		new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: params,
				onSuccess: function(res){
					if (res.responseText=='' || res.responseText=='0') {
						// ERROR: No sales order found
					}
					else {
						radio.form['salesOrderId'].value = res.responseText;	// sales order id
					}
				}
			}
		);
	},
*/
	needToSelectShipping: true,

	// needToRecalculate: false,

	setShipping: function() {
		Effect.Fade('shippingMethodError',{queue:'front'});
		var url = '/ajax/setshipping.php';
		var params = 'salesOrderId='+$F('salesOrderId');

		// Get checked shipping method
		var f = $$('input.shippingMethodRadio');
		var shippingMethod = '';
		for (var i=0; i<f.length; i++) {
			if (f[i].checked) {
				shippingMethod = f[i].value;
				break;
			}
		}
		params += '&shippingMethod='+shippingMethod;

		// billing address
		if ($('existingBilling')!=null && $F('existingBilling')) {
			params += '&existingBilling='+encodeURIComponent($F('existingBilling'));
		}
		params += '&Name='+encodeURIComponent($F('firstName'));
		params += '&phone='+encodeURIComponent($F('phone'));
		params += '&streetAddress='+encodeURIComponent($F('streetAddress'));
		params += '&streetAddress2='+encodeURIComponent($F('streetAddress2'));
		params += '&city='+encodeURIComponent($F('city'));
		params += '&state='+encodeURIComponent($F('state'));
		params += '&zip='+encodeURIComponent($F('zip'));

		// shipping address
		if ($('existingShipping')!=null && $F('existingShipping')) {
			params += '&existingShipping='+encodeURIComponent($F('existingShipping'));
		}
		params += '&shipping_name='+encodeURIComponent($F('shipping_name'));
		params += '&shipping_phone='+encodeURIComponent($F('shipping_phone'));
		params += '&shipping_streetAddress='+encodeURIComponent($F('shipping_streetAddress'));
		params += '&shipping_streetAddress2='+encodeURIComponent($F('shipping_streetAddress2'));
		params += '&shipping_city='+encodeURIComponent($F('shipping_city'));
		params += '&shipping_state='+encodeURIComponent($F('shipping_state'));
		params += '&shipping_zip='+encodeURIComponent($F('shipping_zip'));
		//if ($('is_business').checked) params += '&is_residential=0';
		params += '&is_residential=1';

		if (
				(($('existingBilling')!=null && $F('existingBilling')) || (
					$F('firstName') && ($F('phone').length>=10) && $F('streetAddress') &&
					$F('city') && $F('state') && ($F('zip').match(/^\d{5}$/))
				)) &&
				(($('existingShipping')!=null && $F('existingShipping')) || (
					$F('shipping_name') && ($F('shipping_phone').length>=10) && $F('shipping_streetAddress') &&
					$F('shipping_city') && $F('shipping_state') && ($F('shipping_zip').match(/^\d{5}$/))
				))
			) {
			$('shippingMethodError').update('');
			$('shippingMethodError').removeClassName('error');
		}
		else {
			$('shippingMethodError').addClassName('error');
			var msg = 'Please enter your full billing and shipping addresses.';
			if (($F('phone').length<10)||($F('shipping_phone').length<10)) msg += '<br />Please check your phone numbers.';
			if ((!$F('zip').match(/^\d{5}$/))||(!$F('shipping_zip').match(/^\d{5}$/))) msg += '<br />Please check your zip codes.';
			//$('shippingMethodError').addClassName('errorMarker');
			$('shippingMethodError').update(msg);
			Effect.Appear('shippingMethodError',{queue:'end'});
			// var f = $$('input.shippingMethodRadio');
			// for (var i=0; i<f.length; i++) {
			// 	f[i].checked=false;
			// }
			return false;
		}

		// Effect.Fade('needToRecalculate', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
		// Effect.Fade('creditCardFields', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
		// Effect.Fade($('submitOrder').up(), { duration:.25 });
		$('needToSelectShipping').style.display='none';

		INCASE.checkout.needToSelectShipping=false;
		Effect.Appear('waitForIt', {queue: {position:'end', scope:'waitForIt'} });	// spinner
		// Effect.Appear('waitForShipping', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
		new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onSuccess: function(res,json){
					Effect.Fade('waitForIt', {queue: {position:'end', scope:'waitForIt'} });
					// Effect.Fade('waitForShipping', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
					if (json.error=='no shipping method') {
						// ERROR: No shippingMethod was set in the form
						// Effect.Appear('needToRecalculate', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
						Effect.Fade('creditCardFields', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
						Effect.Fade($('submitOrder').up(), { duration:.25 });
						// INCASE.checkout.needToRecalculate=true;
					}
					else if (json.error=='no zip code') {
						// ERROR: No shippingMethod was set in the form
						// Effect.Appear('needToRecalculate', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
						Effect.Fade('creditCardFields', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
						Effect.Fade($('submitOrder').up(), { duration:.25 });
					}
					else if (json.error=='HI and 3-day') {
						// ERROR: No shippingMethod was set in the form
						// Effect.Appear('needToRecalculate', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
						Effect.Fade('creditCardFields', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
						Effect.Fade('submitOrder', { duration:.25 });
						$('shippingMethodError').addClassName('error');
						$('shippingMethodError').update('UPS 3-Day Select is not available to Alaska or Hawaii.');
						// hide 3-day option
						$('shippingMethod_603').checked=false;
						Effect.Fade('shippingMethodContainer_603');
						$('shipping_detail').update('not calculated');
					}
					else if (json.error=='no sales order') {
						// ERROR: No sales order found
						// Effect.Appear('needToRecalculate', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
						Effect.Fade('creditCardFields', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
						Effect.Fade($('submitOrder').up(), { duration:.25 });
						// INCASE.checkout.needToRecalculate=true;
					}
					else {
						var thecost = (json.shippingCost==0) ? 'free shipping' : formatCurrency(json.shippingCost);
						$('shipping_detail').update(thecost) ;	// shipping cost
						$('handling_detail').update(formatCurrency(json.handlingCost));
						$('tax_detail').update(formatCurrency(json.taxTotal));
						$('subtotal_detail').update(formatCurrency(json.subTotal));
						$('subtotal').update(formatCurrency(json.subTotal));
						$('total_detail').update(formatCurrency(json.total));
						// Effect.Fade('needToRecalculate', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
						Effect.Appear('creditCardFields', {queue: {position:'end', scope:'creditCardFields'}, duration:.25 });
						Effect.Appear($('submitOrder').up(), { duration:.25 });
						// INCASE.checkout.needToRecalculate=false;
					}
				}
			}
		);
	},
	populateBillingAddress: function(eaid, theForm) {
		var addr;
		for (var i=0; i<eba.length; i++) {
			if (eba[i].id==eaid) addr = eba[i];
		}
		if (addr==undefined) {
			theForm['Name'].value = '';
			theForm['streetAddress'].value = '';
			theForm['streetAddress2'].value = '';
			theForm['city'].value = '';
			theForm['state'].selectedIndex = 0;
			theForm['zip'].value = '';
			//theForm['country'].value = '';
			theForm['phone'].value = '';
			theForm['sameAsBilling'].checked = false;
			return;
		}
		for (var i=0; i<theForm['existingBilling'].options.length; i++) {
			if (theForm['existingBilling'].options[i].value == addr.id) {
				theForm['existingBilling'].selectedIndex = i;
			}
		}
		theForm['Name'].value = addr.name;
		theForm['streetAddress'].value = addr.street;
		theForm['streetAddress2'].value = addr.street2;
		theForm['city'].value = addr.city;
		for (var i=0; i<theForm['state'].options.length; i++) {
			if (theForm['state'].options[i].value == addr.state) {
				theForm['state'].selectedIndex = i;
			}
		}
		theForm['zip'].value = addr.zip;
		//theForm['country'].value = addr.country;
		theForm['phone'].value = addr.phone;
	},
	populateShippingAddress: function(eaid, theForm) {
		var addr;
		for (var i=0; i<esa.length; i++) {
			if (esa[i].id==eaid) addr = esa[i];
		}
		if (addr==undefined) {
			theForm['shipping_name'].value = '';
			theForm['shipping_streetAddress'].value = '';
			theForm['shipping_streetAddress2'].value = '';
			theForm['shipping_city'].value = '';
			theForm['shipping_state'].selectedIndex = 0;
			theForm['shipping_zip'].value = '';
			//theForm['shipping_country'].value = '';
			theForm['shipping_phone'].value = '';
			return;
		}
		for (var i=0; i<theForm['existingShipping'].options.length; i++) {
			if (theForm['existingShipping'].options[i].value == addr.id) {
				theForm['existingShipping'].selectedIndex = i;
			}
		}
		theForm['shipping_name'].value = addr.name;
		theForm['shipping_streetAddress'].value = addr.street;
		theForm['shipping_streetAddress2'].value = addr.street2;
		theForm['shipping_city'].value = addr.city;
		for (var i=0; i<theForm['shipping_state'].options.length; i++) {
			if (theForm['shipping_state'].options[i].value == addr.state) {
				theForm['shipping_state'].selectedIndex = i;
			}
		}
		theForm['shipping_zip'].value = addr.zip;
		//theForm['shipping_country'].value = addr.country;
		theForm['shipping_phone'].value = addr.phone;
	},
	clearPaymentInfo: function(theForm) {
		$$('.paymentMethodRadio').each(function(elm){
			elm.checked=false;
		});
		theForm['nameOnCard'].value='';
		theForm['cardNumber'].value='';
		theForm['securityCode'].value='';
		theForm['expirationMonth'].selectedIndex=0;
		theForm['expirationYear'].selectedIndex=0;
	}
	
};



INCASE.products = {
	click: function(e) {
		e = (e) ? e : window.event;
		var target = $(Event.findElement(e,'li'));
		var href = target.getElementsByTagName('a')[0].href;
		if(href) window.location = href;
		Event.stop(e)
		return false;
	},
	
	mouseover: function(e) {
		e = (e) ? e : window.event;
		var target = $(Event.findElement(e,'li'));
		var a = $(target.getElementsByTagName('a')[1]);
		if(a) a.addClassName('hover');
	},
	
	mouseout: function(e) {
		e = (e) ? e : window.event;
		var target = $(Event.findElement(e,'li'));
		var a = $(target.getElementsByTagName('a')[1]);
				if(a) a.removeClassName('hover');
	},
	
	expandClickArea: function(classname) {
		var buttons = document.getElementsByClassName(classname);
		buttons.each(function(button) {
				Event.observe(button,'click',INCASE.products.click,false);
				Event.observe(button,'mouseover',INCASE.products.mouseover,false);
				Event.observe(button,'mouseout',INCASE.products.mouseout,false);
			});
	},

	swapProductByColor: function(elementId, obj) {
		var el;
		el = $(elementId);
		if(!el.style.backgroundImage.match('url('+obj.thumb+')')) {
			el.style.backgroundImage = 'url('+obj.thumb+')';
		}
		
		$(el).down('a.full-item-click').href = obj.link;
		$(el).down('h3 a').href = obj.link;
		
	},
	
	swapImages: [],
	preloadColorSwapImages: function(imgs) {
		for (var i=0;i<imgs.length;i++) {
			if (imgs[i]!='') {
				var im = new Image();
				im.src = imgs[i];
				INCASE.products.swapImages.push(im);
			}
		}
	}
};



/*
INCASE.imageSwapper =  {
	onPageChange: function() {
		var hash = document.location.hash;
		var id = (!hash) ? null : (hash == "" || (hash.length == 1 && hash.charAt(0) == "#")) ? "" : (hash.length > 1 && hash.charAt(0) == "#") ? hash.substring(1) : hash;
				


			if(id && id != "") {
				$A($('addtlphotos').getElementsByTagName('a')).each(function(anchor) {
					if(anchor.id.split('_')[1] == id) {
						INCASE.imageSwapper.swapImage(anchor);
					}
				});
			} else if(id == "" || !id) {
				INCASE.imageSwapper.swapImage($('addtlphotos').getElementsByTagName('a')[0],{reload: true});
			}
	},

	showNewImage: function() {
		$('longDescription').hide();
		$('thumb_loading').style.visibility = 'hidden';
		document.getElementsByClassName('thumb_description','sub_main').each(function(desc) {
			$(desc).hide();
			});
			
			if($('thumb_description_' + INCASE.imageSwapper.id)) {
				$('thumb_description_' + INCASE.imageSwapper.id).show();
			} else {
				$('longDescription').show();
			}
	},
	
	prepLoading: function(location) {
		location = $(location)
		var loading = document.createElement('div');
		loading.id = 'thumb_loading';
		
		$(loading).style.visibility = 'hidden';
		
		var img = document.createElement('img');
		img.id  = 'thumb_loading_img';
		img.src = "/images/lightbox/loading.gif";
		loading.appendChild(img);
		location.appendChild(loading);
	},
	
	swapImage: function(a) {
		var options = arguments[1] || {
			thumbnail: true,
			reload: false
		};
		var element  = $('main_item_photo');
		var image 	 = Element.extend(element.getElementsByTagName('img')[0]);
		var url	 	 = a.href;
		INCASE.imageSwapper.id		 = a.id.split('_')[1];

		if(!options.reload) {
        	dhtmlHistory.add(INCASE.imageSwapper.id,a.id);
		}
	


		if(!$('thumb_loading')) INCASE.imageSwapper.prepLoading('addtlphotos');
		if(options.thumbnail) {
			Position.clone(Element.findElement(a,'div'),$('thumb_loading'));
		} else {
			var remoteThumb = $('thumb_'+INCASE.imageSwapper.id);
			Position.clone(Element.findElement(remoteThumb,'div'),$('thumb_loading'));
		}
		$('thumb_loading').style.visibility = 'visible';
		image.onload = INCASE.imageSwapper.showNewImage.bind(INCASE.imageSwapper);
		//Change the old image to the new image
		image.src = url;
	}
}
*/
// For consistancy sake, add all the script.aculo.us effects to INCASE.Effect
INCASE.Effect = Object.extend({}, Effect);

// Similar to Event.findElement
Object.extend(Element,{
	findElement: function(element, tagName) {
		var element = $(element);

		while (element.parentNode && (!element.tagName || 
			(element.tagName.toUpperCase() != tagName.toUpperCase())))
			element = element.parentNode;
		
			return $(element);
	}
});



// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
function getPageSize() {
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}
