$(document).ready(function() {
	/*THUMBNAIL NAVIGATION*/
	var thumbBox = $('#thumbNav .box');
	var thumbLink = $('#thumbNav a');
	var navThumb = $('#thumbNav img');
	var navBar = $('#thumbNav .bar');
	var thumbShadow = $('#thumbNav .shadow');
	
	/*CART CHECKOUT*/
	var cartBtn = $('.cartBtn');
	var cartFrame = $('#cart .frame');	
	
	/*FEEDBACK*/
	var feedback = $('#feedback');
	var feedbackRight = $('#feedback .right');
	var feedbackBtn = $('#feedback .left a');
	var feedForm = $('#feedback form');
	var feedSubmit = $('#feedback .button');
	var feedMsg = $('#feedback .message');
	var feedState = false;
	
	/*SKU*/
	var prodZoom = $('#prodDFoot .clickZoom');
	var prodZoomOut = $('#prodDetail .exitZoom');
	var prodZoomOutContainer = $('#prodDetail .zoom_exit_container');
	var prodImg = $('#prodDetail .mainImg');
	var prodRow = $('#prodDR');
	var prodFoot = $('#prodDFoot');
	var prodFootLeft = $('#prodDFoot .left a');
	var prodMore = $('#prodDFoot .moreImg');
	var prodThumb = $('#prodThumbs');
	var prodThumbLink = $('#prodThumbs .thumbs a');
	var prodThumbClose = $('#prodThumbs .close');
	
 	var all_images = [];
 	function do_preload() {
	 	jQuery('a.clickZoom').each(function() {
	 		var href = jQuery(this).attr('href');
	 		var img = new Image();
	 		img.src = href;
	 		all_images.push(img);
	 	});
	 	var img = new Image();
	 	img.src = "images/x_thumb_wrap.png";
	 	all_images.push(img);
	}
	do_preload();
	
	
	/*THUMBNAIL NAVIGATION*/
	$(thumbBox).hover(
	  function () {
		 var x = $(this).index();
		 $(thumbLink).eq(x).css({'color' : '#FFF'});
		 $(navThumb).eq(x).css({'left' : '235px','display':'block'}); 
		 $(navBar).eq(x).css({'left' : '-8px','display':'block'});
		 $(thumbShadow).eq(x).css({'left' : '235px','display':'block'});
	
	  }, 
	  function () {
		 var x = $(this).index();
		 $(thumbLink).eq(x).css({'color' : '#878888'});
		 $(navThumb).eq(x).css({'left' : '-300px','display':'none'});
		 $(navBar).eq(x).css({'left' : '-300px','display':'none'});
		 $(thumbShadow).eq(x).css({'left' : '-300px','display':'none'});
	  }
	);
	
  /*FEEDBACK*/
    $(feedbackBtn).click(function(e){
		e.preventDefault();
		
		if(feedState == false){
			if ($.browser.msie && $.browser.version.substr(0,1)<7) {
				$('body').css('overflow-x', 'hidden');
				$(feedback).css({'width':'490px','right':'-420px'})
				$(feedbackRight).css({'display':'block'});
				$(feedback).animate({
					right:"-20px"
				},
				800,
				function(){
					feedState = true
				});
			 }else{
				$('body').css('overflow-x', 'hidden');
				$(feedback).css({'width':'460px','right':'-420px'})
				$(feedbackRight).css({'display':'block'});
				$(feedback).animate({
					right:"0"
				},
				800,
				function(){
					feedState = true
				});
			 }
		}else{
			$(feedback).animate({
				right:"-420px"
			},
			800,
			function(){
				$(feedback).css({'width':'40px','right':'0'})
			    $(feedbackRight).css({'display':'none'});
				$('body').css('overflow-x', 'auto');
				feedState = false
			});
		}
	});
	$(feedSubmit).click(function(e){
		e.preventDefault();
		$(feedForm).css({"display":"none"});
		$(feedMsg).css({"display":"block"});
	});
  
    /*CUSTOMIZED COMBOBOX*/
	$(".combobox").msDropDown({mainCSS:'dd2'});
	$(".combobox2").msDropDown({mainCSS:'dd3'});
	
	
	/*SKU*/
	$(prodZoom).click(function(e){
		var imgSrc = $(this).attr('href');
		e.preventDefault();
		$(prodImg).attr('src','');
		$(prodImg).attr('src',imgSrc);
		$(prodRow).css({'display':'none'});
		$(prodFoot).css({'display':'none'});
		$(prodZoomOut).css({'display':'block'});
		$(prodZoomOutContainer).css({'display':'block'});
		image_pan.start(prodImg);
	});
	
	$(prodZoomOut).click(function(e){
		var imgSrc = $(this).attr('href');
		e.preventDefault();
		$(prodImg).attr('src',imgSrc);
		$(prodRow).css({'display':'block'});
		$(prodFoot).css({'display':'block'});
		$(prodZoomOutContainer).css({'display':'none'});
		$(this).css({'display':'none'});
		image_pan.stop();
	});
    $(prodThumbLink).click(function(e){
		var imgSrc = $(this).attr('href');
		e.preventDefault();
		$(prodImg).attr('src',imgSrc);
		$(prodZoomOut).attr('href', imgSrc);
		
		$(prodZoom).attr('href', $(this).attr('data-zoom'));
		do_preload();
	});
	$(prodMore).click(function(e){
		e.preventDefault();
		$(prodFootLeft).css({'display':'none'});
		$(prodThumb).css({'display':'block'});
	});
	$(prodThumbClose).click(function(e){
		e.preventDefault();
		$(prodThumb).css({'display':'none'});
		$(prodFootLeft).css({'display':'block'});
	});
	
	slideshow();
	
	if ($.browser.webkit) {
    	$('#sort .dd2 .ddTitle').css({'width':'107px'});
  	}
	
	if ($.browser.msie && $.browser.version.substr(0,1)<8) {
		$(":checkbox").click(function(e){
				$( this ).parent().parent().find(".addMsg").toggle();
				$( this ).parent().parent().parent().find(".giftP").toggle();
			});
	 }
	
	
	jQuery('span.gift_wrap').hover(
		function() {
			var pos = jQuery(this).offset();
			pos.top += 20;
			var gift_wrap_img = jQuery('<img id="gift_wrap_img" src="/images/x_thumb_wrap.png" style="position: absolute; top: ' + pos.top + 'px; left: ' + pos.left + 'px" />');
			jQuery('body').append(gift_wrap_img);
		}, function() {
			jQuery('#gift_wrap_img').remove();
		}
	);
});

