var autoQuantityKeyUpTimer = [];

function mailingServices()
{
	if (typeof productGrouping != 'undefined' && productGrouping) {
		return;
	}

	var mailingServicesSelect = null;
	$('.option-select').each(function() {
		if ($(this).attr('optionName')=='Mailing Services')
		{
			mailingServicesSelect = $(this);
		}
	});

	if (mailingServicesSelect!=null)
	{
		if (mailingServicesSelect.children('option:selected').attr('valueName')=='Yes Mailing Services')
		{
			$('.option-select').each(function() {

				if ($(this).attr('optionName')=='Coating Type')
				{
					$(this).children('option[text="UV Coating"]').attr('disabled', true);
					if ($(this).children('option:selected').attr('valueName')=='UV Coating')
					{
						$(this).children('option[text="No Coating"]').attr('selected', true);
					}
				} else
				if ($(this).attr('optionName')=='Must Be Exact Trim Size')
				{
					$(this).children('option[text="No"]').attr('disabled', true);
					$(this).children('option[text="Yes"]').attr('selected', true);
				}

			});
		} else
		{
			$('.option-select').each(function() {

				if ($(this).attr('optionName')=='Coating Type')
				{
					$(this).children('option[text="UV Coating"]').attr('disabled', false);
				} else
				if ($(this).attr('optionName')=='Must Be Exact Trim Size')
				{
					$(this).children('option[text="No"]').attr('disabled', false);
				}

			});
		}
	}
}

function folding()
{
	if (typeof productGrouping != 'undefined' && productGrouping) {
		return;
	}

	var foldingSelect = null;
	$('.option-select').each(function() {
		if ($(this).attr('optionName')=='Folding')
		{
			foldingSelect = $(this);
		}
	});

	if (foldingSelect!=null)
	{
		if (foldingSelect.children('option:selected').attr('valueName')!='No Folding')
		{
			$('.option-select').each(function() {

				if ($(this).attr('optionName')=='Scoring')
				{
					$(this).children('option[text="No Scoring"]').attr('disabled', true);

					$('.option-select option:contains("Yes Scoring")').attr('selected', 'selected');

				}

			});
		} else
		{
			$('.option-select').each(function() {

				if ($(this).attr('optionName')=='Scoring')
				{
					$(this).children('option[text="No Scoring"]').attr('disabled', false);
				}

			});
		}
	}
}

function paperType()
{
	if (typeof productGrouping != 'undefined' && productGrouping) {
		return;
	}
	
	var paperTypeSelect = null;
	$('.option-select').each(function() {
		if ($(this).attr('optionName')=='Paper Type')
		{
			paperTypeSelect = $(this);
		}
	});

	if (paperTypeSelect!=null)
	{
		if (paperTypeSelect.children('option:selected').attr('valueName')=='100# Gloss Text')
		{
			$('.option-select').each(function() {

				if ($(this).attr('optionName')=='Must Be Exact Trim Size')
				{
					$(this).children('option[text="No"]').attr('disabled', true);
					$(this).children('option[text="Yes"]').attr('selected', true);
				}

				if ($(this).attr('optionName')=='Coating Type')
				{
					var optionsToDisable = $('.option-select[optionName="Coating Type"]').find('option').filter(function() {
						if ($(this).attr('valueGroups') != '') {
							return false;
						}
						return ($(this).text().indexOf('UV ') > -1);
					});

					var anySelected = false;
					optionsToDisable.each(function() {
						if ($(this).is(':selected')) {
							anySelected = true;
						}
					});

					optionsToDisable.attr('disabled', true);
					optionsToDisable.hide();

					if (anySelected) {
						var firstEnabled = $('.option-select[optionName="Coating Type"]').find('option').filter(function() {
							return ($(this).is(':disabled') == false);
						}).first();
						firstEnabled.attr('selected', true);
						$('.option-select[optionName="Coating Type"]').val(firstEnabled.val());
					}
				}

			});
		} else
		{
			$('.option-select').each(function() {

				if ($(this).attr('optionName')=='Must Be Exact Trim Size')
				{
					$(this).children('option[text="No"]').attr('disabled', false);
				}

				if ($(this).attr('optionName')=='Coating Type')
				{
					var optionsToEnable = $('.option-select[optionName="Coating Type"]').find('option').filter(function() {
						if ($(this).attr('valueGroups') != '') {
							return false;
						}
						return ($(this).text().indexOf('UV ') > -1);
					});

					optionsToEnable.attr('disabled', false);
					optionsToEnable.show();
				}

			});
		}
	}
}

