var jq_inventory_productId = null;
var giftChoice = null;

(function($) {
	/**
	 * web service returns a list of inventory items that are out of stock
	 */
	 
	 $.fn.inventory = function(productId, attributeSelected, form, JSONInventoryURL, options) {
		var opts = $.extend({}, $.fn.inventory.defaults, options);
		var UNAVAILABLE_CLASS_NAME = opts.UNAVAILABLE_CLASS_NAME;
		var NOSTOCK_CLASS_NAME = opts.NOSTOCK_CLASS_NAME;
		giftChoice = $("#giftChoice").val();
				
		$.ajax({
			url: JSONInventoryURL,
			dataType: 'json',
			success: function(json) {
				// alert('start');
				var unavailableProduct = json.unavailableProduct;
				var unavailableItems = json.unavailableItems;
				var otherAttributes = json.otherAttributes;
			  	 // alert(otherAttributes);	
				if(otherAttributes != undefined){
					// rebuild size drop down
				  	$("#attrValue_2").children().remove();
				  	$("#attrValue_2").append('<option value="">Select Size </option> ');
				  	$.each(otherAttributes, function(key, attributes) {
				  		var name = attributes["Name"];
				  		var value = attributes["Value"];
				     	//  alert(name + " : " + value);
						$('#attrValue_2').append($("<option></option>").attr("value",name).attr("class",name.toLowerCase()).text(value)); 
				   	});
				  	$("#attrValue_2").html();
				 } 
				  
				if (unavailableProduct == null && unavailableItems == null) {
					// all of the items are available
					
				} 
				else {
					var selectedAttributes = form.find('.attribute .selected').first();
					
					if(selectedAttributes.size() == 0) {
						selectedAttributes = form.find('.attribute button, .attribute select').first();
						if(selectedAttributes.size() == 0) {
							return;
						}
					}
					
					if(unavailableProduct == true){
						var unavailable = form.find('.unavailable-message');
						var addToCart = form.find('.add-to-cart-button');
						var replacements = form.find('.replacement-products');
						addToCart.hide();
						unavailable.show();
						replacements.show();
						$.fn.colorbox.resize();
					}
					else {
						selectedAttributes.each(function() {
							//var attrName = $.fn.inventory.getAttrName($(this), form);
							//var attrList = $.fn.inventory.getAttrList(form);
							//var otherAttrName = $.fn.inventory.getOtherAttrName(attrName, attrList, form);
							
							//Inventory actions should be driven by color and
							//results should be displayed in the size drop-down
							var attrName = "color";
							var otherAttrName = "size";
							
							if (jq_inventory_productId == null || jq_inventory_productId != productId) {
								jq_inventory_productId = productId;
							}
							
							$.fn.inventory.clearUnavailable(otherAttrName, form, UNAVAILABLE_CLASS_NAME, NOSTOCK_CLASS_NAME);
							
							$.fn.inventory.setUnavailable(attrName, $.fn.inventory.getAttrValue(attrName, form), otherAttrName, form, unavailableItems, UNAVAILABLE_CLASS_NAME, NOSTOCK_CLASS_NAME);
							$.fn.inventory.showUnavailableButton(form, UNAVAILABLE_CLASS_NAME, NOSTOCK_CLASS_NAME);
						});
					}
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				// alert(textStatus + errorThrown);
				/*
				 * if(!attributeSelected && $('#inventory-exception').size() == 1) {
						$('.inventory-exception').remove();
						form.prepend($('#inventory-exception').html());
					}
				 */
				$('.inventory-exception').remove();
				form.prepend($('#inventory-exception').html());
			}
		});
	};
	$.fn.inventory.getAttrName = function(button, form) {
		//alert('getAttrName');
		var attrName = /attribute-(\w+)/.exec(button.parents('li[class^=attribute-]').attr('class'))[1];
		return attrName;
	};
	
	$.fn.inventory.getAttrList = function(form){
		//alert('getAttrList');
		var attrList = [];
		$.grep(form.find('li[class^=attribute-]'), function(li, i) {
			var attrName = /attribute-(\w+)/.exec($(li).attr('class'))[1];
			attrList.push(attrName);
		})
		//console.info(attrList)
		return attrList;
	};
	$.fn.inventory.getOtherAttrName = function(attrName, attrList, form) {
		//alert('getOtherAttrName');
		var otherAttrName = $.grep(attrList, function(attr) {
			return attr != attrName;
		});
		return otherAttrName;
	};
	$.fn.inventory.getAttrValue = function(attrName, form) {
		//alert('getAttrValue');
		var attrTag = form.find('.attribute-' + attrName + ' .selected')[0];
		if(attrTag) {
			return $(attrTag).val().toLowerCase();
		} 
	};
	$.fn.inventory.clearUnavailable = function(attrName, form, UNAVAILABLE_CLASS_NAME, NOSTOCK_CLASS_NAME) {
		var unavailableOps = form.find('.attribute-' + attrName + ' .' + UNAVAILABLE_CLASS_NAME);
		unavailableOps.each(function() {
			$(this).text($(this).val());
		});
		unavailableOps.removeClass(UNAVAILABLE_CLASS_NAME);
		
		var nostockOps = form.find('.attribute-' + attrName + ' .' + NOSTOCK_CLASS_NAME);
		nostockOps.each(function() {
			$(this).text($(this).val());
		});
		nostockOps.removeClass(NOSTOCK_CLASS_NAME);
	};
	$.fn.inventory.setUnavailable = function(attrName, attrValue, otherAttrName, form, unavailableItems, UNAVAILABLE_CLASS_NAME, NOSTOCK_CLASS_NAME) {
		// looks for out of stock items with the selected attribute, and sets the "other attributes" that are unavailable
		// alert('attrName: ' + attrName + ', attrValue: ' + attrValue + ', otherAttrName: ' + otherAttrName);
		$.each(unavailableItems, function(key, attributes) {
			if (attributes[attrName] == attrValue) {
				var otherAttrValue = attributes[otherAttrName];
				var optionSelector = '.attribute-' + otherAttrName + ' option.' + otherAttrValue;
				var buttonSelector = '.attribute-' + otherAttrName + ' button.' + otherAttrValue;
				
				if (attributes.qtyAvailable == 'null') {
					//Can't hide options in IE, so have to remove them
					form.find(optionSelector + ', ' + buttonSelector).remove();
				}				
				else if (attributes.qtyAvailable < -49999) {
					form.find(optionSelector + ', ' + buttonSelector).addClass(UNAVAILABLE_CLASS_NAME);
				} 
				else {
					if ((attributes.expectedDate == 'past') && (attributes.dropDate == 'future')) {
						form.find(optionSelector + ', ' + buttonSelector).addClass(UNAVAILABLE_CLASS_NAME);
					} else {
						form.find(optionSelector + ', ' + buttonSelector).addClass(NOSTOCK_CLASS_NAME);
					}
				}

				// See if there is a message to display.
				if (attributes.message.length) {
					// Append the message to text content of size option
					form.find(optionSelector).append(" " + attributes.message);
				}
			}
		});
	};
	$.fn.inventory.showUnavailableButton = function(form, UNAVAILABLE_CLASS_NAME, NOSTOCK_CLASS_NAME) {
		var unavailable = form.find('.unavailable-message');
		var addToCart = form.find('.add-to-cart-button');
		var giftChoiceAddToCart = form.find('#purchase-gift-add-to-cart-button');
		var replacements = form.find('.replacement-products');
				
		if(form.find(':selected.' + UNAVAILABLE_CLASS_NAME).size() > 0) {
			//sold out case - stock not expected back in
			addToCart.hide();
			giftChoiceAddToCart.hide();
			unavailable.hide();
			replacements.show();
		}
		else if(form.find(':selected.' + NOSTOCK_CLASS_NAME).size() > 0) {
			addToCart.hide();
			giftChoiceAddToCart.hide();
			unavailable.show();
			replacements.show();
		}
		else {
			addToCart.show();
			giftChoiceAddToCart.show();
			unavailable.hide();
			replacements.hide();
		}
		$.fn.colorbox.resize();
	};

	
	$.fn.inventory.defaults = {
		UNAVAILABLE_CLASS_NAME: 'unavailable',
		NOSTOCK_CLASS_NAME: 'nostock'
	};
	
})(jQuery)

