//ANYTHING THAT NEEDS TO HAPPEN IMMEDIATELY

jQuery('#hat-options form select').hide();
jQuery('.tag-for-price').hide();


/////////// HASH ///////////////

function getValueInd(ar,val) {
	var pos = -1;
	for (i=0;i<ar.length;i++) {
		if(ar[i]==val) {
		pos = i;
		return pos;
		}
	}
}


function setHatBuilderFromHash()
{
	var hshAR = window.location.hash.substr(2).split('/');
	var md = hshAR[0].replace(/_/g,' ');
	if(md != "")
	{
		curModel = md;	
	}
	if(hshAR[1])
	{
		curColor = hshAR[1].replace(/_/g,' ');
	}
	

	if(curColor.indexOf('&') != -1 && window.location.href.indexOf('products/hats') != -1)
	{
		//show snowboard text
		jQuery('#hat-options-title').css(
			{
				'background-position':'0 -50px',
				'left':'-45px'
			}
		);
		isSnowboard = true;
		curModel = "";

		//scroll to top
		if(window.location.hash != "")
		{
	    jQuery.scrollTo(150);	
		}
	} else if(isOtherProducts)
	{
		if(hshAR[2] != undefined)
		{
			curOther = hshAR[2].replace(/_/g,' ');	
		} else
		{
			curOther = "";
		}
		if(window.location.hash != "")
		{
	    jQuery.scrollTo(150);		
		}
	}
	
	if(hshAR[2])
	{
		curPin = hshAR[2].replace(/_/g,' ');
	}
	var modelInd = getValueInd(modelsNameAR,curModel);
	//get value for celebrity and remove and place first
	if(modelInd)
	{
		modelsURLAR.unshift(modelsURLAR.splice(modelInd,1));
		modelsNameAR.unshift(modelsNameAR.splice(modelInd,1));
		colorsAR.unshift(colorsAR.splice(modelInd,1));
	}	

}


//use hash to set hat color and celebrity
function setHashPosition() 
{
	var hshAR = window.location.hash.substr(2).split('/');
	var curMod = hshAR[0];
	var nextMod;
	var prevMod;

	curModel = curMod.replace(/_/g,' ');
	//see if current model div is one less or one greater than current (first) div
	if(modelsNameAR.length-1)
	{
		var $nM = jQuery('.hat-model').eq(1).find('.model-image img:last');
		if($nM.length>0)
		{
			nextMod = $nM.attr('alt').replace(/ /g,'_');	
		}
		var $pM = jQuery('.hat-model').eq(modelsNameAR.length-1).find('.model-image img:last');
		if($pM.length>0)
		{
			prevMod = $pM.attr('alt').replace(/ /g,'_');	
		}

	} 
	
	var hatAnimSpeed = 1000;
	if(nextMod == curMod && isNextModel)
	{
		//set source image of next mod to cur mod src (for sharing image)
		isNextModel = false;
		//set z-index of 
		jQuery('#hat-options').css('z-index',28);
		jQuery('#hat-images-holder').css('z-index',29);
		jQuery('#product-thumbs').css('z-index',27);
		jQuery('#model-arrows-holder').css('z-index',30);
		jQuery('#tundra-details-holder').css('z-index',31);

		jQuery('#hat-models').animate({
			'margin-left':-1*jQuery(window).width()
			},
			hatAnimSpeed,
			function() {
			//first element to end and reset margin
			jQuery('.hat-model').filter(":first").remove().appendTo('#hat-models');
			jQuery('#hat-models').css({'margin-left':0});
			//reset z-index
			jQuery('#hat-options').css('z-index',55);
			jQuery('#hat-images-holder').css('z-index',15);
			jQuery('#product-thumbs').css('z-index',18);
			jQuery('#model-arrows-holder').css('z-index',17);
			jQuery('#tundra-details-holder').css('z-index',16);
		})

		jQuery('#hat-images').animate({
			'margin-left':-1*jQuery(window).width()
			},
			hatAnimSpeed,
			function() {
			//first element to end and reset margin
			jQuery('.hat-image').filter(":first").remove().appendTo('#hat-images');
			jQuery('#hat-images').css({'margin-left':0});
		})
	} else if(prevMod == curMod)
	{
		jQuery('.hat-model').filter(':last').remove().prependTo('#hat-models');
		jQuery('#hat-models').css({'margin-left':-1*jQuery(window).width()});
		jQuery('.hat-image').filter(':last').remove().prependTo('#hat-images');
		jQuery('#hat-images').css({'margin-left':-1*jQuery(window).width()});
		
		//set z-index of 
		jQuery('#hat-options').css('z-index',28);
		jQuery('#hat-images-holder').css('z-index',29);
		jQuery('#product-thumbs').css('z-index',27);
		jQuery('#model-arrows-holder').css('z-index',30);
		jQuery('#tundra-details-holder').css('z-index',31);

		jQuery('#hat-models').animate({
			'margin-left':0
			},
			hatAnimSpeed,function() {
					
			jQuery('#hat-options').css('z-index',55);
			jQuery('#hat-images-holder').css('z-index',15);
			jQuery('#product-thumbs').css('z-index',18);
			jQuery('#model-arrows-holder').css('z-index',17);
			jQuery('#tundra-details-holder').css('z-index',16);
			});

		jQuery('#hat-images').animate({
			'margin-left':0
			},
			hatAnimSpeed);
	} else
	{
		//TODO (maybe)
		//move all the way to correct model
	}
	
	setDropDowns();
	//hat color
	if(curColor == "")
	{
		setHatColor(true);
	} else
	{
		setHatColor();
	}
	if(curPin == "")
	{
		setPin(true);
	} else
	{
		setPin();
	}
	
	//check price and show tag if things selected
	if(curPrice && curColor != "" || curPrice != "")
	{

		checkPrice();	
	}

}


