$(document).ready(function(){
	
	// Buy online
	$("#buynow").click(function() {
		$(this).parent().toggleClass("activated");		
		return false;
	});
	
	// Buy online go away
	$(document).click(function(event) {
		
		target = (event.target) ? event.target : event.srcElement;
	
		if ($(target).parents(".buy").length == 0 || $(target).parents(".top").length != 0) {
			$(".buy").removeClass("activated");
		}
		
	});
	
	$("#product_size").change(function() {
		
		$("#product_submit").removeAttr("disabled").attr("value", "Go");
		$("#onlineresults").slideUp("fast", function() {
			$("#onlineresults").empty();
			$("#product_submit").removeClass("engaged")
		});
		
	});
	
	// Online Shop pull
	$("#product_submit").click(function() {
		
		if ($(this).attr("disabled")) return false;
	
		// Check for valid query
		if ($("#product_size").val() == "no") {
			alert("Select a size!");
			return false;
		}
		
		$("#product_size").attr("disabled", "disabled");
		$(this).attr("disabled", "disabled").attr("value", "Chill");
		$("#shopresults").slideUp("fast");
		findOnlineShops();
		
		return false;
		
	});

});

// Find online shops
function findOnlineShops() {
	
	// Do AJAX request
	shopsURL = "/api/inventorysearch/?format=json&sku=" + $("#product_sku").val() + "&code=" + $("#product_code").val() + "&size=" + $("#product_size").val();
	//document.write(shopsURL);
	$.getJSON(shopsURL, function(results){
	
		if (results.shops && results.shops.length) {
			
			$("#onlineresults").append("<p>Buy now from:</p>").append("<ul />");
			for (var i = 0; i < results.shops.length; i++) {
								
				thisShop = results.shops[i];
				
				$("#onlineresults ul").append("<li><a href=\"" + thisShop.url + "\" onclick=\"pageTracker._trackPageview('/outbound/" + thisShop.token + "/" + $("#product_token").val() + "-" + $("#product_sku").val() + "/" + $("#colorway_token").val() + "-" + $("#product_code").val() + "/'); pageTracker._trackPageview('/productlinks/" + $("#product_token").val() + "-" + $("#product_sku").val() + "/" + $("#colorway_token").val() + "-" + $("#product_code").val() + "/');\"><img src=\"" + thisShop.image + "\" width=\"102\" height=\"78\" alt=\"" + thisShop.name + "\" /><br/>" + thisShop.name + "</a></li>");
			}
			
		}
		else $("#onlineresults").append("<p class=\"statusmessage\">Sorry, no shops were found with that size in stock!</p>");
		
		// Show results
		$("#onlineresults").slideDown("slow");
		
		$("#product_size").removeAttr("disabled");
		$("#product_submit").addClass("engaged").attr("value", "Done");
		
	});
	
}