function quantityKeyUp()
{
	if ((typeof shippingOptionsRun)!='undefined') shippingOptionsRun = 0; //Reset shipping option prices

	var addDisabled;

	// if ($('#product option:selected').attr('orderable')==1) $.blockUI({ message: '<h2><img src="/themes/general/images/busy.gif" /> Calculating total...</h2>' });

	addDisabled = '';
	$('#product-calculator select:disabled').each(function() {
		addDisabled += '&'+encodeURIComponent($(this).attr('name'))+'='+$(this).val();
	});
	$.getJSON('/store/ajaxGetCustomQuantityGroups.html?ajax=true', $('#product-calculator').serialize()+addDisabled, function(data) {

		$.unblockUI();
		$('.option-select[optionName!="Quantity"] option').show();

		var selected = null;

		var valueGroup = data.valueGroups;
		if (valueGroup==null) return;

		if ((valueGroup==null) || (valueGroup==''))
		{
			$('.option-select[optionName!="Quantity"] option[valueGroups!=""]').removeAttr('disabled', 'disabled');

			$('.option-select[optionName!="Quantity"]').each(function() {

				var selectedChildren = $(this).children('option:selected');

				if (selectedChildren.length>0) return;

				$(this).children('option:enabled:first').attr('selected', 'selected');

			});

			return;
		}

		$('.option-select[optionName!="Quantity"] option[valueGroups!=""]').each(function() {

			selected = $(this).attr('selected');

			if ($(this).attr('valueGroups').indexOf(valueGroup)==-1)
			{
				$(this).attr('disabled', 'disabled');

				if (selected!=null)
				{
					$(this).removeAttr('selected');
					$('.option-select[optionName="'+$(this).attr('optionName')+'"]').val( $('.option-select[optionName="'+$(this).parent().attr('optionName')+'"] option:enabled').attr('value') );
				}
			} else
			{
				$(this).removeAttr('disabled');
			}

		});

		$('.option-select[optionName!="Quantity"]').each(function() {

			var selectedChildren = $(this).children('option:selected');

			if (selectedChildren.length>0) return;

			$(this).children('option:enabled:first').attr('selected', 'selected');
			$(this).val($(this).children('option:enabled:first').attr('value'));

		});

		$('.option-select[optionName!="Quantity"] option:selected:disabled').each(function() {

			var select = $(this).parent();
			select.children('option:enabled:first').attr('selected', 'selected');
			select.val(select.children('option:enabled:first').attr('value'));
			select.change();

		});

		$('.option-select[optionName!="Quantity"] option:disabled').hide();

		mailingServices();
		folding();
		paperType();
		// calculateTotal(1);
	});
}