function checkPrice(p)
{
	var p;
	if(p)
	{
	} else if(!isOtherProducts)
	{
		p = 0;
		if(curColor != "")
		{
			if(isSnowboard)
			{
				p = snowboardPrice;
			} else
			{
				p = hatPrice;
				if(curPin!= "")
				{
					p=Number(p)+8;
				}	
			}
		} else if(curPin != "")
		{
			p = 8;
		}
	}
	
	//animate tag down if p > 0
	if(p == undefined)
	{
		return;
	}
	var $ele = jQuery('.tag-for-price');
	$ele.show();
	$ele.text('$'+p);
	if(p > 0)
	{
		$ele.animate({'top':70},'fast');
	} else
	{
		$ele.animate({'top':15},'fast');
	}
}


function setDropDowns()
{
	//set dropdowns from hash 
	//set dropdown to initial color	
	if(curColor != "")
	{
		jQuery('.hat-color option:contains("'+curColor+'")').attr('selected','selected');
		colorVal = jQuery('.hat-color').val();
	}
	if(curPin != "")
	{
		jQuery('.sport-pin option:contains("'+curPin+'")').attr('selected','selected');	
		pinVal = jQuery('.sport-pin').val();
	}
}




/////////// BUTTONS //////////////

//a function so can reattach events once ajax fires
var isCartNew = true;
function resetCart(isUpdate,isError)
{
	var $cart = jQuery('#tundra-cart .cart');
	$cart.css({
		'display':'block'
	});
	jQuery('#tundra-cart .tab').css({'display':'block'});
	if(isCheckout)
	{
		var $but = jQuery('#tundra-cart .checkout-button a');
		//replace text in submit button
		$but.replaceWith('<a style="padding:14px 10px;" href="#" onclick="document.checkoutForm.submit();">Place Order</a>')
		jQuery('#tundra-cart .cart').css({
			'display':'block',
			'margin-top': 0
		});
				
		jQuery('#tundra-cart .tab').css('display','block');
		//still set update button
		updateUpdateButton();

		//disable place order button once clicked
		jQuery('#tundra-cart .checkout-button a').click(function() {
			jQuery(this).replaceWith('<a style="padding:14px 10px;">Place Order</a>');
		})
	} else
	{
		if(isUpdate)
		{
			jQuery('#tundra-cart .cart').css({
				'margin-top': 0
			});
		} else
		{
			if(!isCartOpen)
			{
				if(isCartNew)
				{
					isCartNew = false;
					var mT = 0;
					$cart.css({
						'display':'block',
						'margin-top': -1*$cart.height()-40-mT
					});
					jQuery('#tundra-cart .tab').css('display','block');
					$cart.delay(500).animate({'margin-top': -1*$cart.height()-mT});
				} else
				{
					//make sure cart is initially positioned closed
					$cart.css({
						'margin-top':-1*$cart.height()
					})
					if(isError)
					{
						//open and cart
						$cart.animate({'margin-top':0},500);
						isCartOpen = true;
					} else
					{
						//open and close cart
						$cart.animate({'margin-top':0},500).delay(1000).animate({'margin-top':-1*$cart.height()-1},500);
					}
				}
			} 
		}
		//update button
		updateUpdateButton();

		jQuery('#tundra-cart .tab').unbind('click');
		jQuery('#tundra-cart .tab').click(function() {
			if(isCartOpen)
			{
				//close cart
				jQuery('#tundra-cart .cart').animate({'margin-top':-1*jQuery('#tundra-cart .cart').height()},500);
				isCartOpen = false;
			} else
			{
				//open cart
				jQuery('#tundra-cart .cart').animate({'margin-top':0},500);
				isCartOpen = true;
			}
		})
	}
	
}

