﻿/// <reference path="/Content/scripts/jquery-1.4.1-vsdoc.js" /> 

// -----------------------
// various functions for use during the products listing
// -----------------------

// handles the interactivity for variant-bound option dropdowns for each product
function initializeProductDropdowns() {

	$("select[name^='variants-of-']").each(function () {
		$(this).change(function (e) {
			var selectedVariantId = $(e.target).attr("value");
			var siblingOptionDivs = $(e.target)
				.closest(".productoptions")
				.contents()
				.filter("div[id*='options-of-']");
			siblingOptionDivs.slideUp(300);
			$("div[id='options-of-" + selectedVariantId + "']").slideDown(300);
		});
	});

}

// handles the interactivity for case selection. automatically disables checkboxes
// above the number of distinctProductsAllowed
function initializeCaseSelectionConstraints(caseSelector, distinctProductsAllowed) {

	var jCase = $(caseSelector);
	setCaseSubmissionAllowed(jCase, false);

	jCase.find("input[type='checkbox']")
		.removeAttr("checked")
		.removeAttr("disabled")
		.data("jCase", jCase)
		.bind('change', function (e) {
		
			var jCase = $(this).data("jCase");
			var totalBoxesChecked = jCase.find(":checked").length;
			var boxesNotChecked = jCase.find("input[type='checkbox']:not(:checked)");

			if (totalBoxesChecked >= distinctProductsAllowed) {
				boxesNotChecked.attr("disabled", "disabled");
				jCase.find(".caseproductqty").slideDown(300, function () { $(this).parent().find(".qtybox").focus(); });
				setCaseSubmissionAllowed(jCase, true);
			} else {
				boxesNotChecked.removeAttr("disabled");
				jCase.find(".caseproductqty").slideUp(300);
				setCaseSubmissionAllowed(jCase, false);
			}
		}
	);
}

// replaces the submit handler surrounding the provided jCaseSelector to 
// prevent/allow invalid/valid caseSubmissions
function setCaseSubmissionAllowed(jCaseSelector, isAllowed) {
	jCaseSelector.closest("form").unbind().submit(function () {
		if (isAllowed) {
			return true;
		} else {
			return false;
		}
	});
}