function filterOptionValues(addToCart, buttonId)
{
	if (!productGrouping) return true;
    return true;
    //DEPRECATED

//	$('.option-select option').removeAttr('disabled').show();

//	var passed = [];
//	$('.option-select').each(function() {
//
//		passed.push($(this).attr('optionName'));
//
//		var optionName = $(this).attr('optionName');
//
//		var valueProducts = $(this).children('option:selected').attr('products');
//		if ((typeof valueProducts)=='undefined') valueProducts = '';
//		valueProducts = valueProducts.split('|');
//
//		$('.option-select option').each(function() {
//
//			if ($.inArray($(this).parent().attr('optionName'), passed)>-1) return;
//
//			var anyFound = false;
//			for (var i=0; i<valueProducts.length; i++) {
//				if (valueProducts[i]=='' || $(this).attr('products')=='') {
//					anyFound = true;
//					continue;
//				}
//
//			    if ($(this).attr('products')!=null) {
//                    if ($(this).attr('products').indexOf(valueProducts[i])>-1) {
//
//                        anyFound = true;
//                        break;
//                    }
//				}
//			}
//
//			if (!anyFound) {
//				$(this).attr('disabled', 'disabled');
//				$(this).hide();
//			}
//		});
//
//	});

//	var products = ($('#product option:selected').attr('products')!=null)?$('#product option:selected').attr('products').split('|'):[$('#product').val()];
	// var productsMatching = [];
	// var totalOptions = $('.option-select option:selected').length;
	// for (var i=0; i<products.length; i++) {
	// 	if (products[i]=='') continue;

	// 	if ($('.option-select option:selected[products*=\''+products[i]+'\']').length==totalOptions) {
	// 		productsMatching.push(products[i]);
	// 	}
	// }

	var productsMatching = findMatchingProducts();

//	var printTurnaroundMatchingQuantity = $('.option-select[optionName="Print Turnaround"] option[valueName*=" '+$('.option-select[optionName="Quantity"] option:selected').attr('valueName')+'"]');
//	if (printTurnaroundMatchingQuantity.length>0) {
//
//		var anyMatchingTheQuantity = false;
//
//		printTurnaroundMatchingQuantity.each(function() {
//
//			if ($(this).attr('valueName').endsWith($('.option-select[optionName="Quantity"] option:selected').attr('valueName'))) {
//				anyMatchingTheQuantity = true;
//			}
//
//		});
//
//		if (anyMatchingTheQuantity) {
//			$('.option-select[optionName="Print Turnaround"] option').attr('disabled', 'disabled').hide();
//
//			printTurnaroundMatchingQuantity.each(function() {
//
//				if ($(this).attr('valueName').endsWith($('.option-select[optionName="Quantity"] option:selected').attr('valueName'))) {
//					$(this).removeAttr('disabled');
//					$(this).show();
//				}
//
//			});
//		}
//	}

	if (!addToCart) {
		// console.info(productsMatching);
		if (productsMatching.length>0) {
			$('#product option:selected').attr('value', productsMatching[0]);
		}
		return productsMatching;
	} else {

		if (productsMatching.length==0) {
			$('#matchingProducts .modal-body').html('We did not find any products matching selected options. Please try again.');
			$('#matchingProducts').modal('show');
		} else
		if (productsMatching.length==1) {
			$('#product option:selected').attr('value', productsMatching[0]);

			$('#product-calculator *[name=Size]').attr('value', productsMatching[0]).val(productsMatching[0]);

			if ($('#add-to-cart-process').length>0) {
				$('#add-to-cart-process').attr('uniqueProductSelected', 1);
				$('#add-to-cart-design').attr('uniqueProductSelected', 1);
				$('#add-to-cart-design-calc').attr('uniqueProductSelected', 1);
				$('#add-to-cart-cbDesigner-calc').attr('uniqueProductSelected', 1);

                if ((buttonId === 'add-to-cart-design') || (buttonId === 'add-to-cart-design-calc') || (buttonId === 'add-to-cart-cbDesigner-calc')) {
                    $('#'+buttonId).click();
                } else {
                    $('#add-to-cart-process').click();
                }

			} else {

				$('#add-to-cart').attr('uniqueProductSelected', 1);
                $('#add-to-cart-design').attr('uniqueProductSelected', 1);
                $('#add-to-cart-design-calc').attr('uniqueProductSelected', 1);
                $('#add-to-cart-cbDesigner-calc').attr('uniqueProductSelected', 1);

                if ((buttonId === 'add-to-cart-design') || (buttonId === 'add-to-cart-design-calc') || (buttonId === 'add-to-cart-cbDesigner-calc')) {
                    $('#'+buttonId).click();
                } else {
                    $('#add-to-cart').click();
                }
			}
		} else {
			if ($('#add-to-cart-process').length>0) {
                $('#add-to-cart-design').attr('uniqueProductSelected', 0);
                $('#add-to-cart-design-calc').attr('uniqueProductSelected', 0);
                $('#add-to-cart-cbDesigner-calc').attr('uniqueProductSelected', 0);

                $('#add-to-cart-process').attr('uniqueProductSelected', 0);
			} else {
                $('#add-to-cart-design').attr('uniqueProductSelected', 0);
                $('#add-to-cart-design-calc').attr('uniqueProductSelected', 0);
                $('#add-to-cart-cbDesigner-calc').attr('uniqueProductSelected', 0);

				$('#add-to-cart').attr('uniqueProductSelected', 0);
			}

			$('#matchingProducts .modal-body').html('').append('We have found multiple products matching selected options.<br />Please select one.<br /><br />');

			for (var i=0; i<productsMatching.length; i++) {

				var productIt = {};
				var productItFound = false;
				for (var j=0; j<currentProductGroupProductsObjects.length; j++) {
					if (currentProductGroupProductsObjects[j].id==productsMatching[i]) {
						productIt = currentProductGroupProductsObjects[j];
						productItFound = true;
						break;
					}
				}

				if (!productItFound) continue;

				var productItPrice = '';
				for (var j=0; j<matchingProductsPrices.length; j++) {
					if (matchingProductsPrices[j].productId==productsMatching[i]) {
						productItPrice = ' - $'+matchingProductsPrices[j].price;
						break;
					}
				}

				$('#matchingProducts .modal-body').append('<a class="select-matching-product" buttonId="'+buttonId+'" productId="'+productsMatching[i]+'" href="#">'+productIt.title+productItPrice+'</a><br />');
			}

			$('#matchingProducts').modal('show');
		}
	}

}