function updateUpdateButton()
{
		jQuery('#tundra-cart .btn-update').unbind('click');
		jQuery("#tundra-cart .btn-update").click(function() {
			//show loader
			jQuery('#tundra-cart .update-row').append('<div class="clearer"></div><span class="update-gif">Updating Cart&hellip;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>')
			var params = jQuery("#tundra-cart .cart-form").serialize();
			jQuery.ajax({
			        url: baseURL+"checkout/cart/updatePost",
			        type: 'POST',
			        cache: false,
			        data: params,
			        success: function(data) {
			        	var htm = jQuery(data).find('.cart').eq(1);
			        	var isCheckout = false;
			        	//check if on checkout page and no items in cart and redirect
			        	if(window.location.href.indexOf('checkout/onepage') != -1 && htm.find('.empty-cart').length>0)
			        	{
			        		isCheckout = true;
			        		window.location = baseURL;
			        	}
			        	if(htm.length > 0)
			        	{
									jQuery('#tundra-cart .cart').replaceWith(htm);
			        	} else
			        	{
				        	jQuery('#tundra-cart .cart').replaceWith('<div class="cart" style="display: block; margin-top: 0px; "><div class="page-title title-buttons"><ul class="checkout-types"></ul></div><div class="empty-cart">Your Cart is Empty</div><div class="cart-collaterals"></div></div>');

			        	}
		        	
			        	if(window.location.href.indexOf('checkout/onepage') != -1)
			        	{
			        		isCheckout = true;
			        	}

								//add shipping (if any) to tfoot of table
								if(isCheckout)
								{
									if(jQuery('#tundra-cart .shipping').length == 0)
									{
										jQuery('#tundra-cart .cart tfoot tr').eq(1).after("<tr class='shipping'><th colspan='2'>Shipping</th><th style='text-align:right;' colspan='2'><span class='price'>TBD</span></th></tr>");	
									}
									if(shippingRate != "")
									{
										jQuery('#tundra-cart .cart tfoot tr.shipping th').eq(1).html(shippingRate);
										setShippingOptions(true);
									}
									jQuery('#tundra-cart .shipping').show();	
								}
								jQuery('#tundra-cart .update-row').append('<span class="updated">Cart Updated</span>');
								jQuery('#tundra-cart .update-row .updated').delay(300).fadeOut();
								//reattach events to new data
								resetCart(true);
								//reattach coupon code
								setCoupon();
			        }
			      });
			return false;
		})	
}

