/* Static JavaScript code for the Product List Attributes module */

var plac = new Array();
var pla_ajax = false;

function pla_sortNumeric(arg1, arg2)
{
	return (arg1 - arg2);
}

function pla_addProductCombination(id_product, id_combination, array_id_attribute, quantity, minimal_quantity, price, price_display, price_original, price_original_display, id_image)
{
	// Create an associative array with the data for this combination.
	element = new Array();
	element['id_combination'] = id_combination;
	// slice() causes the array to be copied.  We do not just want to copy a
	// pointer to the array because our copy of the array is modified below.
	element['array_id_attribute'] = array_id_attribute.slice();
	element['quantity'] = quantity;
	element['minimal_quantity'] = minimal_quantity;
	element['price'] = price;
	element['price_display'] = price_display;
	element['price_original'] = price_original;
	element['price_original_display'] = price_original_display;
	element['id_image'] = id_image;

	// Sort the array of id_attribute values.  This will make lookups faster.
	element['array_id_attribute'].sort(pla_sortNumeric);

	// Associate this associative array with the product in the overall plac
	// array.
	if (plac[id_product] == null)
	{
		plac[id_product] = new Array();
	}
	plac[id_product].push(element);
}

function pla_lookupProductCombination(id_product, array_id_attribute)
{
	combination = false;

	if (plac[id_product] instanceof Array)
	{
		// Sort the array_id_attribute parameter.
		local_array_id_attribute = array_id_attribute.slice();
		local_array_id_attribute.sort(pla_sortNumeric);

		// Outer loop over all combinations for this product.
		for (i = 0; i < plac[id_product].length; i++)
		{
			// If the combination doesn't have the same number of attributes as
			// we are looking for, ignore it.
			if (local_array_id_attribute.length == plac[id_product][i]['array_id_attribute'].length)
			{
				// All elements in array_id_attribute must exist in this
				// combination for there to be a match.
				match = true;
				for (j = 0; j <= local_array_id_attribute.length; j++)
				{
					if (local_array_id_attribute[j] != plac[id_product][i]['array_id_attribute'][j])
					{
						// Any mismatch means we can ignore this combination.
						match = false;
						break;
					}
				}

				// If the combination matched, remember it.  Also, it is
				// unnecessary to look for more combinations in this case.
				if (match)
				{
					combination = new Array();
					combination['id_combination'] = plac[id_product][i]['id_combination'];
					combination['quantity'] = plac[id_product][i]['quantity'];
					combination['minimal_quantity'] = plac[id_product][i]['minimal_quantity'];
					combination['price'] = plac[id_product][i]['price'];
					combination['price_display'] = plac[id_product][i]['price_display'];
					combination['price_original'] = plac[id_product][i]['price_original'];
					combination['price_original_display'] = plac[id_product][i]['price_original_display'];
					combination['id_image'] = plac[id_product][i]['id_image'];
					break;
				}
			}
		}
	}
	else
	{
		combination = false;
	}

	return combination;
}

function pla_lookupProductAttributes(id_product)
{
	array_id_attribute = new Array();

	$('select[name^="pla_attribute_' + id_product + '_"]').each(function() {
		id_attribute = parseInt($(this).val());
		if (!isNaN(id_attribute) && (id_attribute >= 1))
		{
			array_id_attribute.push(id_attribute);
		}
	});

	return array_id_attribute;
}