$(document).ready(function() {

    $(document).on('keyup change', '.option-input[optionName="Quantity"]', function() {

        for (var i=0; i<autoQuantityKeyUpTimer.length; i++) {
            clearTimeout(autoQuantityKeyUpTimer[i]);
        }
        autoQuantityKeyUpTimer = [];

        autoQuantityKeyUpTimer.push(setTimeout("quantityKeyUp();", 500));

        if ((typeof shippingOptionsRun)!='undefined') shippingOptionsRun = 0; //Reset shipping option prices
    });

});

$(document).on('click', '.select-matching-product', function() {
	var productId = $(this).attr('productId');
    var buttonId = $(this).attr('buttonId');

	$('#product option:selected').attr('value', productId);
	$('#product-calculator *[name=Size]').attr('value', productId).val(productId);

	$('#matchingProducts').modal('hide');

	if ($('#add-to-cart-process').length>0) {
		$('#add-to-cart-process').attr('uniqueProductSelected', 1);
        $('#add-to-cart-design').attr('uniqueProductSelected', 1);
        $('#add-to-cart-design-calc').attr('uniqueProductSelected', 1);
        $('#add-to-cart-cbDesigner-calc').attr('uniqueProductSelected', 1);

        if ((buttonId == 'add-to-cart-design') || (buttonId == 'add-to-cart-design-calc') || (buttonId == 'add-to-cart-cbDesigner-calc')) {
            $('#'+buttonId).click();
        } else {
            $('#add-to-cart-process').click();
        }
	} else {
		$('#add-to-cart').attr('uniqueProductSelected', 1);
        $('#add-to-cart-design').attr('uniqueProductSelected', 1);
        $('#add-to-cart-design-calc').attr('uniqueProductSelected', 1);
        $('#add-to-cart-cbDesigner-calc').attr('uniqueProductSelected', 1);

        if ((buttonId == 'add-to-cart-design') || (buttonId == 'add-to-cart-design-calc') || (buttonId == 'add-to-cart-cbDesigner-calc')) {
            $('#'+buttonId).click();
        } else {
            $('#add-to-cart').click();
        }
	}

	return false;
});