function setCoupon()
{
	//if IE7 don't use fancybox
	var isIE7 = false;

	if(jQuery.browser.msie && jQuery.browser.version == "7.0")
	{
		isIE7 = true;
	}
	//isIE7 = true;
	if(isIE7) {
		jQuery('#tundra-cart .btn-coupon-code').click(function() {
			jQuery('#coupon-content').parent().parent().css('overflow','visible');
			jQuery('#coupon-content').parent().show();
			jQuery('#coupon-content').append('<div class="close-but"></div>');
			jQuery('#coupon-content .close-but').click(function() {
				jQuery(this).parent().parent().hide();
				jQuery(this).remove();
				jQuery('#coupon-content').parent().parent().css('overflow','hidden');
			})
			setCouponForm();
			return false;
		})
	} else
	{
		//set up fancybox for coupon code entering in
		jQuery('#tundra-cart .btn-coupon-code').fancybox({
			'width':600,
			'padding':0,
			'margin':0,
			'titleShow':false,
			'onComplete':function() {
				setCouponForm();
				jQuery('#fancybox-content div').css('overflow','visible');
			}
		})
	}
}

function setCouponForm()
{
	//button to update coupon code
	//remove binding that is applied by fancybox by default for forms
	jQuery('#coupon-content .btn-coupon-code').unbind();
	jQuery('#coupon-content .btn-coupon-code').click(function() {

		jQuery('#coupon-content .coupon-code-status').text("Please wait, applying code...");
		var params = {
			'coupon_code':jQuery('#fancybox-wrap #coupon_code').val()
		}
		jQuery.ajax({
			url: baseURL+"scripts/checkCoupon.php",
			type: 'POST',
			data: params,
			success: function(out) {
				var data = eval("("+out+")");
				if(data.error)
				{
					alert(data.error);
					jQuery('#coupon-content .coupon-code-status').text('');
				} else
				{
					//apply coupon code text 
					jQuery('#coupon-content .coupon-code-status').text(data.success);
					//apply coupon code to the cart
					//get shipping amount and add to total
					var sh = jQuery('#tundra-cart .cart-shipping .price').text().split('$')[1];
					if(isNaN(Number(sh)))
					{
						sh = 0;
					}
					var t = Number(data.total)+Number(sh);
					jQuery('#tundra-cart .cart-total .price').text("$"+t.toFixed(2));

					//now change discount in cart
					var d = Number(data.discount);
					jQuery('#tundra-cart .discount-row .price').text('$'+d.toFixed(2));
					jQuery('#tundra-cart .discount-row').show();

				}
			}
		});
		return false;
	})

	
}

