/*
	Copyright 2008 (c) Walter Flaschka
	jQuery JS to check whether pulldown attrib combos result in a non-available product.
	- There may be multiple configurable products on the page
	- On any attribute pulldown change, check the stock list to see if it's in stock and show message if not
	- If there are 2 attribute pulldowns, relate them so that the first selection filters the second
	- If (bi-directional) a selection in one pulldown has NO availability in the other pulldown(s), remove that option completely
	- For the above rule, have it apply for 1..n attribute pulldowns. 
*/

$(document).ready(function(){
	$("#stock-level-warning").hide();
	stockLevel_findPulldownDependency(); // Run this first so it stores a full view of the 2nd attribute pulldown (if applicable)
	stockLevel_pulldownPreCheck(); // Run this next to filter out default choices
	// stockLevel_findPulldownDependency();
});

var productPulldownHTML = [];

function stockLevel_findPulldownDependency() {
	// Products with 2 pulldowns must be interdependent; a common situation. Client rule.
	for (prodId in stockLevels) {
		if ($('.attribute-'+prodId).hasClass('pulldownCount-2')) {

			// First, remember what the pulldown was (this is a MSIE hack workaround)
			// We will need this to rebuild the pulldowns
			productPulldownHTML[prodId] = $('.attribute-'+prodId+'.pulldownCount-2').html();

			// Then make the pulldwons interdependent:
			$('.attribute-'+prodId+'.pulldownCount-1').change(function(){
				stockLevel_changeDependentPulldownSelections(prodId);
			});

		}
	}
}

function stockLevel_changeDependentPulldownSelections(prodId) {
	// When the left pulldown is updated, then the right pulldown must be changed. Client rule.
	PAIDFirst    = stockLevel_deriveProductAttributeId($('.attribute-'+prodId+'.pulldownCount-1').attr('name'));
	PAIDFirstSel = $('.attribute-'+prodId+'.pulldownCount-1').val();
	PAIDSecond   = stockLevel_deriveProductAttributeId($('.attribute-'+prodId+'.pulldownCount-2').attr('name'));
	var secondPulldownQuantities = [];

	attributeCombos: for (idx in stockLevels[prodId]) {
		var pimArray = stockLevels[prodId][idx];
		if (pimArray[PAIDFirst] == PAIDFirstSel) {
			// Only for combos where the first pulldown matches our selection
			secondPulldownQuantities[pimArray[PAIDSecond]] = pimArray['qty'];
		}
	}
	// We now have quantities for each option in the second pulldown
	// MSIE hack: Reset the 2nd pulldown to what they were at page load
	$('.attribute-'+prodId+'.pulldownCount-2').html(productPulldownHTML[prodId]);
	$('.attribute-'+prodId+'.pulldownCount-2').find('option').each(function() {
		if (1 > parseInt(secondPulldownQuantities[$(this).val()])) {
			// MSIE hack: Remove option from pulldown if there is no qty associated with it
			$('.attribute-'+prodId+'.pulldownCount-2').removeOption($(this).val());
		}
	});

	// Check the stock levels and show the warnings (there should be none, but they're triggering during this func)
	checkStockLevels(prodId)
}

function stockLevel_pulldownPreCheck() {
	// Check default pulldown settings when the page loads
	for (prodId in stockLevels) {
		stockLevel_filterSoldoutOptions(prodId);
		checkStockLevels(prodId);
		if ($('.attribute-'+prodId).hasClass('pulldownCount-2')) {
			stockLevel_changeDependentPulldownSelections(prodId);
		}
	}
}

function checkStockLevels(prodId) {
	var checkArray = stockLevel_buildCheckArray(prodId);
	var qty = stockLevel_quantityLookup(prodId, checkArray);
	if (1 > qty) {
		$("#stock-level-warning").show();
	} else {
		$("#stock-level-warning").hide();
	}
}

function stockLevel_quantityLookup(prodId, checkArray) {
	attributeCombos: for (idx in stockLevels[prodId]) {
		var pimArray = stockLevels[prodId][idx];
		checkingAgainstThisArray: for (paid in checkArray) {
			var pavid = checkArray[paid];
			if (pimArray[paid] == pavid) {
				// good
			} else {
				continue attributeCombos;
			}
		}
		return pimArray['qty'];
	}
}

function stockLevel_buildCheckArray(prodId) {
	var returnArray = [];
	var productAttributeId;
	$('.attribute-'+prodId).each(function(){
		productAttributeId = stockLevel_deriveProductAttributeId($(this).attr('name'));
		returnArray[productAttributeId] = $('.attribute-'+prodId+'-'+productAttributeId).val();
	});
	return returnArray;
}

function stockLevel_deriveProductAttributeId(productAttributeId) {
	// Get the paid for a given pulldown settings[prodId][paid]
	// we do it this way because regex never works for us
	productAttributeId = productAttributeId.replace(/settings/g,'');
	productAttributeId = productAttributeId.replace('['+prodId+']','');
	productAttributeId = productAttributeId.replace(/\[|\]/g,''); 
	return productAttributeId;
}

function stockLevel_filterSoldoutOptions(prodId) {
	var PIMList = stockLevels[prodId];
	var quantityTotals = [];
	var checkArray = stockLevel_buildCheckArray(prodId);

	for (paid in checkArray) {
		for (idx in PIMList) {
			var selectedOption = PIMList[idx][paid];
			var comboTotal = parseInt(PIMList[idx]['qty']);

			if (typeof quantityTotals[selectedOption] == 'undefined' ) {
				quantityTotals[selectedOption] = comboTotal;
			} else {
				quantityTotals[selectedOption] += comboTotal;
			}
		}

		// Clear out options that are sold out:
		for (pavid in quantityTotals) {
			var sumqty = quantityTotals[pavid];
			if (1 > sumqty) {
				$("select.attribute-"+prodId+"-"+paid).removeOption(pavid);
			}
			// See if there are any options available.
			if (1 > $("select.attribute-"+prodId+"-"+paid).children('option').length) {
				$("select.attribute-"+prodId+"-"+paid).parent().hide();
				// $("div#add-to-cart-buttons").hide();
				$("div#stock-level-warning-soldout").show('slow');
			}
		}
		
		quantityTotals = [];
	}
}