var slideshow_paused = false;

function slideshow(){
	var totalSeconds = 5;
	var second = 0;
	var milliSecond = 0;
	var progress = 0;
	var totalFires = totalSeconds * 30;
	var slideNum = 0;
	var pause = false;
	var pauseTime = 0;
	var restack = false;
	var container = $('#slideshow');
	var slideshow = $('#slideshow .slide');
	var numberOfSlides = slideshow.length;
	var bullets = $('<div class="bullets"></div>');
	var time = 6000;
	
	//If slideshow has more than 1 slide then build show
	if (numberOfSlides > 1){
		//Create bullets
		$(slideshow).each(function(i){
			
			$(this).css({
				'z-index' : 0
			});
			$(bullets).append('<div class="thumb"><img src="'+ $(this).find('.thumb').attr("src") +'" /><div class="slug"></div><div class="shadow"></div><a href="#">' + (i+1) + '</a></div>');
			$(this)
				.hover(function(){
				  $(this).find('.top').css({"top":"0"});
				}, function(){
				  $(this).find('.top').css({"top":"-629px"});
				});
			
		});
		
		
		// Set default positions of first and second slide
		$(slideshow).eq(0).css({'z-index' : 2});
		$(slideshow).eq(1).css({'z-index' : 1});
		
		// Load container with bullet nav
		$(container)
			.append(bullets);
		
		// Add current class to first bullet
		currentBullet(slideNum);
		
		// Add functionality to navigation links
		
		$('.bullets a')
			  .hover(function(){
					var linkPosition = $(this).position();
					
			    	$(this).parent().find("img").css({"display":"block","left": linkPosition.left - ($(this).parent().find("img").width() / 2) + "px"}).stop().animate({opacity: 1}, 500);
					$(this).parent().find(".shadow").css({"display":"block","left": linkPosition.left - ($(this).parent().find("img").width() / 2) + "px"}).stop().animate({opacity: 1}, 500);
					$(this).parent().find(".slug").css({"display":"block"}).stop().animate({opacity: 1}, 500);
					slideshow_paused = true;
				}, function(){
					$(this).parent().find("img").stop().animate({opacity: 0}, 500);
					$(this).parent().find(".shadow").stop().animate({opacity: 0}, 500);
					$(this).parent().find(".slug").stop().animate({opacity: 0}, 500);
					slideshow_paused = false;
				});
			
		$('.bullets a')
			.click(function(e){
				e.preventDefault();
				if ($(slideshow).is(":animated")){
					return;
				}else{
					
					var linkName = $(this).html();
					arrangeNavStack(linkName);
					pauseTime = 0;
					
				    if(!pause){
					  pause = true;
					  startClock();
					  waitAndPlay(); 
				    }else{
					  return;  
				    } 
				}
				
			});
		
		setTimeout(function() {startClock();},time)
	};
	
	// Add class to current bullet
	function currentBullet(bulletNum){
		$('.bullets a').removeClass('current');
		$('.bullets a').eq(bulletNum).addClass('current');
	}
	
	// Previous Slide
	function prevSlide(){
		if(slideNum == 0){
			var slideName = $(slideshow).eq(numberOfSlides - 1).attr('name');
			currentBullet(numberOfSlides - 1);
			//comment(slideName);
		}else{
			var slideName = $(slideshow).eq(slideNum - 1).attr('name');
			currentBullet(slideNum - 1);
			//comment(slideName);
		}
		
		$(slideshow).eq(slideNum).fadeOut(function(){
			if(slideNum == 0){
				slideNum = numberOfSlides - 1;
				$(slideshow).eq(slideNum).css({'z-index': 2});
				$(slideshow).eq(slideNum - 1).css({'z-index': 1});
			}else if(slideNum == 1){
				--slideNum;
				$(slideshow).eq(slideNum).css({'z-index': 2});
				$(slideshow).eq(numberOfSlides - 1).css({'z-index': 1});
			}else{
				--slideNum;
				$(slideshow).eq(slideNum).css({'z-index': 2});
				$(slideshow).eq(slideNum - 1).css({'z-index': 1});	
			}
			$(this).show().css({'z-index' : 0});
		});
	}
	
	// Next Slide
	function nextSlide(){
		if(slideNum == numberOfSlides - 1){
			var slideName = $(slideshow).eq(0).attr('name');
			currentBullet(0);
			//comment(slideName);
		}else{
			var slideName = $(slideshow).eq(slideNum + 1).attr('name');
			currentBullet(slideNum + 1);
			//comment(slideName);
		}
			
		$(slideshow).eq(slideNum).fadeOut(function(){	
			if(slideNum == numberOfSlides - 1){
				slideNum = 0;
				$(slideshow).eq(0).css({'z-index': 2});
				$(slideshow).eq(1).css({'z-index': 1});
			}else if(slideNum == numberOfSlides - 2){
					++slideNum;
				$(slideshow).eq(slideNum).css({'z-index': 2});
				$(slideshow).eq(0).css({'z-index': 1});
			}else{
				++slideNum;
				$(slideshow).eq(slideNum).css({'z-index': 2});
				$(slideshow).eq(slideNum + 1).css({'z-index': 1});	
			}
			$(this).show().css({'z-index' : 0});
		});
	}
	
	// Arrange navigation Stack
	function arrangeNavStack(linkName){
		restack = true;
		
		$(slideshow).each(function(i){
			$(this).css({
				'z-index' : 0
			});
		});
		
		if(linkName == 'next'){
			if(slideNum == 0){
				$(slideshow).eq(0).css({'z-index' : 2});
				$(slideshow).eq(1).css({'z-index' : 1});
			}else if(slideNum == numberOfSlides - 1){
				$(slideshow).eq(slideNum).css({'z-index' : 2});
				$(slideshow).eq(0).css({'z-index' : 1});
			}else{
				$(slideshow).eq(slideNum).css({'z-index' : 2});
				$(slideshow).eq(slideNum + 1).css({'z-index' : 1});
			}
			nextSlide()
		}else if(linkName == 'prev'){
			if(slideNum == 0){
				$(slideshow).eq(0).css({'z-index' : 2});
				$(slideshow).eq(numberOfSlides - 1).css({'z-index' : 1});
			}else if(slideNum == numberOfSlides - 1){
				$(slideshow).eq(slideNum).css({'z-index' : 2});
				$(slideshow).eq(slideNum - 1).css({'z-index' : 1});
			}else{
				$(slideshow).eq(slideNum).css({'z-index' : 2});
				$(slideshow).eq(slideNum - 1).css({'z-index' : 1});
			}
			prevSlide();
		}else{
			var slideName = $(slideshow).eq(linkName - 1).attr('name')
			if((linkName - 1) == 0){
				$(slideshow).eq(0).css({'z-index' : 2});
				$(slideshow).eq(1).css({'z-index' : 1});
			}else if((linkName - 1) == numberOfSlides - 1){
				$(slideshow).eq(linkName - 1).css({'z-index' : 2});
				$(slideshow).eq(0).css({'z-index' : 1});
			}else{
				$(slideshow).eq(linkName - 1).css({'z-index' : 2});
				$(slideshow).eq(linkName).css({'z-index' : 1});
			}
			slideNum = linkName - 1;
			currentBullet(linkName - 1)
			//comment(slideName);
		}
	}
	
	// ENGINE
	function engine (currentSlide){	
		$(slideshow).eq(currentSlide).fadeOut(function(){
			if(currentSlide == numberOfSlides - 2){
				++slideNum;
				$(slideshow).eq(currentSlide + 1).css({'z-index': 2});
				$(slideshow).eq(0).css({'z-index': 1});
			}else if(currentSlide == numberOfSlides - 1){
				slideNum = 0;
				$(slideshow).eq(0).css({'z-index': 2});
				$(slideshow).eq(1).css({'z-index': 1});
			}else{
				++slideNum;
				$(slideshow).eq(currentSlide + 1).css({'z-index': 2});
				$(slideshow).eq(currentSlide + 2).css({'z-index': 1});
			}
			$(this).show().css({'z-index' : 0});
		});
				
	};
	
	function ignite(){
		if(restack){
				restack = false;
				$(slideshow).each(function(i){
					$(this).css({
						'z-index' : 0
					});
				});
				if(slideNum == 0){
					$(slideshow).eq(0).css({'z-index' : 2});
					$(slideshow).eq(1).css({'z-index' : 1});
				}else if(slideNum == numberOfSlides - 1){
					$(slideshow).eq(slideNum).css({'z-index' : 2});
					$(slideshow).eq(0).css({'z-index' : 1});
				}else{
					$(slideshow).eq(slideNum).css({'z-index' : 2});
					$(slideshow).eq(slideNum + 1).css({'z-index' : 1});
				}
			}
			
		if(slideNum == numberOfSlides - 1){
			var slideName = $(slideshow).eq(0).attr('name');
			currentBullet(0);
			//comment(slideName);
		}else{
			var slideName = $(slideshow).eq(slideNum + 1).attr('name');
			currentBullet(slideNum + 1);
			//comment(slideName);
		}	
		engine(slideNum);
		
	}
	
	//WAIT AND PLAY
	function waitAndPlay(){
			if(pause && pauseTime <= 3){
				++pauseTime
				setTimeout(function() {waitAndPlay();},1000)
			}else if(!pause){
				return;
			}else{
				pause = false;
				startClock();	
			}
		}
		
	//CLOCK
		function startClock(){
		  if(!pause){
			if (!slideshow_paused) ignite();
			setTimeout(function() {startClock();},time)
		  }else{
			return;
		  }		
		}; 
	
};