function pla_catchAddEvent(event)
{
	// The value to return.
	return_value = false;
	rel = $(this).attr('rel');
	id_product = parseInt(rel.substr(16));
	if (!isNaN(id_product) && (id_product >= 1))
	{
		array_id_attribute = new Array();
		$("select[name^='pla_attribute_" + id_product + "_']").each(function() {
			id_attribute = parseInt($(this).val());
			if (!isNaN(id_attribute) && (id_attribute >= 1))
			{
				array_id_attribute.push(id_attribute);
			}
		});

		quantity = 1;
		$("input[name='pla_quantity_" + id_product + "']").each(function() {
			quantity_field = parseInt($(this).val());
			if (!isNaN(quantity_field) && (quantity_field >= 1))
			{
				quantity = quantity_field;
			}
		});

		if (array_id_attribute.length == 0)
			combination = null;
		else
			combination = pla_lookupProductCombination(id_product, array_id_attribute);

		if (combination === false)
		{
			// This is a failsafe because the customer should ideally be unable
			// to click the Add to Cart button at all while an invalid
			// combination is selected.
			alert(pla_status_no_combination);

			// Prevent the default action.  The default may be to add the item
			// to the cart.  Without a valid combination, this should be
			// suppressed.
			return_value = false;
		}
		else
		{
			if (combination === null)
				id_combination = null;
			else
				id_combination = combination['id_combination'];

			if (pla_ajax)
			{
				ajaxCart.add(id_product, id_combination, false, this, quantity);

				// Workaround for PS 1.4.1.
				$('.pla_ajax_add_to_cart_button').removeAttr('disabled');

				// Prevent the default action, which is likely to be a duplicate
				// addition of the item to the cart.
				return_value = false;
			}
			else
			{
				// Update the href to go to the combination.
				// Do nothing if href is undefined or a zero-length string.
				href = $(this).attr('href');
				if (href)
				{
					ipa_begin = href.indexOf('&ipa=');
					if (ipa_begin == -1)
						ipa_begin = href.indexOf('?ipa=');
					if (ipa_begin >= 0)
					{
						ipa_end = href.indexOf('&', ipa_begin + 5);
						new_href = href.substr(0, ipa_begin + 5) + ((id_combination === null) ? '' : id_combination);
						if (ipa_end >= 0)
							new_href += href.substr(ipa_end);
						href = new_href;
					}
					else
					{
						if ('&' == href.charAt(href.length - 1))
							href = href + 'ipa=';
						else
							href = href + '&ipa=';
						href = href + ((id_combination === null) ? '' : id_combination);
					}

					qty_begin = href.indexOf('&qty=');
					if (qty_begin == -1)
						qty_begin = href.indexOf('?qty=');
					if (qty_begin >= 0)
					{
						qty_end = href.indexOf('&', qty_begin + 5);
						new_href = href.substr(0, qty_begin + 5) + quantity;
						if (qty_end >= 0)
							new_href += href.substr(qty_end);
						href = new_href;
					}
					else
					{
						if ('&' == href.charAt(href.length - 1))
							href = href + 'qty=' + quantity;
						else
							href = href + '&qty=' + quantity;
					}
					$(this).attr('href', href);
				}
				return_value = true;
			}
		}
	}

	return return_value;
}

