function init_option_selector(items, target) {
	var self = {};
	/*
	/	 items => the jquery obj pointing to the dom listing of products
	/	 target => contains the order form and the selects
	*/
	function get_products() {//loop through the dom items and compose a list of products
		var products = Array();
		items.each(function() {
			var obj = {};
			$(this).children().each(function() {
				var val = $(this).text();
				$.each($(this).attr('class').split(' '), function() {
					obj[this] = val
				});
			});
			products.push(obj);
		});
		return products;
	}
	
	function get_possible_products(index) {
		var selections = {};
		var possible_products = Array();
		for(var i=0; i < index; i++){//compose a list of the currently selected options
			if (!self.selectors[i].val()) continue;
			selections['option'+(i+1)] = self.selectors[i].find(':selected').text();
		};
		$.each(self.products, function() {//filter products that match the selected options
			for(var key in selections) {
				if (this[key] != selections[key]) return;
			}
			possible_products.push(this);
		});
		return possible_products;
	}
	
	function select_option(index) {
		var possible_products = get_possible_products(index);
		// store the currently selected option values
		var avaliable_options=[];    
		for(i in self.selectors) avaliable_options.push(self.selectors[i].val());
		// Iterate through option1..n and widdle down the possible products
		for(var i=index; i < self.selectors.length; i++) {
			var selector = self.selectors[i];
			var pval = selector.val();
			selector.children('[value!=""]').remove();
			var added_options = {};
			$.each(possible_products, function() {//loop through possible products and add possible options
				var val = this['option'+(i+1)];
				if (added_options[val]) return;
				added_options[val] = true;
				selector.append('<option value="'+val+'">'+val+'</option>');
			});
			selector.val(pval);
		}
		possible_products = get_possible_products(self.selectors.length); //given the current selection, is there one product match?
		if (possible_products.length == 1) { //person selected the last option
			select_product(possible_products[0]);//we have our product, update the form and send the signal
		} else {
			target.find('input[name="sku"]').val('');
			target.trigger('product-selected', [null, false, false]); //no product selected
		}
		
		// Use the curoptions to figure out if we should jump to an image,
		// assuming images have option1..n attributes
		var imgoptfilter = '';
		for(var i=0;i<avaliable_options.length;i++) {
			if(avaliable_options[i] && avaliable_options[i].length) {
				if(imgoptfilter.length) imgoptfilter += ',';
				imgoptfilter += "[option" + (i+1) + "='" + avaliable_options[i].replace("'","\'") + "']";
			}
		}
		// if there are options to filter by, do that now
		if(imgoptfilter.length) $('#product_images .thumbnail:'+imgoptfilter).click();
	}
	
	function bool(val) {
		return val == 'True' || val == '1';
	}
	
	function select_product(product) {
		for(key in product) {
			target.find('input[name="'+key+'"]').val(product[key]);
		}
		target.trigger('product-selected', [product, bool(product.can_order), bool(product.in_stock)]);
	}
	
	function init_selectors() {
		var index = 0;
		var selectors = Array();
		while(true) {
			index += 1;
			var selector = target.find('.product_option'+index);
			if (!selector.length) break;
			selectors.push(selector);
			selector.data('index', index); //need to duplicate index
			selector.change( function () {
				self.select_option($(this).data('index'));
			});
		}
		return selectors
	}

	self.products = get_products(items);
	self.select_option = select_option;
	self.select_product = select_product;
	self.selectors = init_selectors();
	if (!self.selectors.length && self.products.length == 1) {
		select_product(self.products[0]);
	} else {
		select_option(0);
	}
	return self;
}