/* begin dropdown cart */
var dropdown_cart = {
	quantity_sel: '#lbl_cart_quantity',
	table_sel: '#cartTbl_body',
	data: {},
	showing: false,
	
	update_display: function() {
		//updates the data and displays the cart
		this.load_data(dropdown_cart.update_display_callback);
	},
	
	update_display_callback: function() {
		dropdown_cart.refresh();
		dropdown_cart.autohide = true;
		dropdown_cart.show(true);

		setTimeout('dropdown_cart.do_autohide()', 3000);
	},
	
	do_autohide: function() {
		if (dropdown_cart.autohide) {
			dropdown_cart.show(false);
		}
	},
	
	show: function(bshow) {
		if (bshow && !dropdown_cart.showing) {
			dropdown_cart.showing = true;
			$('#cart .frame').stop().attr('style','display: none').slideDown("slow");
		} else if (!bshow && dropdown_cart.showing) {
			dropdown_cart.showing = false;
			$('#cart .frame').stop().slideUp("slow");
		}
	},
	
	setup: function() {
		//checkout button hook
		jQuery('#btn_checkout').click(function() {
			location.href = "checkout";
		});
		
		jQuery('#cart').hover(
			function(){
				dropdown_cart.autohide = false;
				dropdown_cart.show(true);
			},
			function(){
				dropdown_cart.show(false);
			}
		);		
		
		//load data and update
		this.load_data(dropdown_cart.refresh);
	},
	
	refresh: function() {
		var data = dropdown_cart.data;
		
		//update quantity label
		if (data.products)
			var item_count = data.products.length;
		else
			var item_count = 0;
			
		if (item_count == 1) {
			var quantity_label = "<span>1</span> Item in your Shopping Bag";
		} else {
			var quantity_label = "<span>" + item_count + "</span> Items in your Shopping Bag";
		}
		jQuery(dropdown_cart.quantity_sel).html(quantity_label);
		
		//update product table
		var output = "";
		
		var subtotal = 0;
		
		if (data.products) {
			for(var i=0; i<data.products.length; i++) {
				var id = data.products[i].id;
				var name = data.products[i].attributes.name;
				var quantity = 0;
				//find quantity
				for(var j=0; j<data.cart.length; j++) {
					if (data.cart[j].id == id) {
						quantity = data.cart[j].quantity;
						break;
					}
				}
				var cost = data.products[i].attributes._price * quantity;
				subtotal += cost;
				output += dropdown_cart.make_product_row(id, name, quantity, cost);
			}
		}
		
		output += dropdown_cart.make_subtotal_row(subtotal);
		
		if (item_count > 0) {
			jQuery('#btn_checkout').show();
		} else {
			jQuery('#btn_checkout').hide();			
		}
		
		jQuery(dropdown_cart.table_sel).html(output);
	},
	
	load_data: function(callback) {
		var url = "cart/ajax/get";
		
		jQuery.get(url, function(data) {
			dropdown_cart.data = jQuery.parseJSON(data);
			if (jQuery.isFunction(callback)) {
				callback();
			}			
		});
	},
	
	remove_item: function(id) {
		var url = "cart/ajax/update/" + id + "/0";
		
		jQuery.get(url, function() {
			dropdown_cart.load_data(dropdown_cart.refresh);
		});
	},
	
	update: function(id) {
		var quantity = parseInt(jQuery('#quantity_' + id).val());
		
		var url = "cart/ajax/update/" + id + "/" + quantity;
		
		jQuery.get(url, function() {
			dropdown_cart.load_data(dropdown_cart.refresh);
		});
	},
	
	make_product_row: function(id, name, quantity, cost) {
      return '<tr><td class="prod">' + name + '</td>' + 
			'<td><form action="javascript:void(0)" onsubmit="return dropdown_cart.update(' + id + ')"><input type="text" id="quantity_' + id + '" value="' + quantity + '" class="text" /></form></td>' +
			'<td>$' + cost + '</td>' +
			'<td><a href="javascript:dropdown_cart.remove_item(' + id + ')" title="Delete Item" class="delete">Delete Item</a></td>' +
			'</tr>';
	},
	
	make_subtotal_row: function(cost) {
		return '<tr class="subtotal"><td>&nbsp;</td><td colspan="3">Subtotal $' + cost + '</td></tr>';
	}
};
jQuery(document).ready(function() {
	dropdown_cart.setup();
});
/* end dropdown cart */