var currentShippingValue;
var shippingRequest;
function setShippingOptions()
{
	jQuery('#tundra-checkout .shipping-type').replaceWith('<span class="shipping-type shipping-type-loading">Please Wait, Loading Shipping Options...</span>');
	jQuery('#tundra-checkout .shipping-type-loading').css('display','block');

	//abort any previous
	if(shippingRequest)
	{
		shippingRequest.abort();
	}
		var params = jQuery("#tundra-checkout form").serialize();
		shippingRequest = jQuery.ajax({
		        url: baseURL+"scripts/getShippingOptions.php",
		        type: 'POST',
		        data: params,
		        success: function(data) {
		        	var d = eval("("+data+")");
		        	if(d.error)
		        	{
		        		jQuery('#tundra-checkout .shipping-type').replaceWith("<span class='shipping-type'>"+d.message+"</span>");
		        	} else
		        	{
			        	var selectForm = "<select class='shipping-type' name='shipping_type'>";
			        	for(var rate in d.rates)
			        	{
			        		selectForm += "<option value='"+rate+"'>"+rate.split('_')[1]+" - "+d.rates[rate]+"</option>";
			        		if(currentShippingValue == rate)
			        		{
			        			shippingRate = d.rates[rate];
			        		}
			        	}
			        	selectForm += "</select>";

								jQuery('#tundra-checkout .shipping-type').unbind();
			        	jQuery('#tundra-checkout .shipping-type').replaceWith(selectForm);

			        	//set old value if one
			        	if(currentShippingValue != undefined)
			        	{
			        		jQuery('#tundra-checkout .shipping-type').val(currentShippingValue);
			        	} else
			        	{
				        	shippingRate = d.default_shipping_price;
			        	}
			        	//add tax if one
			        	jQuery('#tundra-cart .cart-tax .tax-value').html(d.tax);
			        	jQuery('#tundra-cart .cart-total').html(d.grand_total);

			        	//var tV = jQuery('#tundra-cart .tax-row .price').text().split('$')[1];
			        	var gT = jQuery('#tundra-cart .cart-total .price').text().split('$')[1];
			        	gT = Number(gT);
			        	jQuery('#tundra-cart .cart-total .price').text('$'+gT.toFixed(2));

			        	if(Math.round(jQuery('#tundra-cart .tax-row .price').text().split('$')[1]) != 0)
			        	{
				        	jQuery('#tundra-cart .tax-row').show();
			        	} else
			        	{
				        	jQuery('#tundra-cart .tax-row').hide();
			        	}
		        	


								//set up cart changing
								jQuery('#tundra-checkout .shipping-type').change(function() {
									//set value in cart
							  	//also change shipping amount in cart and total
							  	var nSP = jQuery(this).find('option:selected').text().split('$')[1];
							  	var oSP = jQuery('#tundra-cart .cart-shipping .price').text().split('$')[1];
							  	var tV = jQuery('#tundra-cart .tax-row .price').text().split('$')[1];
							  	jQuery('#tundra-cart .cart-shipping .price').text('$'+nSP);
							  	var oT = jQuery('#tundra-cart .cart-total .price').text().split('$')[1];
							  	var nT = Number(oT)-Number(oSP)+Number(nSP)+Number(tV);
							  	nT = Math.round(nT*100)/100;
							  	jQuery('#tundra-cart .cart-total .price').text('$'+nT.toFixed(2));

									//set current value globally
									currentShippingValue = jQuery(this).val();
								})
			        	//also change shipping amount in cart and total
			        	jQuery('#tundra-cart .cart-shipping').html(shippingRate);
								jQuery('#tundra-checkout .shipping-type').trigger('change');

		        	}
		        }
		      });
}



////////// RESIZING ///////////

//resizing
function resizeModels()
{
	if(numModels)
	{
		var w = Math.max(jQuery(window).width(),1150);
		jQuery('#hat-models').width(w*numModels);
		jQuery('.hat-model').width(w);	
		var img;
		var hatWidth = 0;
		jQuery('.hat-image').each(function() {
			img = jQuery(this).find('.models-hat');
			imgW = w;
			if(img.length >0)
			{
				imgW = img.width();
			}
			var imgW = Math.max(w,imgW);
			jQuery(this).width(imgW);
			hatWidth+=imgW;
		})
		jQuery('#hat-images').width(hatWidth);
		jQuery('#hat-options').width(Math.ceil(w/2-60));
		jQuery('#hat-options-left').width(jQuery('#hat-options').width()-jQuery('#hat-options-right').width());
		jQuery('#hat-options-background').width(jQuery('#hat-options-left').width()+423);

		//for pins
		jQuery('.pin-container').css({
			'width':w,
			'left':472-w/2
		})
		pinOffset = -1*parseInt(jQuery('.pin-container').css('left'));
		jQuery('.pin-container dd').css({
			'margin-left':pinOffset
		})

		//for product thumbs
		jQuery('#product-thumbs').css({
			'left':w/2-471
		})

		//for hat models
		jQuery('#hat-models-holder').height(jQuery('body').height()-161);

		//contact
		jQuery('#contact-slider .contact-text').css(
		{
			'right':w/2-492
		})
	}
	
}