$(document).ready(function() {
	var product_images = $('#product_images');
	var main_image = $('#main_image');
	var num_images = $('li', product_images).length;
	if (!num_images) {
		//no images
		$('#product_image').hide();
		return;
	}
	if (num_images <= 1) {
		product_images.hide();
	}
	if (num_images <= 5) {
		$('.left, .right', product_images).hide();
	}
	var options = {
		zoomWidth: 300,
		zoomHeight: 250,
		xOffset: 10,
		yOffset: 0,
		position: "right" //and MORE OPTIONS
	};
	function load_video(target, auto_play) {
		$("img", main_image).fadeOut(200);
		$('.display', main_image).html('<div id="video_piece">&nbsp;</div>');
		var flashvars = { 
				accentcolor:'0b6dd2',
				videoPath:target,
				baseurl: location.protocol + '//' + location.host,
				emailurl: "mailto:?body=I recommend visiting this page: "+location.href
		};
		
		var params = {
				bgcolor: '#000000',
				allowFullScreen: 'true',
				scale: 'noscale',
				wmode: 'transparent',
				quality: 'high',
				menu: 'false',
				allowScriptAccess: 'sameDomain'
		};
		var attributes = {id: 'video_piece'};
		swfobject.embedSWF("/static/videos/flash/Web_Cube_VideoPlayer.swf","video_piece","435","348","9.0.0", '', flashvars, params, attributes);
	}
	
	var media_list = WebCubePager(product_images, 5);
	
	// clicking a thumbnail updates display and zoom
	media_list.find('li.image a.thumbnail').click(function() {
		var $this = $(this);
		var $link = $this.siblings('.display').find('.fullsize');
		media_list.find('li').removeClass('selected');
		$this.parent('li:first').addClass('selected');
		$('.display', main_image).html($this.siblings('.display').html());
		$('.display', main_image).data('link', $link);
		$('.display', main_image).click(function () {
			 $('.zoomer a').click();
		});
		$('.display a', main_image).jqzoom(options);
		
		// center display image in its container
		$("img", main_image).hide();
		$('img', main_image).load(function(){
			var display_offset = [
				($('.display', main_image).width() - $('.display a', main_image).width())/2,
				($('.display', main_image).height() - $('.display a img', main_image).height())/2
			]
			$('.display a', main_image).css('left', display_offset[0]).css('top',display_offset[1]);
			$("img", main_image).fadeIn(200);
		});
		$('img', main_image).load();
		return false;
	});
	media_list.find('li.video a.thumbnail').click(function() {
		load_video($(this).attr('href'), true);
		return false;
	});
	$('.jqZoomPup', main_image).live('click', function () {
		$('.zoomer a').click();
		return false;
	});
	
	media_list.find('a.fullsize').fancybox();
	$('.zoomer a').click(function() {
		$('.display', main_image).data('link').click();
		return false;
	});
	
	// center thumbnails in case they are not proportionate
	$('.thumb', product_images).each(function() {
		CtrThumbnailImage($(this));
	});
	
	media_list.find('li a.thumbnail:first').click()
});

function CtrThumbnailImage(thumb) {
	//alert(thumb.children('a.thumbnail').height());
	thumb.children('a.thumbnail img').fadeOut(10);
	if(thumb.children('a.thumbnail').height()>0) {
		var thumb_offset = [
			(thumb.width() - thumb.children('a.thumbnail').width())/2,
			(thumb.height() - thumb.children('a.thumbnail').height())/2
		];
		//alert(thumb_offset);
		thumb.children('a.thumbnail').css('left', thumb_offset[0]).css('top',thumb_offset[1]);
		thumb.children('a.thumbnail img').fadeIn(200);
	} else {
		setTimeout(function() {CtrThumbnailImage(thumb)}, 200);
	}
}

$(document).ready(function () {
	function load_recaptcha() {
		$('#review_post form').ajaxForm({
			target: '#review_post_cont',
			success: load_recaptcha
		}); 
		Recaptcha.create(
			RECAPTCHA_PUB_KEY,
			"recaptcha_div", {
			theme: 'white'
		});
	}
	$('#write_review_btn a').click(function() {
		$('#write_review_btn').hide();
		$('#review_post').show();
		load_recaptcha();
		return false;
	});
	$('div.rating').each(function (){
		rating_value = parseFloat($(this).children('div.value').html());
		ratio = rating_value/5; // out of 5 stars
		full_width = $(this).width();
		$(this).children('div.value').html('&nbsp;');
		$(this).children('div.value').width(Math.round(ratio*full_width));
	});
});

$(document).ready(function() {
	$('form[name="request_instock_notification"]').submit(function() {
		$('body').append('<a id="_temp_rin_anchor" href="'+$(this).attr('action') + '?' + $(this).serialize() + '&iframe"></a>');
		$('#_temp_rin_anchor').fancybox().click().remove();
		return false;
	});
});

$(document).ready(function() {
	 $('a#sendtofriend').fancybox({
		'frameWidth': 500,
		'frameHeight': 400
	 }); 
});