/* begin product form */
var product_form = {
	action_sel: '#product_action',
	price_sel: '#product_price',
	quantity_row_sel: '#row-quantity',
	quantity_sel: '#quantity',
	id_sel: '#product_id',
	color_sel: '#color',
	size_sel: '#size',
	data: false,
	price: 0,
	all_colors: [],
	all_sizes: [],
	
	check_init: function() {
		if (this.data == false && !(typeof product_data === 'undefined')) {
			this.data = product_data;

			for(var i=0; i<this.data.sizes.length; i++) {
				var opt = this.data.sizes[i];
				if (!this.in_array(this.all_sizes, opt)) this.all_sizes.push(opt);
			}
			for(var i=0; i<this.data.colors.length; i++) {
				var opt = this.data.colors[i];
				if (!this.in_array(this.all_colors, opt)) this.all_colors.push(opt);
			}
			return true;
		}
		return !(this.data == false);
	},
	
	submit: function() {
		var product_id = jQuery(this.id_sel).val();
		var quantity = parseInt(jQuery(this.quantity_sel).val());
		
		var url = "cart/ajax/update/" + product_id + "/" + quantity;
		
		jQuery.get(url, function(data) {
			dropdown_cart.update_display();
		});
				
		return false;
	},
	
	get_options: function(color, size) {
		//find options that match this color and size
		var results = [];
		for(var i=0; i<this.data.ids.length; i++) {
			var item = { 
				id: this.data.ids[i], 
				price: this.data.prices[i],
				color: this.data.colors[i],
				size: this.data.sizes[i],
				quantity: this.data.quantities[i]
			};
			
			if ((color == '' || item.color == color)) {
				if (size == '' || item.size == size) {
					results.push(item);
				}
			}
		}
		
		return results;
	},
	
	update_price: function(quantity) {
		var new_price = quantity * product_form.price;
		jQuery(this.price_sel).val('$' + new_price);
	},
	
	update: function() {
		if (!this.check_init())	return;
		var color_jq = jQuery(this.color_sel);
		var size_jq = jQuery(this.size_sel);
		
		var color = color_jq.val();
		color = color.replace('é', '&eacute;');
			

		var size = size_jq.val();
		var	options = this.get_options(color, size);
			
		
		this.apply_options(color_jq, size_jq, color, size);
		
		if (options.length == 1) {
			//show add button
			jQuery(this.action_sel).show();
			jQuery(this.id_sel).val(options[0].id);
			jQuery(this.price_sel).val('$' + options[0].price);
			product_form.price = options[0].price;
			
			//resize price
			jQuery(this.price_sel).css({width: 120});
			
			//resize list of quantities
			var opts = "";
			for(var i=1; i<=options[0].quantity && i<=20; i++) {
				opts += '<option value="' + i + '">' + i + '</option>';
			}
			jQuery(this.quantity_sel).html(opts);
			document.getElementById('quantity').refresh();
			
			//show quantities row
			jQuery(this.quantity_row_sel).show();
		} else {
			//hide add button
			jQuery(this.action_sel).hide();
			
			//hide quantity row
			jQuery(this.quantity_row_sel).hide();
			
			//resize price
			jQuery(this.price_sel).css({width: 180});
			
			//figure out price range
			var price_low = options[0].price;
			var price_high = options[0].price;
			for(var i=1; i<options.length; i++) {
				var p = options[i].price;
				if (p < price_low)
					price_low = p;
				else if (p > price_high)
					price_high = p;
			}
			
			var label = '$' + price_low;
			if (price_low != price_high)
				label += ' - ' + price_high;
				
			jQuery(this.price_sel).val(label);
		}
	},
	
	in_array: function(arr, val) {
		for (j=0; j<arr.length; j++) {
			if (arr[j] == val) {
				return true;
			}
		}
		return false;
	},
	
	
	
	apply_options: function(color_jq, size_jq, color, size) {
		var sizes = [];
		var colors = [];
		for(var i=0; i<this.data.ids.length; i++) {
			var item = { 
				id: this.data.ids[i], 
				price: this.data.prices[i],
				color: this.data.colors[i],
				size: this.data.sizes[i],
				quantity: this.data.quantities[i]
			};
			if (color == '' || item.color == color)
				if (!this.in_array(sizes, item.size)) sizes.push(item.size);
			
			if (size == '' || item.size == size)
				if (!this.in_array(colors, item.color)) colors.push(item.color);	
		}

		if (sizes.length > 1) {
			var html = '<option value="">Please Select</option>';
			
			sizes.sort(product_form.sort_size);
			
			for(var i=0; i<sizes.length; i++) {
				var cur = sizes[i];
				var sel = "";
				if (cur == size) {
					sel = 'selected="selected" ';
				}
				
				html += '<option ' + sel + 'value="' + cur + '">' + cur + '</option>';
			}
			size_jq.html(html);
			document.getElementById('size').refresh();
		}

		if (colors.length > 1) {
			html = '<option value="">Please Select</option>';
			
			for(var i=0; i<colors.length; i++) {
				var cur = colors[i];
				var sel = "";
				if (cur == color) {
					sel = 'selected="selected" ';
				}
				
				html += '<option ' + sel + 'value="' + cur + '">' + cur + '</option>';
			}
			color_jq.html(html);
			document.getElementById('color').refresh();
		}
	},
	
	sort_size: function(a, b) {
		if (a == b) {
			return 0;
		} else if (a == 'Newborn') {
			return -1;
		} else if (b == 'Newborn') {
			return 1;
		}
		
		var s1 = a.indexOf(' ');
		if (s1 > -1) {
			var n1 = a.substr(0, s1);
			var u1 = a.substr(s1 + 1);
		} else {
			var n1 = s1;
			var u1 = "";
		}
		
		var s2 = b.indexOf(' ');
		if (s2 > -1) {
			var n2 = b.substr(0, s2);
			var u2 = b.substr(s2 + 1);
		} else {
			var n2 = b;
			var u2 = "";
		}
		
		if (isNaN(n1) && isNaN(n2)) {
			//neither are number, standard ordering
			if (a < b)
				return -1;
			else if (a > b)
				return 1;
		} else if (isNaN(n1) && !isNaN(n2)) {
			//first is text, second is a number - number is first
			return 1;
		} else if (!isNaN(n1) && isNaN(n2)) {
			//first is a number, second is text - number is first
			return -1;
		} else {
			//both are numbers
			if (u1 == u2) {
				//same units
				if (parseFloat(n1) < parseFloat(n2)) {
					return -1;
				} else if (parseFloat(n1) > parseFloat(n2)) {
					return 1;
				}
			} else if (u1 < u2) {
				return -1;
			} else {
				return 1;
			}
		}
		
		return 0;
	},
	
	update_color: function() {
		this.update();
		/* select image associated with color */
		var color = jQuery(this.color_sel).val();
		var children = jQuery('#prodThumbs span.thumbs').children('a');
		for (var i=0, j=children.length; i<j; i++) {
			var link = jQuery(children[i]);
			if (link.data('color') == color) {
				link.trigger('click');
				break;
			}
		}
		/* end select image associated with color */
	},
	
	update_size: function() {
		this.update();
		
	}
};
jQuery(document).ready(function() {
	product_form.update();
});
/* end product form */