jQuery(window).resize(function() {
	resizeModels();
});

//call to initially size models
resizeModels();


////////////// IMAGE LOADING ///////////

function loadModelImage(i)
{
	if(i==1)
	{
		jQuery('#model-arrows').css('visibility','visible').hide().fadeIn('fast',function() {
			//show arrow buttons and then fade out pinks
			jQuery(this).find('#model-prev').show();
			jQuery(this).find('#model-next').show();
			//now fade out pink
			jQuery(this).find('#model-prev-pink').delay(1000).fadeOut(500);
			jQuery(this).find('#model-next-pink').delay(1000).fadeOut(500);
			
		});
	}
	var ldr = jQuery('<div/>').addClass('hat-model hat-model-'+i).appendTo('#hat-models');
	ldr = jQuery('<div/>').addClass('model-image').appendTo(ldr);
	jQuery('<div/>').addClass('hat-image hat-image-'+i).appendTo(jQuery('#hat-images'));
	jQuery('<img/>').addClass('models-hat').appendTo(jQuery('#hat-images .hat-image').eq(i));
	jQuery('<img/>').addClass('models-pin').appendTo(jQuery('#hat-images .hat-image').eq(i));
	resizeModels();
	totModels = modelsURLAR.length;
	if(i == totModels)
	{
		return;
	}
	var uri = modelsURLAR[i];
	modelImages['image'+i] = new Image();
	jQuery(modelImages['image'+i])
   // once the image has loaded, execute this code
   .load(function () {
     // with the holding div #loader, apply:
     ldr
       // then insert our image
			.append(this)
		//hide modelImages initially
		if(i == curImage)
		{
			jQuery(this).parent().hide();
	     // fade our image in to create a nice effect
	    jQuery(this).parent().fadeIn('slow');
		} 
		//increase index of image
		curLoadedModel = String(modelsNameAR[i]);
		i++;
		curModelLoadInd = i;
		//load corresponding hats for models
		if(curColor == "")
		{
			loadDesatHat(i);
		} else
		{
			loadModelHat(0);	
		}
   })
	  // *finally*, set the src attribute of the new image to our image
	  .attr('src', uri).attr('alt',modelsNameAR[i]);
}

function loadDesatHat(i)
{
	var uri = modelsHatsJSON['desat_hat_'+curLoadedModel.replace(/ /g,'_')];
	var ldr = jQuery('<div/>').appendTo(jQuery('#hat-cache'));
	desatHatImages['image'+i] = new Image();
	jQuery(desatHatImages['image'+i])
		.load(function () {
			ldr
			.append(this)
			setHatColor(true);
			loadModelHat(0);
	})
	  .attr('src', uri);
}

function loadModelHat(i)
{
	var col = String(colorsAR[i]).replace(/ /g,'_').toLowerCase();
	var uri = modelsHatsJSON[col+'_hat_'+curLoadedModel.replace(/ /g,'_')];
	while(uri == undefined && i<totColors-1)
	{
		col = String(colorsAR[i]).replace(/ /g,'_').toLowerCase();
		i++;
		uri = modelsHatsJSON[col+'_hat_'+curLoadedModel.replace(/ /g,'_')];
	}
	if(uri == undefined && curModelLoadInd<totModels)
	{
		loadModelImage(curModelLoadInd);
		return;
	} else
	{				
		var ldr = jQuery('<div/>').appendTo(jQuery('#hat-cache'));
	}
	hatImages['image'+i] = new Image();
	jQuery(hatImages['image'+i])
   // once the image has loaded, execute this code
   .load(function () {
     // with the holding div #loader, apply:
     ldr
       // then insert our image
			.append(this)
			jQuery(this).parent().hide();
	     // fade our image in to create a nice effect
	    /*jQuery(this).parent().fadeIn('slow',function() {

			});*/
		//increase index of image
		i++;
		//see if initial color is this color hat
		if(curColor && curColor.replace(/ /g,'_').toLowerCase() == col)
		{
			setHatColor();
			setPin();
		} else if(curColor == "")
		{
			setHatColor(true);
		}
		if(i<totColors)
		{
			//load corresponding hats for models
			loadModelHat(i);
		} else if(curModelLoadInd<totModels)
		{
			loadModelImage(curModelLoadInd);
		}
   })
	  // *finally*, set the src attribute of the new image to our image
	  .attr('src', uri);
}


