var product_id = 0;
var options = new Array();

$(document).ready(function() {
	$(".accordion").accordion({
		active: -1, 
		autoHeight: false,
		collapsible: true,
		alwaysOpen: false
	});
	$("a.link").click(function(){
		window.location.href = $(this).attr("href");
	});
});

function getProductOptions(){
	$('#our_price').html('Select options first');
	$('#on_hand').html('');
	$.post('store/product_options', {product_id: product_id}, function(data){
		if(data.error != undefined){
			alert(data.error);
		} else {
			switch(data.action){
				case 'next_option':
					$('#options').append(data.options);
					opt = $('#'+data.option_id);
					options.push(data.option_id);
					opt.change(selectOption);
					break;
				case 'show_button':
					$('#variation_id').val(data.variation.id);
					$('#our_price').html('$'+Number(data.variation.price).toFixed(2));
					if(data.variation.product_status_slug == 'out-of-stock' || data.variation.quantity <= 0){
						$('#on_hand').html('Out of stock');
					} else {
						$('#on_hand').html(data.variation.quantity + ' on hand');
						$('#btnAdd').show();
					}
					break;
			}
		}
	}, 'json');
}

function selectOption(evt){
	$('#btnAdd').hide();
	opt = null;
	removals = new Array();
	for(i = 0; i < options.length; i++){
		if(opt != null){
			$('#'+options[i]).remove();
			removals.push(i);
		}
		if(options[i] == $(this).attr('id')) opt = options[i];
	}
	for(i = 0; i < removals.length; i++){
		options.splice(removals[i], 1);
	}
	$.post('store/select_option', {product_id: product_id, opt_id: $(this).val()}, function(data){
		if(data.error != undefined){
			alert(data.error);
		} else {
			getProductOptions();
		}
	}, 'json');
}