/* begin image pan */
var image_pan = {
	jq: {},
	
	start: function(jq) {
		this.jq = jq;
		this.jq.draggable({
			drag: function(event, ui) {
				if (ui.position.left > 0)
					ui.position.left = 0;
				else if (ui.position.left < (-1248 + 976))
					ui.position.left = -1248 + 976;

				if (ui.position.top > 0)
					ui.position.top = 0;
				else if (ui.position.top < (-1476 + 492))
					ui.position.top = -1476 + 492;
			}
		});
		this.jq.css({cursor: 'move', top: -500, left: -120});
		
//		this.jq.delay(1000).animate({top: -500}, 2000);
	},
	
	stop: function() {
		this.jq.draggable('destroy');
		this.jq.stop().css({top: 0, left: 0, cursor: 'auto'});
	}
};
/* end image pan */

/* address selection */
var addresses = {
	data: [
		{field: '#email', validation: 'email'},
		{field: '#phone', validation: 'phone'},
		{field: '#password', validation: 'password'},

		{field: '#billing_first_name', validation: 'required', related: ['#shipping_first_name', '#shipping_slip .fn']},
		{field: '#billing_middle_name', related: ['#shipping_middle_name', '#shipping_slip .mn'], related_extra: '.'},
		{field: '#billing_last_name', validation: 'required', related: ['#shipping_last_name', '#shipping_slip .ln']},
		{field: '#billing_address', validation: 'required', related: ['#shipping_address', '#shipping_slip .address']},
		{field: '#billing_suite', related: ['#shipping_suite', '#shipping_slip .suite'], related_extra: '<br />'},
		{field: '#billing_city', validation: 'required', related: ['#shipping_city', '#shipping_slip .city'], related_extra: ','},
		{field: '#billing_state', validation: 'state_us', dependent: '#billing_country', related: ['#shipping_state', '#shipping_slip .state'], related_extra: '&nbsp;'},
		{field: '#billing_state_other', validation: 'state_other', dependent: '#billing_country', related: ['#shipping_state_other', '#shipping_slip .state'], related_extra: '&nbsp;'},
		{field: '#billing_zip', validation: 'zip', zip_country: '#billing_country', related: ['#shipping_zip', '#shipping_slip .zip']},
		{field: '#billing_country', validation: 'required', related: ['#shipping_country', '#shipping_slip .country'], callback: 'addresses.update_billing_country()'},

		{field: '#shipping_first_name', validation: 'required'},
		{field: '#shipping_middle_name'},
		{field: '#shipping_last_name', validation: 'required'},
		{field: '#shipping_address', validation: 'required'},
		{field: '#shipping_suite'},
		{field: '#shipping_city', validation: 'required'},
		{field: '#shipping_state', validation: 'state_us', dependent: '#shipping_country'},
		{field: '#shipping_state_other', validation: 'state_other', dependent: '#shipping_country'},
		{field: '#shipping_zip', validation: 'zip', zip_country: '#shipping_country'},
		{field: '#shipping_country', validation: 'required', callback: 'addresses.update_shipping_country()'}
	],
	updating_related_fields: true,
	
	show_error: function(jq) {
		jq.focus();
		if (jq.data('showing_error') == 1)
			return;
		/*
		var position = jq.position();
		if (position.left != 0) {
			var tagLabel = jq.parent().find("label").text();
			var validTag = jQuery('<div class="tag"><div class="frame">Please enter a valid<br />' + tagLabel + '<div class="slug"></div></div></div>');
			jQuery(validTag).css({"top" : (position.top - 15) + "px","left" : (position.left - 145) + "px"});
			jq.parent().append(validTag);
		}		
		*/
		jq.css({"border-color":"#CC6666"});
		
		jq.data('showing_error', 1);
	},
	
	clear_error: function(jq) {
		if (jq.data('showing_error') == 1) {
			jq.css({"border-color":"#C6C7C6"});
			/*jq.parent().find(".tag").remove();*/
			jq.data('showing_error', 0);
		}
	},
	
	submit: function() {
		var valid = true;
		
		for(var i=0; i<this.data.length; i++) {
			var item = this.data[i];
			
			if (!this.validate(item, true)) valid = false;
		}
		
		if (!valid) {
			jQuery('#cart_error').show();
		}
		
		return valid;
	},
	
	validate: function(item, show_errors) {
		var valid = true;
		
		if (item.validation) {
			if (item.jq.length == 0) return true;
			var val = item.jq.val();
			if (item.validation == 'required') {
				if (val == '') {
					valid = false;
				}
			} else if (item.validation == 'password') {
				if (val != '') {
					if (val.length < 6)
						valid = false;
				}
			} else if (item.validation == 'email') {
				if (val == '') {
					valid = false;
				} else {
					var exp = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
					var re = new RegExp(exp);
					var match = re.exec(val);
					if (match == null)
						valid = false;
				}
			} else if (item.validation == 'phone') {
				if (val == '') {
					valid = false;
				} else {
					var int_val = val.replace(/[^0-9]/g, '');
					if (int_val != val) {
						item.jq.val( int_val );
					}
					
					if (int_val.length != 10)
						valid = false;
				}
			} else if (item.validation == 'state_us') {
				var dependent = jQuery(item.dependent);
				
				if (dependent.val() == 'United States') {
					if (val == '') {
						valid = false;
					}
				}
			} else if (item.validation == 'state_other') {
				var dependent = jQuery(item.dependent);
				
				if (dependent.val() != 'United States') {
					if (val == '') {
						valid = false;
					}
				}
			} else if (item.validation == 'zip') {
				var country = jQuery(item.zip_country);
				if (country.val() == 'United States') {
					var int_val = parseInt(val, 10);
					if (isNaN(int_val) || int_val < 10000 || int_val > 100000 || val.length != 5)
						valid = false;
				}
			}
		}
		
		if (!valid) {
			if (show_errors) this.show_error(item.jq);
		} else {
			this.clear_error(item.jq);
		}
		
		return valid;
	},
	
	setup: function() {
		//check if new shipping flag is set
		var new_shipping = jQuery('#new_shipping').val();
		if (new_shipping == '1') {
			this.change_shipping();
		}
		
		for(var i=0; i<this.data.length; i++) {
			var jq = jQuery(this.data[i].field);
			this.data[i].jq = jq;
			jq.data('address_data', this.data[i]);
			var item = this.data[i];

			if (item.related) {
				jq.change(function() { 
					addresses.update_related_field(jQuery(this).data('address_data'));
				}).keyup(function() { 
					addresses.update_related_field(jQuery(this).data('address_data'));
				})
			}
			
			if (item.callback) {
				jq.change(function() { 
					var item = jQuery(this).data('address_data');
					eval(item.callback);
				}).keyup(function() { 
					var item = jQuery(this).data('address_data');
					eval(item.callback);					
				})
			}
			
			
			jq.change(function() { 
				var item = jQuery(this).data('address_data');
				addresses.validate(item, false);
			}).keyup(function() { 
				var item = jQuery(this).data('address_data');
				addresses.validate(item, false);
			})
			
			jq.trigger('change');
		}
		
		
	},
	
	change_shipping_cancel: function() {
		this.updating_related_fields = true;
		jQuery('#new_shipping').val('0');
		
		jQuery('#shipping_slip').css({'display':''});
		jQuery('#shipping_info').css({'display':'none'});
		
		//refresh values
		for(var i=0; i<this.data.length; i++) {
			var jq = jQuery(this.data[i].field);
			jq.trigger('change');
		}
	},
	
	change_shipping: function() {
		this.updating_related_fields = false;
		
		jQuery('#new_shipping').val('1');
		
		jQuery('#shipping_slip').css({'display':'none'});
		jQuery('#shipping_info').css({'display':'block','width':'100%'});
	},
	
	update_related_field: function(item) {
		if (this.updating_related_fields) {
			var val = item.jq.val();
			if (item.related) {
				var extra = "";
				if (val != "" && item.related_extra) extra = item.related_extra;
				jQuery(item.related[0]).val(val).trigger('change');
				jQuery(item.related[1]).html(val + extra);
			}
		}
	},
	
	update_billing_country: function() {
		var val = jQuery('#billing_country').val();
		if (val == 'United States') {
			jQuery('#billing_state').show();
			jQuery('#billing_state_other').hide();
			jQuery('#billing_state_label').attr('for', 'billing_state');
			jQuery('#billing_zip_label').html('Zip');
		} else {
			jQuery('#billing_state').hide();
			jQuery('#billing_state_other').show();
			jQuery('#billing_state_label').attr('for', 'billing_state_other');
			jQuery('#billing_zip_label').html('Postal Code');
			
		}
	},
	
	update_shipping_country: function() {
		var val = jQuery('#shipping_country').val();
		if (val == 'United States') {
			jQuery('#shipping_state').show();
			jQuery('#shipping_state_other').hide();
			jQuery('#shipping_state_label').attr('for', 'shipping_state');
			jQuery('#shipping_zip_label').html('Zip');
		} else {
			jQuery('#shipping_state').hide();
			jQuery('#shipping_state_other').show();
			jQuery('#shipping_state_label').attr('for', 'shipping_state_other');
			jQuery('#shipping_zip_label').html('Postal Code');
			
		}
	}
}