function loadSnowboardHat(i)
{
	isLoadingSnowboardImages = true;
	var lbl = snowboardColorsAR[i][0];
	var uri = snowHatThumbsJSON['color_'+snowboardColorsAR[i][1]].image_1;
	var ldr = jQuery('<div rel="'+lbl+'"/>').appendTo(jQuery('#snowboard-cache'));
	otherImages['image'+i] = new Image();
	jQuery(otherImages['image'+i])
   // once the image has loaded, execute this code
   .load(function () {
     // with the holding div #loader, apply:
     ldr
       // then insert our image
			.append(this)
			jQuery(this).parent().hide();
	     // fade our image in to create a nice effect
	    /*jQuery(this).parent().fadeIn('slow',function() {

			});*/
		//increase index of image
		i++;
		if(i<totSnowboardColors)
		{
			//load corresponding hats for models
			loadSnowboardHat(i);
		} else 
		{
			//show snowboard image correspoinding to cur color
			jQuery('#other-products').empty();
			jQuery('#snowboard-cache div[rel="'+curColor+'"] img').clone().appendTo(jQuery('#other-products'));
			isDoneLoadingSnowboard = true;
		}
   })
	  // *finally*, set the src attribute of the new image to our image
	  .attr('src', uri);
}

function loadSimpleProductImage(url)
{
	url = baseURL+'scripts/timthumb.php?src='+url+"&h=600";

	var $oP = jQuery('#other-products');
	$oP.show();
	var ldr = jQuery('#snowboard-cache');
	otherImages['image'] = new Image();
	jQuery(otherImages['image'])
	.load(function() {
		ldr
		.append(this)
		$oP.empty();
		$oP.append(jQuery(this));
	}).attr('src',url);
}

