$(document).ready(function() {
	
	var change_dropdown = function(level, id, name) {
		for(x=(parseFloat(level)+1); x<(parseFloat(level)+10); x++) {
			if($(".stock_line_"+ x).length > 0) { $(".stock_line_"+ x).each(function() { $(this).remove(); }); }
		}
		$("#product_price").html(""); $("#product_add").hide();
		$.ajax({
			type: "GET",
			url: "/custom/addons/product_stock_level.php",
			data: "level="+ level +"&productID="+ id +"&name="+ name,
			success: function(e) {
				$("#product_stock").append(e);
				$("#product_stock select").unbind();
				$("#product_stock select").change(function() {
					if($(this).hasClass("final") && $(this).val() > 0) {
						$("#product_add").show();
						val = $(this).val();
						$.ajax({
							type: "GET",
							url: "/custom/addons/product_price.php",
							data: "stockID="+ $(this).val() +"&productID="+ id,
							success: function(e) {
								$("#product_price").html(e);
								$("p#product_add input[type=text]").keyup(function() {
									update_price(val, $(this).val());
								});
							}
						});
					} else if($(this).val() == 0) {
						return false;
					} else {
						var par = $(this).parent(".stock_line");
						change_dropdown($(par).attr("id"), $(par).attr("rel"), $(this).val());
					}
				});
			}
		});
	}
	
	var single_dropdown = function(val, id) {
		$("#product_add").show();
		$.ajax({
			type: "GET",
			url: "/custom/addons/product_price.php",
			data: "stockID="+ val +"&productID="+ id,
			success: function(e) {
				$("#product_price").html(e);
				$("p#product_add input[type=text]").keyup(function() {
					update_price(val, $(this).val());
				});
			}
		});
	}
	
	var update_price = function(val, qty) {
		$.ajax({
			type: "GET",
			url: "/custom/addons/product_price_update.php",
			data: "stockID="+ val +"&quantity="+ qty,
			success: function(e) {
				$("#main_product_price").html(e);
			}
		});
	}
	
	$("#product_stock select").change(function() {
		var par = $(this).parent(".stock_line");
		if($(this).hasClass("final")) {
			single_dropdown($(this).val(), $(par).attr("rel"));
		} else {
			change_dropdown($(par).attr("id"), $(par).attr("rel"), $(this).val());
		}
	});
	
});