jQuery(document).ready(function() {
	addresses.setup();
});
/* end address selection */

/* start order */
var order = {
	data: [
		{field: '#cc_number', validation: 'credit_card'},
		{field: '#cc_full_name', validation: 'required', required_text: 'Please enter the full name on the credit card'},
		{field: '#exp_month', validation: 'required', required_text: 'Please select an expiration month'},
		{field: '#exp_year', validation: 'required', required_text: 'Please select an expiration year'},
		{field: '#cvv', validation: 'required', required_text: 'Please enter a valid CVV Number'},
		{field: '#chk_terms', validation: 'checkbox', required_text: 'Please indicate you agree to the Terms and Conditions'},
		{field: 'input.shipping_option', validation: 'radio', required_text: 'Please select a shipping option'}
	],
	
	show_error: function(jq, msg) {
		if (jq.data('showing_error') == 1)
			return;
		
		var position = jq.position();
		if (position.left != 0) {
			if (msg == '') {
				var tagLabel = jq.parent().find("label").text();
				msg = 'Please enter a valid<br />' + tagLabel;
			}
			
			var validTag = jQuery('<div class="tag"><div class="frame">' + msg + '<div class="slug"></div></div></div>');
			jQuery(validTag).css({"top" : (position.top - 15) + "px","left" : (position.left - 145) + "px"});
			jq.parent().append(validTag);
		}		
		
		jq.css({"border-color":"#CC6666"});
		
		jq.data('showing_error', 1);
	},
	
	clear_error: function(jq) {
		if (jq.data('showing_error') == 1) {
			jq.css({"border-color":"#C6C7C6"});
			jq.parent().find(".tag").remove();
			jq.data('showing_error', 0);
		}
	},
	
	setup: function() {
		for(var i=0; i<this.data.length; i++) {
			var jq = jQuery(this.data[i].field);
			this.data[i].jq = jq;
			jq.data('address_data', this.data[i]);
			var item = this.data[i];
			
			
			jq.change(function() { 
				var item = jQuery(this).data('address_data');
				order.validate(item, false);
			}).keyup(function() { 
				var item = jQuery(this).data('address_data');
				order.validate(item, false);
			});
		}		
	},

	is_credit_card: function( number ) {
	    var sum = 0;
	    var mul = 1;
	 
	    for (var i = 0; i < number.length; i++) {
	       var digit = number.substring(number.length - i - 1, number.length - i);
	       var tproduct = parseInt(digit ,10) * mul;
	       if (tproduct >= 10)
	            sum += (tproduct % 10) + 1;
	       else
	            sum += tproduct;
	 
	       mul = 3 - mul;
	    }
	 
	    if ((sum % 10) == 0)
	        return true;
	    else
	        return false;
	},

	validate: function(item, show_errors) {
		var valid = true;
		
		if (item.validation) {
			var val = item.jq.val();
			if (item.validation == 'required') {
				if (val == '') {
					valid = false;
				}
			} else if (item.validation == 'credit_card') {
				if (val == '') {
					valid = false;
				} else if (!this.is_credit_card(val)) {
					valid = false;
				}
			} else if (item.validation == 'checkbox') {
				valid = item.jq.attr('checked');
			} else if (item.validation == 'radio') {
				var selected = jQuery(item.field + ":checked");
				
				valid = (selected.length > 0);
			}
		}
		
		if (!valid) {
			if (show_errors) {
				var msg = "";
				if (item.required_text) msg = item.required_text;
				this.show_error(item.jq, msg);
			}
		} else {
			this.clear_error(item.jq);
		}
		
		return valid;
	},
		
	submit: function() {
		var valid = true;
		
		for(var i=0; i<this.data.length; i++) {
			var item = this.data[i];
			
			if (!this.validate(item, true)) valid = false;
		}
		
		return valid;
	},
	
	format_number: function(num) {
		
		return '$' + parseFloat(num).toFixed(2);
	},
	
	update: function() {
		var product_subtotal = parseFloat(jQuery('#subtotal').val());
		var tax_rate = parseFloat(jQuery('#tax').val());
		var discount = parseFloat(jQuery('#discount').val());
		
		//calculate shipping
		var shipping = 0;
		var id = jQuery('input.shipping_option:checked').attr('id');
		if (id) {
			shipping = parseFloat(jQuery('#' + id + '_value').val());
		}
		
		//calculate gift wrap costs
		var gift_wrap = 0;
		var gift_wrap_item = parseFloat(jQuery('#gift_wrap').val());
		var gift_wrap_count = 0;
		jQuery('input.chk_gift').each(function() {
			if (jQuery(this).is(':checked')) {
				gift_wrap_count++;
			}
		});
		gift_wrap = parseFloat(gift_wrap_item * gift_wrap_count);
		
		
		var subtotal = product_subtotal + gift_wrap;
		
		var taxed_amount = subtotal - discount;
		var tax = tax_rate * taxed_amount;
		
		var grand_total = taxed_amount + tax + shipping;
		
		jQuery('#label_subtotal').html(this.format_number(subtotal));
		jQuery('#label_shipping_method').html(this.format_number(shipping));
		jQuery('#label_tax').html(this.format_number(tax));
		
		var grand_total_val = this.format_number(grand_total);
		
		jQuery('#label_grand_total').html(grand_total_val);
		jQuery('#calculated_grand_total').val(grand_total_val);
	}
};
jQuery(document).ready(function() {
	order.setup();
});
/* end order */
/* start shipping options */
var shipping = {
	setup: function() {
		jQuery('input.shipping_option').click(function() {
			order.update();
		});
		
		order.update();
	}
};
jQuery(document).ready(function() {
	shipping.setup();
});
/* end shipping options */
/* start gift message */
var gift_message = {
	popup_status: 0,
	last_id: '',
	
	setup: function() {
		jQuery('#overlay').click(function(){
			gift_message.hide_popup();
		});
		jQuery('input.chk_gift').click(function() {
			var id = jQuery(this).attr('id');
			
			var state = 0;
			if (jQuery(this).is(':checked')) state = 1;
			
			jQuery('#' + id + '_message').val('');
			gift_message.toggle_giftwrap(id, state);
		});
		jQuery('input.chk_gift').each(function() {
			if (jQuery(this).is(':checked')) {
				var id = jQuery(this).attr('id');
				var existing_message = jQuery('#' + id + '_message').val();
				
				 if (existing_message == '') {
				 	gift_message.toggle_giftwrap(id, 1);
				 } else {
				 	gift_message.toggle_giftwrap(id, 2);		 	
				 }
			}
		});
		
	},
	
	save: function() {
		var new_val = jQuery('#gift_message').val();
		
		 jQuery('#' + this.last_id + '_message').val(new_val);
		 
		 if (new_val == '') {
		 	gift_message.toggle_giftwrap(this.last_id, 1);
		 } else {
		 	gift_message.toggle_giftwrap(this.last_id, 2);		 	
		 }

		 this.hide_popup();
	},
	
	show: function(id) {
		this.last_id = id;
		
		jQuery('#gift_message').val(jQuery('#' + id + '_message').val());
		
		this.show_popup();
	},
	
	remove: function(id) {
		this.last_id = id;
		jQuery('#gift_message').val('');
		this.save();
	},
	
	toggle_giftwrap: function(id, state) {
		if (state == 0) {
			//no giftwrap
			jQuery('#' + id + '_add').hide();
			jQuery('#' + id + '_edit').hide();
			jQuery('#' + id + '_price').hide();
			order.update();
		} else if (state == 1) {
			//giftwrap, no message
			jQuery('#' + id + '_add').show();
			jQuery('#' + id + '_edit').hide();
			jQuery('#' + id + '_price').show();
			order.update();
		} else if (state == 2) {
			//giftwrap with message
			jQuery('#' + id + '_add').hide();
			jQuery('#' + id + '_edit').show();
			jQuery('#' + id + '_price').show();
			order.update();
		}
	},	

    show_popup: function() {
		if (this.popup_status == 0) {
			var windowWidth = $(window).width();
			var windowHeight = $(window).height();
			var documentTop = $(document).scrollTop();
			var popupHeight = $("#giftMsg").height();  
			var popupWidth = $("#giftMsg").width(); 
			$("#giftMsg").css({  
				"position": "absolute",  
				"top": ((windowHeight / 2) - (popupHeight / 2)) + documentTop,  
				"left": windowWidth/2-popupWidth/2  
			});
	 
			$("#overlay").css({  
				"height": windowHeight  
			});  

			$("body").css({"overflow":"hidden"});
			$("#overlay").css({"opacity": "0.7"});  
    		$("#overlay").fadeIn("slow");  
    		$("#giftMsg").fadeIn("slow");  
    		this.popup_status = 1;  
    	}  
    },
    
  	hide_popup: function() {
		if (this.popup_status == 1){  
			this.popup_status = 0;
			$("#overlay").fadeOut("slow");  
			$("#giftMsg").fadeOut("slow");  
			$('body').css('overflow', 'auto');
		} 
    }
};
jQuery(document).ready(function() {
	gift_message.setup();
});
/* end gift message */