//c is for desat initial load
function setHatColor(c)
{
	var col;
	var isDesat = false;
	if(c) {
		col = 'desat';
		isDesat = true;
	} else
	{
		//col is text color value, colorVal is val (index) of dropdown
		col = curColor.replace(/ /g,'_').toLowerCase();	
	}
	//remove all thumb images for hats
	jQuery('#product-thumbs .hat-thumb img').each(function() {
		jQuery(this).parent().parent().css('border','none');
		jQuery(this).remove();
	})
	if(colorVal || isDesat)
	{
		//i is the offset of starting point of alternate views
		//different for snowboard vs tundra
		if(isSnowboard && snowHatThumbsJSON["color_"+colorVal])
		{
			var i = 2;
			jQuery('.hat-thumb').each(function() {
				if(jQuery(this).find('img').length == 0)
				{
					jQuery(this).find('a').append('<img/>');
				}
				jQuery(this).find('img').attr('src',baseURL+'scripts/timthumb.php?src='+snowHatThumbsJSON["color_"+colorVal]["image_"+i]+"&h=54&w=54");
				jQuery(this).find('a').attr('href',snowHatThumbsJSON["color_"+colorVal]["image_"+i]);
				jQuery(this).css('border','1px solid #999');
				i++;
			});	
			jQuery('#product-thumbs').fadeTo(500,1);
		} else if(hatThumbsJSON["color_"+colorVal])
		{
			var i = 1;
			jQuery('.hat-thumb').each(function() {
				if(jQuery(this).find('img').length == 0)
				{
					jQuery(this).find('a').append('<img/>');
				}
				jQuery(this).find('img').attr('src',baseURL+'scripts/timthumb.php?src='+hatThumbsJSON["color_"+colorVal]["image_"+i]+"&h=54&w=54");
				jQuery(this).find('a').attr('href',hatThumbsJSON["color_"+colorVal]["image_"+i]);
				jQuery(this).css('border','1px solid #999');
				i++;
			});	
			jQuery('#product-thumbs').fadeTo(500,1);
		}

		//change all hats on currently shown models
		var i = 0;
		jQuery('#hat-models').find('.hat-model').each(function() {
			var mod = "";
			if(jQuery(this).find('.model-image img').attr('alt'))
			{
				var mod = jQuery(this).find('.model-image img').attr('alt').replace(/ /g,'_');	
			}
			var $hI = jQuery('#hat-images .hat-image').eq(i);
			if($hI.find('.models-hat').length == 0)
			{
				$hI.prepend('<img class="models-hat"/>');
			} 
			var url;
			if(isDesat)
			{
				url = desatHatsJSON[col+'_hat_'+mod];
			} else
			{
				url = modelsHatsJSON[col+'_hat_'+mod];	
			}
			if(url)
			{
				if(!isDesat)
				{
					//add img above and then remove
					$hI.append('<img class="models-hat"/>');
					var $lI = $hI.find('.models-hat:last');
					$lI.attr('src',url);
					$lI.hide();
					$lI.fadeIn('slow',function() {
						$hI.find('.models-hat:first').remove();
					});
				} else
				{
					if($hI.find('.models-hat:last').attr('src') != url)
					{
						$hI.fadeTo(0,0);
						$hI.find('.models-hat:last').attr('src',url);
						$hI.fadeTo(300,1);
					}
				}
			}
			i++;
		})
	}
}

function setPin(isD)
{
	if(isD)
	{
		jQuery('.models-pin').css('display','none');
	} 
		
		//remove all thumb images for pins thumbs
	jQuery('#product-thumbs .pin-thumb a img').each(function() {
		jQuery(this).parent().parent().css('border','none');
		jQuery(this).remove();
	})

	if(isD)
	{
		return;
	}
	//col is text color value, colorVal is val (index) of dropdown
	if(pinVal)
	{
		if(pinThumbsJSON["color_"+pinVal])
		{
			var i = 1;
			jQuery('.pin-thumb').each(function() {
				if(i>1)
				{
					
				} else
				{
					if(jQuery(this).find('img').length == 0)
					{
						jQuery(this).find('a').append('<img/>');
					}
					if(pinThumbsJSON["color_"+pinVal]["image_"+i] != undefined)
					{
						jQuery(this).find('img').attr('src',baseURL+'scripts/timthumb.php?src='+pinThumbsJSON["color_"+pinVal]["image_"+i]+"&h=54&w=54");
						jQuery(this).find('a').attr('href',pinThumbsJSON["color_"+pinVal]["image_"+i]);	
						jQuery(this).css('border','1px solid #999');
					}
				}
					
				i++;
			});	
			jQuery('#product-thumbs').fadeTo(500,1);
		}


		//change all pins on currently shown models
		if(pinsJSON[curPin])
		{
			jQuery('#hat-images').find('.hat-image').each(function() {
				if(jQuery(this).find('.models-pin').length == 0)
				{
					jQuery(this).find('.models-hat').after('<img class="models-pin"/>');
				}
				jQuery(this).find('.models-pin').attr('src',baseURL+'scripts/timthumb.php?src='+pinsJSON[curPin].image_url+"&h=150");
				jQuery(this).find('.models-pin').css('display','block');
			})
		}
	}	
}