function pla_catchChangeAttributeEvent(pla_product)
{
	var id_attribute;

	var name = '';
	if (pla_product.length)
		name = pla_product.attr('name');
	else
		name = $(this).attr('name');
	var name_id_values = name.substr(14);
	underscore_position = name_id_values.indexOf('_');
	if (underscore_position == -1)
	{
		id_product = parseInt(name_id_values);
		id_attribute_group = 0;
	}
	else
	{
		id_product = parseInt(name_id_values.substr(0, underscore_position));
		id_attribute_group = parseInt(name_id_values.substr(underscore_position + 1));
	}

	if (!isNaN(id_product) && (id_product >= 1))
	{
		array_id_attributes = pla_lookupProductAttributes(id_product);
	}
	var combination = pla_lookupProductCombination(id_product, array_id_attribute);

	if (combination['quantity'] <= 0 && !pla_products_oos[id_product])
	{
		$('#pla_block_' + id_product+' .availability').html(
			(pla_products_quantity[id_product] > 0)
				? (pla_is_homefeatured
					? ''
					: pla_status_oos_combination)
				: (pla_is_homefeatured
					? ''
					: pla_status_oos_product));
		$('#pla_block_' + id_product + ' .pla_ajax_add_to_cart_button:visible').hide();
		$('#pla_block_' + id_product + ' .pla_disabled_add_to_cart_button:hidden').show();
		if (combination['id_image'])
		{
			$('li#pla_block_' + id_product + ' a.product_img_link img').attr('src', pla_product_directory + id_product + '-' + combination['id_image'] + '-home.jpg');
			$('li#pla_block_' + id_product + ' a.product_image img').attr('src', pla_product_directory + id_product + '-' + combination['id_image'] + '-home.jpg');
		}
	}
	else if (!combination)
	{
		$('#pla_block_' + id_product+' .availability').html(pla_is_homefeatured
			? ''
			: pla_status_no_combination);
		$('#pla_block_' + id_product + ' .pla_ajax_add_to_cart_button:visible').hide();
		$('#pla_block_' + id_product + ' .pla_disabled_add_to_cart_button:hidden').show();
	}
	else
	{
		if (combination['quantity'] <= 0 && pla_products_oos[id_product])
		{
			$('#pla_block_' + id_product+' .availability').html(pla_products_messages_available_later[id_product]
				? pla_products_messages_available_later[id_product]
				: (pla_is_homefeatured
					? ''
					: pla_status_available));
		}
		else
		{
			$('#pla_block_' + id_product+' .availability').html(pla_products_messages_available_now[id_product]
				? pla_products_messages_available_now[id_product]
				: (pla_is_homefeatured
					? ''
					: pla_status_available));
		}

		pla_updatePrice(id_product,
			combination['price'], combination['price_display'],
			combination['price_original'], combination['price_original_display']);
		$('#pla_block_' + id_product + ' .pla_quantity').attr('value', combination['minimal_quantity']);
		$('#pla_block_' + id_product + ' .pla_disabled_add_to_cart_button:visible').hide();
		$('#pla_block_' + id_product + ' .pla_ajax_add_to_cart_button:hidden').show();
		if (combination['id_image'])
		{
			$('li#pla_block_' + id_product + ' a.product_img_link img').attr('src', pla_product_directory + id_product + '-' + combination['id_image'] + '-home.jpg');
			$('li#pla_block_' + id_product + ' a.product_image img').attr('src', pla_product_directory + id_product + '-' + combination['id_image'] + '-home.jpg');
		}
	}

	// id_attribute = parseInt($('select[name="pla_attribute_' + id_product + '_' + id_attribute_group + '"]').val());
	// if (isNaN(id_attribute) || (id_attribute < 1))
	//	id_attribute = 0;

	// var swatch_selector = '#pla_color_swatch_' + id_product + '_' + id_attribute_group;
	// $(swatch_selector + ' div.pla_color_container_selected').removeClass('pla_color_container_selected');
	// $(swatch_selector + ' #pla_color_container_' + id_product + '_' + id_attribute).addClass('pla_color_container_selected');

	if (pla_ready && pla_is_homefeatured)
	{
		pla_updateHomeFeaturedAvailabilityHeight();
		pla_updateHomeFeaturedAttributesHeight();
	}

	return true;
}

function pla_updatePrice(id_product, price, price_display, price_original, price_original_display)
{
	if (price < price_original)
		$('#pla_block_' + id_product + ' .price').html(price_display + '<br /><span class="pla_original_price">' + price_original_display + '</span>');
	else
		$('#pla_block_' + id_product + ' .price').html(price_display);
}

function pla_updateColorSelect(id_product, id_attribute_group, id_attribute)
{
	var select_selector = 'select[name="pla_attribute_' + id_product + '_' + id_attribute_group + '"]';

	$(select_selector + ' option[value="' + id_attribute + '"]').attr('selected', 'selected');
	pla_catchChangeAttributeEvent($(select_selector));
}

function pla_updateHomeFeaturedAvailabilityHeight()
{
	var homefeatured_availability_max_height = 0;
	var current_height;

	$('#featured-products_block_center .pla_attributes .availability').fadeOut().fadeIn();

	$('#featured-products_block_center .pla_attributes .availability').each(function(index) {
		current_height = parseInt($(this).height());
		if (homefeatured_availability_max_height < current_height)
			homefeatured_availability_max_height = current_height;
	});
	if (homefeatured_availability_max_height > 0)
	{
		// $('#featured-products_block_center .pla_attributes').height(pla_homefeatured_div_max_height + homefeatured_availability_max_height);
		$('#featured-products_block_center .pla_attributes .availability').css('min-height', homefeatured_availability_max_height + 'px');
	}
}

function pla_updateHomeFeaturedAttributesHeight()
{
	var pla_homefeatured_div_max_height = 0;
	var current_height;

	$('#featured-products_block_center .pla_attributes').each(function(index) {
		current_height = parseInt($(this).height());
		if (pla_homefeatured_div_max_height < current_height)
			pla_homefeatured_div_max_height = current_height;
	});
	if (pla_homefeatured_div_max_height > 0)
	{
		$('#featured-products_block_center div.block_content ul').height(pla_homefeatured_ul_original_height + pla_homefeatured_div_max_height);
		$('#featured-products_block_center .pla_attributes').css('min-height', pla_homefeatured_div_max_height);
	}
}