var email_subscribe = {
	url: 'email_signup/',
	working: false,
	
	get_email: function() {
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		var email = jQuery('#email');
		var email_val = email.val();
		   		
		if (email_val == '' || email_val == 'Email Address' || reg.test(email_val) == false)
			return false;
		else
			return email_val;
	},
	
	submit: function() {
		var email = email_subscribe.get_email();
		if (email) {
			jQuery.ajax({
				url: email_subscribe.url,
				data: {email: email},
				success: function(data) {
					jQuery('#newsletter_form').hide();
					jQuery('#newsletter_success').fadeIn();
				}
			});
		} else {
			jQuery('#email').css({border: 'solid 1px red'});
		}
	}
}

var ajax_login = {
	email: '#email',
	password: '#password',
	url: '/ajax_login/',
	waiting: false,
	delay: 500,
	
	check: function() {
		if (!ajax_login.waiting) {
			ajax_login.waiting = true;
			setTimeout("ajax_login.tick()", ajax_login.delay);
		}
	},
	
	tick: function() {
		var credentials = ajax_login.get_credentials();
		if (credentials) {
			jQuery.get(ajax_login.url, credentials, function(data) {
				if (data && data.result) {
					location.href = '/checkout';
				}
			}, "json");
		}
		ajax_login.waiting = false;
	},
	
	get_credentials: function() {
		var email = jQuery(ajax_login.email);
		var password = jQuery(ajax_login.password);
		
		if (email && email.val() && password && password.val()) {
			return {email: email.val(), password: password.val()};
		} else {
			return null;
		}
	}
};

