function replaceProducts(products) {
	bycode = [];
	for( index = 0; index < products.length; index++ ) {
		bycode[products[index].code] = products[index];
	}
	$jq(".ajax-product-lookup").each(function() {
		product = bycode[$jq(this).text()];

		if ( product != null ) {
			if ( product.catalogPrices.lowestLessThanList ) {
				pricing_class = "sale-price";
				price_img = "<img class='sale-tag' src='/template-resources/images/te1/sale.gif' height='12' width='40' alt='SALE' />"
				was_save = "Was " + product.catalogPrices.listPrice.moneyValueAndSymbol +
					", Save " + product.catalogPrices.dollarSavings.moneyValueAndSymbol +
					" (" + product.catalogPrices.discountPercentage + "%)"
			} else {
				pricing_class = "reg-price";
				price_img = "";
				was_save = "";
			}
			product_url = "/prod" + product.code + ".html";

						innerHTML = "<ul class='product'>" +
						"<li class='product-img'><a href='" + product_url + "'>" +
						"<img src='/renderImage.image?imageName=" + product.image + 
						"&width=130&height=130&border=0' />" +
						"</a></li>" +
						"<li class='product-item-name'>" +
						"<div class='brand-name'>" + product.brand.localizedPropertiesMap.brandDisplayName_en.value +
						"</div>" +
						"<div class='prod-name'><a href='" + product_url + "'>" + 
						product.localeDependantFieldsMap.en.displayName + "</a></div></li>"
						
						if ($jq(this).hasClass('apl-price')) {
							innerHTML = innerHTML + "<li class='product-pricing'><div class='" + pricing_class + "'>" + price_img +
							product.catalogPrices.lowestPrice.moneyValueAndSymbol + 
							"</div><div class='was-save'>" + was_save + "</div></li>"
						}
						
						innerHTML = innerHTML + "</ul>"					
					
					
					$jq(this).html(innerHTML).show();


		}
	});
}

function productLookupError() {
	$jq("body").append( "Server note: some products could not be retrieved" );
}

onLibraryLoad( "JQ", function() {
	$jq(document).ready(function() {
		var codes = "";
		$jq(".ajax-product-lookup").each(function() {
			codes += "," + $jq(this).text();
		});
		if ( codes.length > 0 ) {
			codes = codes.substring(1);
			
			$jq.ajax({
				url: "/product-lookup.ep?codes=" + codes,
				dataType: "json",
				success: replaceProducts,
				error: productLookupError,
				cache: false
			});
		}	
	});
});


