///////////////////////////////////////////////////////////////////////////
//                        NEW ADD TO CART FUNCTIONS                      //
///////////////////////////////////////////////////////////////////////////

/**
 * On DOM ready:
 *   foreach form, if out of stock behavior is do not allow purchase, check
 *   availability
 */
$(document).ready(function() {
	//
	// Force a check of available of stock for any form that has its out of
	// stock behavior set to "do not allow purchase".
	//
	$('.add_to_cart_id').each(function() {
		var add_to_cart_id = $(this).val();
		var out_of_stock_behavior = $('#pcs_out_of_stock_behavior-' + add_to_cart_id).val();
		if(out_of_stock_behavior == undefined || out_of_stock_behavior.length == 0 || out_of_stock_behavior == 'do_not_allow_purchase') {
			pcs_handle_selection(add_to_cart_id, 0, 0);
		}
	});
});

/**
 * Handle user choices.  This function is called when a swatch or anchor div is
 * clicked on, or a select drop-down is changed.
 *
 * @param string add_to_cart_id The unique identifier for this particular
 *   Product Configuration Selector.
 * @param string option_type_id The option type ID being selected.
 * @param string option_id The option ID being selected.  May be undefined.
 */
function pcs_handle_selection(add_to_cart_id, option_type_id, option_id) {
	var source_form;
	var render_type;
	var product_id;
	var tag_name;

	product_id = $('#pcs_product_id-' + add_to_cart_id).val();
	if(product_id == undefined || product_id.length == 0) {
		return;
	}

	tag_name = $('#pcs_tag_name-' + add_to_cart_id).val();
	if(tag_name == undefined || tag_name.length == 0) {
		return;
	}

	//
	// For swatch and anchor style tags, mark the element as selected, and set
	// the text above the selector to the option that has been chosen.
	//

	render_type = pcs_determine_render_type(add_to_cart_id, option_type_id);

	if(render_type == 'anchor' || render_type == 'swatch') {
		$('.pcs_option-' + add_to_cart_id + '-' + option_type_id).removeClass('selected_config');

		if(option_id != undefined) {
			$('#pcs_option-' + add_to_cart_id + '-' + option_type_id + '-' + option_id).addClass('selected_config');
			$('#pcs_current_label-' + add_to_cart_id + '-' + option_type_id).html($('#pcs_option-' + add_to_cart_id + '-' + option_type_id + '-' + option_id).attr('option_name'));
			$('#pcs_current_value-' + add_to_cart_id + '-' + option_type_id).val(option_id);
		}
	}
	else {
		option_id = $('#pcs_select-' + add_to_cart_id + '-' + option_type_id).val();
	}

	//
	// Set the price accordingly
	//

	update_dynamic_price('pcs_price_display-' + add_to_cart_id + '-' + option_type_id, '', product_id, tag_name, false, option_id);

	//
	// Check availability
	//

	source_form = 'form#add_to_cart_product_' + add_to_cart_id;
	$.ajax({
		url: 'ajax_targets/add_to_cart_check_availability.php?chosen_option_type_id=' + option_type_id + '&chosen_option_id=' + option_id,
		data: $(source_form).serialize(),
		dataType: 'json',
		success: function(data) {
			pcs_handle_add_to_cart_check_availability(add_to_cart_id, data);
		}
	});

}

/**
 * Compares two option strings and determines if the alternate option string is
 * a subset of the current one.
 *
 * @param string current_option_string The current option string being
 *   processed.
 * @param string altenate_option_string A cached option string.
 *
 * @return boolean true if the alternate option string is a subset of the
 *   current option string.
 */
function pcs_option_string_contains(current_option_string, alternate_option_string) {
	var current_options;
	var current_offset;
	var alternate_options;
	var alternate_offset;
	var matched;

	//
	// Basic validation
	//

	if(current_option_string == '*') {
		return false;
	}

	if(alternate_option_string == '*') {
		return true;
	}

	//
	// All of the alternate options must exist in the current options
	//

	alternate_options = alternate_option_string.split(',');
	current_options = current_option_string.split(',');

	for(alternate_offset=0; alternate_offset<alternate_options.length; alternate_offset++) {
		matched = false;
		for(current_offset=0; current_offset<current_options.length; current_offset++) {
			if(alternate_options[alternate_offset] == current_options[current_offset]) {
				matched = true;
				break;
			}
		}
		if(!matched) {
			return false;
		}
	}

	return true;
}

/**
 * Determines the render type used by a particular option type.
 *
 * @param string add_to_cart_id The unique identifier for this particular
 *   Product Configuration Selector.
 * @param string option_type_id The option type ID being reviewed.
 *
 * @return enum One of 'anchor', 'select', or 'swatch'.
 */
function pcs_determine_render_type(add_to_cart_id, option_type_id) {
	if($('#pcs_select-' + add_to_cart_id + '-' + option_type_id).length > 0) {
		return 'select';
	}

	if($('#pcs_reset_link_span-' + add_to_cart_id + '-' + option_type_id + '.swatch_value').length > 0) {
		return 'swatch';
	}

	return 'anchor';
}

/**
 * A associative array that maintains known states for each option on the form,
 * based on other choices made.  This is done to show out of stock or
 * unavailable messages after a choice has been made on an option type.  (After
 * a choice has been made on an option type, no check is made on other members
 * of the option type during the AJAX availability check.)
 *
 * {
 * 	 add_to_cart_id: {
 * 	   option_type_id: {
 * 	     option_id: {
 * 	       '*': this_options_state
 * 	       '12345': this_options_state
 * 	       '12345,12346': this_options_state
 * 	     },
 * 	     option_id: ...,
 * 	   },
 * 	   option_type_id: ...,
 * 	 },
 * 	 add_to_cart_id: ...,
 * }
 *
 */
var cached_statuses = new Object();

/**
 * Handles the response from an add_to_cart_check_availability AJAX request.
 *
 * @param string add_to_cart_id The unique identifier for this particular
 *   Product Configuration Selector.
 * @param Object data The result of an add_to_cart_check_availability AJAX
 *   request.
 */
function pcs_handle_add_to_cart_check_availability(add_to_cart_id, data) {
	var alternate_option_string;
	var alternate_state;
	var current_option_string;
	var current_state;
	var element_selector;
	var force_reset_link;
	var offset;
	var option_id;
	var option_type_id;
	var out_of_stock_behavior;
	var out_of_stock_message;
	var render_type;
	var show_reset_links;
	var visble_count;

	//
	// Initialization
	//

	out_of_stock_behavior = $('#pcs_out_of_stock_behavior-' + add_to_cart_id).val();
	if(out_of_stock_behavior == undefined || out_of_stock_behavior.length == 0) {
		out_of_stock_behavior = 'do_not_allow_purchase';
	}

	out_of_stock_message = $('#pcs_out_of_stock_message-' + add_to_cart_id).val();
	if(out_of_stock_message == undefined || out_of_stock_message.length == 0) {
		out_of_stock_message = 'out of stock';
	}

	force_reset_link = $('#pcs_force_reset_link-' + add_to_cart_id).val();
	if(force_reset_link == undefined || force_reset_link.length == 0) {
		force_reset_link = 'out of stock';
	}

	//
	// Handle any option types that are being forcibly unset
	//

	for(offset in data['discarded_option_types']) {
		pcs_reset_selection_soft(add_to_cart_id, data['discarded_option_types'][offset]);
	}

	//
	// Pull the current options
	//

	current_option_string = '';
	for(option_type_id in data['chosen_options']) {
		current_option_string += (current_option_string == '' ? '' : ',') + data['chosen_options'][option_type_id];
	}
	if(current_option_string == '') {
		current_option_string = '*';
	}

	//
	// Grab any availability data, merge it with existing data, and set each
	// option accordingly.
	//
	// States: unavailable, in stock, out of stock, option type chosen
	//

	for(option_type_id in data['availability']) {
		render_type = pcs_determine_render_type(add_to_cart_id, option_type_id);

		$('#pcs_out_of_stock_display-' + add_to_cart_id + '-' + option_type_id).css('display', 'none');
		$('#pcs_unavailable_display-' + add_to_cart_id + '-' + option_type_id).css('display', 'none');

		for(option_id in data['availability'][option_type_id]) {
			//
			// Determine the state of the given option, based on the state
			// returned from the availability checks, and any other checks that
			// may have been run.
			//

			current_state = data['availability'][option_type_id][option_id];

			if(cached_statuses[add_to_cart_id] == undefined) {
				cached_statuses[add_to_cart_id] = new Object();
			}
			if(cached_statuses[add_to_cart_id][option_type_id] == undefined) {
				cached_statuses[add_to_cart_id][option_type_id] = new Object();
			}
			if(cached_statuses[add_to_cart_id][option_type_id][option_id] == undefined) {
				cached_statuses[add_to_cart_id][option_type_id][option_id] = new Object();
			}

			if(current_state != 'option type chosen') {
				cached_statuses[add_to_cart_id][option_type_id][option_id][current_option_string] = current_state;
			}

			if(current_state != 'unavailable') {
				for(alternate_option_string in cached_statuses[add_to_cart_id][option_type_id][option_id]) {
					if(alternate_option_string == current_option_string) {
						continue;
					}
					alternate_state = cached_statuses[add_to_cart_id][option_type_id][option_id][alternate_option_string];

					if(alternate_state == 'in stock') {
						// there's no point in evaluating this option further; we assume in stock if not proven otherwise
						continue;
					}

					if(pcs_option_string_contains(current_option_string, alternate_option_string)) {
						// force unavailable and stop processing
						if(alternate_state == 'unavailable') {
							current_state = alternate_state;
							break;
						}

						// force OOS message; and copy any state if the current state is unknown
						if(alternate_state == 'out of stock' || current_state == 'option type chosen') {
							current_state = alternate_state;
						}
					}

				}
			}

			//
			// Handle the display or hiding of the option as needed.
			//

			if(render_type == 'select') {
				element_selector = '#pcs_select-' + add_to_cart_id + '-' + option_type_id + ' option[value="' + option_id + '"]';
				if($(element_selector).length == 0) {
					continue;
				}

				if($(element_selector).data('original_label') == undefined) {
					$(element_selector).data('original_label', $(element_selector).html());
				}

				switch(current_state) {
					case 'out of stock':
						$(element_selector).html($(element_selector).data('original_label') + ' ' + out_of_stock_message);
						$(element_selector).attr('disabled', 'disabled');
						break;

					case 'unavailable':
						$(element_selector).html($(element_selector).data('original_label') + ' (not available)');
						$(element_selector).attr('disabled', 'disabled');
						break;

					default: // in stock, option type chosen
						$(element_selector).html($(element_selector).data('original_label'));
						$(element_selector).removeAttr('disabled');
						break;
				}
			}
			else { // anchor and swatch
				element_selector = '#pcs_option-' + add_to_cart_id + '-' + option_type_id + '-' + option_id;
				if($(element_selector).length == 0) {
					continue;
				}

				$(element_selector).unbind('mouseover');
				$(element_selector).unbind('mouseout');

				if(current_state == 'out of stock' || current_state == 'unavailable') {
					if(out_of_stock_behavior == 'do_not_display') {
						$(element_selector).css('display', 'none');
					}
					else {
						$(element_selector).addClass('config_out_of_stock');

						if(current_state == 'out of stock') {
							$(element_selector).bind('mouseover', pcs_show_out_of_stock_message);
							$(element_selector).bind('mouseout', pcs_hide_out_of_stock_message);
						}
						else {
							$(element_selector).bind('mouseover', pcs_show_unavailable_message);
							$(element_selector).bind('mouseout', pcs_hide_unavailable_message);
						}
					}
				}
				else { // in stock, option type chosen
					if(out_of_stock_behavior == 'do_not_display') {
						$(element_selector).css('display', 'inline');
					}
					else {
						$(element_selector).removeClass('config_out_of_stock');
					}
				}

			}

		}
	}

	//
	// Handle reset links.  Calculate whether or not reset links need to be
	// shown, and then show them on any selection with a chosen value.
	//

	show_reset_links = force_reset_link;

	if(!force_reset_link && out_of_stock_behavior == 'do_not_display') {
		for(option_type_id in data['availability']) {
			render_type = pcs_determine_render_type(add_to_cart_id, option_type_id);
			if(render_type != 'select') { // anchor or swatch
				if($('.pcs_option-' + add_to_cart_id + '-' + option_type_id).length > 1) {
					visible_count = 0;
					$('.pcs_option-' + add_to_cart_id + '-' + option_type_id).each(function() {
						if($(this).css('display') != 'none') {
							visible_count++;
						}
					});
					if(visible_count <= 1) {
						show_reset_links = true;
						break;
					}
				}
			}
		}
	}

	if(show_reset_links) {
		for(option_type_id in data['availability']) {
			if($('#pcs_current_value-' + add_to_cart_id + '-' + option_type_id).val() != '') {
				$('#pcs_reset_link-' + add_to_cart_id + '-' + option_type_id).css('display', 'inline');
			}
			else {
				$('#pcs_reset_link-' + add_to_cart_id + '-' + option_type_id).css('display', 'none');
			}
		}
	}
	else {
		$('.pcs_reset_link-' + add_to_cart_id).css('display', 'none');
	}

}

/**
 * Parses the id of the chosen jQuery object.
 *
 * @param jQuery which The jQuery object being evaluated.
 */
function pcs_parse_jquery_id(which) {
	var id;
	var split_id;

	id = $(which).attr('id');
	if(id == undefined || id == '') {
		return undefined;
	}
	split_id = id.split('-');
	return {
		prefix: split_id[0],
		add_to_cart_id: split_id[1],
		option_type_id: split_id[2],
		option_id: split_id[3]
	};
}

/**
 * Parses the passed event and parses the ID of the div (or surrounding div).
 *
 * @param Event event The calling event.
 */
function pcs_parse_event_target(event) {
	var ret = pcs_parse_jquery_id($(event.target));
	if(ret == undefined) {
		// grab the surrounding div
		ret = pcs_parse_jquery_id($(event.target).parents('div:first'));
	}
	return ret;
}

/**
 * Shows the "out of stock" roll-over message.
 *
 * @param Event event The calling event.
 */
function pcs_show_out_of_stock_message(event) {
	var details = pcs_parse_event_target(event);
	if(details == undefined || details['prefix'] != 'pcs_option') {
		return;
	}
	$('#pcs_out_of_stock_display-' + details['add_to_cart_id'] + '-' + details['option_type_id']).css('display', 'inline');
}

/**
 * Hides the "out of stock" roll-over message.
 *
 * @param Event event The calling event.
 */
function pcs_hide_out_of_stock_message(event) {
	var details = pcs_parse_event_target(event);
	if(details == undefined || details['prefix'] != 'pcs_option') {
		return;
	}
	$('#pcs_out_of_stock_display-' + details['add_to_cart_id'] + '-' + details['option_type_id']).css('display', 'none');
}

/**
 * Shows the "unavailable" roll-over message.
 *
 * @param Event event The calling event.
 */
function pcs_show_unavailable_message(event) {
	var details = pcs_parse_event_target(event);
	if(details == undefined || details['prefix'] != 'pcs_option') {
		return;
	}
	$('#pcs_unavailable_display-' + details['add_to_cart_id'] + '-' + details['option_type_id']).css('display', 'inline');
}

/**
 * Hides the "unavailable" roll-over message.
 *
 * @param Event event The calling event.
 */
function pcs_hide_unavailable_message(event) {
	var details = pcs_parse_event_target(event);
	if(details == undefined || details['prefix'] != 'pcs_option') {
		return;
	}
	$('#pcs_unavailable_display-' + details['add_to_cart_id'] + '-' + details['option_type_id']).css('display', 'none');
}

/**
 * Resets a selection without performing an availability check.
 *
 * @param string add_to_cart_id The unique identifier for this particular
 *   Product Configuration Selector.
 * @param string option_type_id The option type ID being reviewed.
 */
function pcs_reset_selection_soft(add_to_cart_id, option_type_id) {
	var product_id;
	var tag_name;

	product_id = $('#pcs_product_id-' + add_to_cart_id).val();
	if(product_id == undefined || product_id.length == 0) {
		return;
	}

	tag_name = $('#pcs_tag_name-' + add_to_cart_id).val();
	if(tag_name == undefined || tag_name.length == 0) {
		return;
	}

	if(pcs_determine_render_type(add_to_cart_id, option_type_id) == 'select') {
		// reset select lists
		$('#pcs_select-' + add_to_cart_id + '-' + option_type_id).val(0);
	}
	else {
		// reset anchor and swatch selectors
		$('.pcs_option-' + add_to_cart_id + '-' + option_type_id).removeClass('selected_config');
		$('#pcs_current_label-' + add_to_cart_id + '-' + option_type_id).html('please choose');
		$('#pcs_current_value-' + add_to_cart_id + '-' + option_type_id).val('');
	}

	update_dynamic_price('pcs_price_display-' + add_to_cart_id + '-' + option_type_id, '', product_id, tag_name, false, undefined);
}

/**
 * Resets a selection and performs an availability check.
 *
 * @param string add_to_cart_id The unique identifier for this particular
 *   Product Configuration Selector.
 * @param string option_type_id The option type ID being reviewed.
 */
function pcs_reset_selection(add_to_cart_id, option_type_id) {
	pcs_reset_selection_soft(add_to_cart_id, option_type_id);
	pcs_handle_selection(add_to_cart_id, option_type_id, undefined);
}

/**
 * Reviews the configurations associated with a given add_to_cart_id, and verifies
 * that a choice has been made for each option.
 *
 * @param string add_to_cart_id The unique identifier for this particular
 *   Product Configuration Selector.
 */
function pcs_submit_review(add_to_cart_id) {
	var valid = true;
	var message = '';
	var generic_message = false;
	var details;
	var label;

	$('.pcs_configuration_value-' + add_to_cart_id).each(function() {
		if($(this).val() == '' || $(this).val() == '0') {
			valid = false;

			details = pcs_parse_jquery_id($(this));
			if(details != undefined && details['add_to_cart_id'] != undefined && details['option_type_id'] != undefined) {
				label = $('#pcs_label-' + details['add_to_cart_id'] + '-' + details['option_type_id']).html();
				if(label != null && label != undefined) {
					message += (message != '' ? "\n" : '') + 'Please select a "' + label.replace(/:$/, '') + '".';
				}
				else {
					generic_message = true;
				}
			}
		}
	});

	if(!valid) {
		if(generic_message) {
			message = 'All configuration options must be chosen before this item can be added to your shopping cart.';
		}

		alert(message);
	}

	return valid;
}

/**
 * Submits the given form via an AJAX call and renders the result.
 *
 * @param string add_to_cart_id The unique identifier for this particular
 *   Product Configuration Selector.
 * @param string product_id The product ID being submitted.
 * @param string callback_function A function to call upon successful add, for
 *   follow-up processing.
 */
function pcs_add_to_cart_background(add_to_cart_id, product_id, callback_function) {
	if(!pcs_submit_review(add_to_cart_id)) {
		return false;
	}

	source_form = 'form#add_to_cart_product_' + add_to_cart_id;
	$.ajax({
		url: 'ajax_targets/base_add_to_cart.php',
		data: $(source_form).serialize(),
		dataType: 'json',
		success: function(data) {
			var success = false;
			var message = '';
			for(var row_id in data['results']) {
				if(data['results'][row_id]['success']) {
					success = true;
				}
				if(data['results'][row_id]['message'] != '' && data['results'][row_id]['message'] != undefined) {
					message += (message != '' ? "\n" : '') + data['results'][row_id]['message'];
				}
			}

			if(message != '') {
				alert(message);
			}

			if(success) {
				if($('#hidden_minicartholder').length > 0 && $('#hidden_minicartholder').val() != '') {
					$('#' + $('#hidden_minicartholder').val()).html(data['minicart']);
				}
				else {
					$('#minicartblock').html(data['minicart']);
				}

				if(callback_function != 0) { 
					callback_function();
				}
			}
		},
		error: function(data) {
			alert("An error occurred while adding this item to your cart.  Please try again.");
		}
	});

	return false;
}

///////////////////////////////////////////////////////////////////////////
//                            LEGACY FUNCTIONS                           //
///////////////////////////////////////////////////////////////////////////

function change_page(link) {
   href = link.getAttribute("href");
   var current_page = YAHOO.util.History.getQueryStringParameter("current_page", href) || "1";
   var results = YAHOO.util.History.getQueryStringParameter("results_per_page", href) || document.getElementById('hidden_results_per_page').value || "";
   var order_by = YAHOO.util.History.getQueryStringParameter("order_by", href) || document.getElementById('hidden_order_by').value || "";
   var order_by_2 = YAHOO.util.History.getQueryStringParameter("order_by_2", href) || document.getElementById('hidden_order_by_2').value || "";
   var order_by_3 = YAHOO.util.History.getQueryStringParameter("order_by_3", href) || document.getElementById('hidden_order_by_3').value || "";

   var form_search_params = get_escaped_hidden_search_params();
   var search_params = YAHOO.util.History.getQueryStringParameter("search_params", href) || form_search_params || "";
   var state = '?current_page=' + current_page + '&results_per_page=' + results + '&order_by=' + order_by;
   if (order_by_2 != "") {state += '&order_by_2=' + order_by_2};
   if (order_by_3 != "") {state += '&order_by_3=' + order_by_3};
   state += '&search_params=' + search_params;
   
   if (document.getElementById('no_search')) {
   	document.getElementById('no_search').value = 'search';
   }
   try {
	  YAHOO.util.History.navigate("product_listing", state);
   } catch (e) {
	  location.href = href;
   }
}

function on_select_results_per_page_change(select_box) {
   href = select_box.options[select_box.selectedIndex].value;
   var current_page = YAHOO.util.History.getQueryStringParameter("current_page", href) || "1";
   var results = YAHOO.util.History.getQueryStringParameter("results_per_page", href) || document.getElementById('hidden_results_per_page').value || "";
   var order_by = YAHOO.util.History.getQueryStringParameter("order_by", href) || document.getElementById('hidden_order_by').value || "";
   var form_search_params = get_escaped_hidden_search_params();
   var search_params = YAHOO.util.History.getQueryStringParameter("search_params", href) || form_search_params || "";
   var state = '?current_page=' + current_page + '&results_per_page=' + results + '&order_by=' + order_by + '&search_params=' + search_params;
   if (document.getElementById('no_search')) {
   	document.getElementById('no_search').value = 'search';
   }
   try {
	  YAHOO.util.History.navigate("product_listing", state);
   } catch (e) {
	  location.href = href;
   }
}

function check_numeric(e) {
	var number_codes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
	var found = false;
	if (e.type == 'keypress') {
		if (e.keyCode != 0) {
			return true;
		}
		for (num_code in number_codes) {
			if (e.charCode == number_codes[num_code]) {
				found = true;
			}
		}
	}

	if (found) {
		return true;
	}

	if (e && e.preventDefault) {
		e.preventDefault();
	}
	return false;
}

function buttonEnter(e, buttonid) {
    var bt = document.getElementById(buttonid);
    var key = window.event ? e.keyCode : e.which;
    if (key == 13) {
		bt.click();
    }
}

function buttonEnter(e, buttonid) {
    var bt = document.getElementById(buttonid);
    var key = window.event ? e.keyCode : e.which;
    if (key == 13) {
		bt.click();
    }
}

function check_configuration_selection(model_id, suffix, tag_name) {
	var unselected_config_labels = [];
	$("form#add_to_cart_product_" + tag_name + "_" + model_id + suffix + " select, form#add_to_cart_product_" + tag_name + "_" + model_id + suffix + " input").each(function() {
		pattern = new RegExp("configurations\\[(.*)\\]", "gi");
		matches = pattern.exec(this.name);
		if (matches != null) {
			config_label = matches[1];
			if (config_label.length > 0) {
				if (this.value == "" || this.value=='none') {
					config_label = config_label.replace(/_/, " ");
					unselected_config_labels.push(config_label);
				}
				else { 
					this.value = this.value.replace(tag_name+'_','')
				}
			}
		}
	});
	if (unselected_config_labels.length > 0) {
		var msg = "";
		for(i = 0; i < unselected_config_labels.length; i++) {
			msg += (msg ? "\n" : "") + "Please select a \"" + unselected_config_labels[i] + "\".";
		}
		alert(msg);
		return false;
	} else {
		return true;
	}
}

function empty_menus(config_type, product_id) {
	var config_selection_string = 'configuration_selector_'+product_id+'_'+config_type;
	var config_selector = document.getElementById('configuration_selector_' + product_id + '_' + config_type);
	var sandu_id;
	
	if (config_selector.type == 'hidden') {
		for (sandu_id in starting_popup_data[product_id][config_type]) {
			if (sandu_id == 'none' || sandu_id == '') {
				continue;
			}
			var lookup_value = starting_popup_data[product_id][config_type][sandu_id][5]+'_'+sandu_id;
			document.getElementById(lookup_value).style.display = 'none';
		}
	}
	else {
		config_selector.length = 0;
	}
}

function add_option_to_menu(product_id, current_popup_menu_data, menu_info, availability, allow_purchase, out_of_stock_message){
	var option;
	var selected = false;
	var has_selection = true;
	var i;
	for (i=0;i<current_popup_menu_data.length;i++) {
		if (current_popup_menu_data[i][0] == menu_info[0] && current_popup_menu_data[i][1] == menu_info[1]) {
			selected = true;
		}
		if (current_popup_menu_data[i][0] == menu_info[0] && (current_popup_menu_data[i][1] == 'none' || current_popup_menu_data[i][1] == '')) {
			has_selection = false;
		}
	}

	if (menu_info[1] == 'none' || menu_info[1] == '') {
		if (has_selection) {
			option = new Option('choose a different ' + menu_info[0], 'none', false);
		}
		else {
			option = new Option(menu_info[2], menu_info[1], false);
			option.selected = true;
		}
	}
	else if (availability == 'in_stock' || (availability == 'out_of_stock' && allow_purchase)) {
		option = new Option(menu_info[2], menu_info[1], false);
		option.selected = selected;
	}
	else if (availability == 'out_of_stock') {
		if (/msie/i.test(navigator.userAgent) && !/8\.0/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
			return;
		}
		option = new Option(menu_info[2] + ' ' + out_of_stock_message, menu_info[1], false);
		option.disabled = true;
		option.selected = selected;
	}
	else if (availability == 'not_available') {
		if (/msie/i.test(navigator.userAgent) && !/8\.0/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
			return;
		}
		option = new Option(menu_info[2] + ' (not available)', menu_info[1], false);
		option.disabled = true;
		option.selected = selected;
	}

	// add option to menu
	try {
		document.getElementById('configuration_selector_' + product_id + '_' + menu_info[0]).add(option,null);
	} catch(e) {
		document.getElementById('configuration_selector_' + product_id + '_' + menu_info[0]).add(option);
	}
}

function check_availability(config_id, config_type, current_popup_menu_data, product_id) {
	var i;
	var j;
	var k;
	var current_type;
	var skip_loop = true;
	// Cloning a copy of the skus for this config
	var config_skus = new Object();
	for (i in product_config_array[product_id][config_type][config_id]) {
		config_skus[i] = product_config_array[product_id][config_type][config_id][i];
	}
	var available = 'out_of_stock';
	var exists_here;

	if (starting_popup_data[product_id][config_type][config_id][3] == 0) {
		return 'in_stock';
	}

	if (starting_popup_data[product_id][config_type][config_id][4] == 'kit') {
		for (i in config_skus) {
			if (config_skus[i] == 0) {
				return 'kit_out_of_stock';
			}
		}
		return 'in_stock';
	}
	else {
		for (i in config_skus) {
			if (config_skus[i] == 1) {
				available = 'in_stock';
			}
		}
	}

	// We need to remove skus for this config that are not applicable to currently selected options
	var config_groups = new Array();
	for (i = 0; i < current_popup_menu_data.length; i++) {
		if (current_popup_menu_data[i][1] == 'none' || current_popup_menu_data[i][1] == '' || current_popup_menu_data[i][0] == config_type) {
			continue;
		}
		current_type = current_popup_menu_data[i][0];
		selected_config = current_popup_menu_data[i][1];
		for (s_config in product_config_array[product_id][current_type]) {	
			for (j in product_config_array[product_id][current_type][s_config]) {
				if ((j in config_groups) != true) {
					config_groups.push(j);
				}		
			}
		}
	}
		
	
	for (i = 0; i < current_popup_menu_data.length; i++) {
		if (current_popup_menu_data[i][1] == 'none' || current_popup_menu_data[i][1] == '' || current_popup_menu_data[i][0] == config_type) {
			continue;
		}
		current_type = current_popup_menu_data[i][0];
		selected_config = current_popup_menu_data[i][1];

		if(product_config_array[product_id][current_type][selected_config] === undefined) {
			return 'in_stock';
		}

		for (j in config_skus) {		
			if (product_config_array[product_id][current_type][selected_config][j] == 0) {
			//	continue;
				config_skus[j] = 0;
				skip_loop = false;
			} else if (product_config_array[product_id][current_type][selected_config][j] == 1) {
				skip_loop = false;						
			}
		}
	}
	
	if (skip_loop == true) {
		for (j in config_skus) {
			if (in_array(j, config_groups)) {
				available = 'unavailable';
			}
		}
	}

	if (skip_loop == true) {
			return available;
	}

	for (i=0;i<current_popup_menu_data.length;i++) {
		if (i == 'indexOf' || current_popup_menu_data[i][1] == 'none' || current_popup_menu_data[i][1] == '') {
			continue;
		}
		current_type = current_popup_menu_data[i][0];
		selected_config = current_popup_menu_data[i][1];
		
		if (current_type == config_type) {
			continue;
		}

		different_sku = true;
		for (j in product_config_array[product_id][current_type][selected_config]) {
			for (k in config_skus) {
				if (k == j) {
					different_sku = false;
				}
			}
		}
		if (different_sku == true) {
			continue;
		}
		
		if (starting_popup_data[product_id][current_type][selected_config][4] == 'kit') {
			for (j in config_skus) {
				if (config_skus[j] == 0) {
					return 'out_of_stock';
				}
			}
			return 'in_stock';
		}

		exists_here = 'unavailable';
		for (j in product_config_array[product_id][current_type][selected_config]) {
			for (k in config_skus) {
				if (k == j) {
					if (config_skus[k] == 1) {
						exists_here = 'in_stock';
						break;
					}
					else {
						exists_here = 'out_of_stock';
					}
				}
			}
			available = exists_here;
			if (available == 'in_stock') {
				break;
			}
		}
		
		if (available == 'unavailable' || available == 'out_of_stock') {
			break;
		}
	}
	return available;
}

function update_selectors(product_id, selected_config_type, suffix)
{
	if (!suffix) suffix = '';
	var config_type;
	var sandu_id;
	var out_of_stock_option = document.getElementById(product_id + '_out_of_stock_option').value;
	var out_of_stock_message = document.getElementById(product_id + '_out_of_stock_message').value;
	var current_popup_menu_data = eval('get_popup_menu_data_'+product_id+suffix+'()');
	var render_type;
	var selected;
	var cleared = false;
	var tagname = '';

	for (config_type in starting_popup_data[product_id]) {
		empty_menus(config_type, product_id);
		if (document.getElementById('configuration_selector_' + product_id + '_' + config_type + suffix).type == 'hidden') {
			render_type = 'anchor';
		}
		else {
			render_type = 'select';
		}
		for (sandu_id in starting_popup_data[product_id][config_type]) {
			tagname = starting_popup_data[product_id][config_type][sandu_id][5];
			if (document.getElementById('configuration_selector_' + product_id + '_' + config_type + suffix).value == sandu_id) {
				selected = true;
			}
			else {
				selected = false;
			}
			available = check_availability(sandu_id, config_type, current_popup_menu_data, product_id);
			if (available == 'in_stock' || starting_popup_data[product_id][config_type][sandu_id][1] == '' || starting_popup_data[product_id][config_type][sandu_id][1] == 'none') {
				// this is an option we need to draw!
				if (render_type == 'anchor') {
					if (starting_popup_data[product_id][config_type][sandu_id][1] != '' && starting_popup_data[product_id][config_type][sandu_id][1] != 'none') {
						var element = document.getElementById(tagname+'_'+sandu_id);
						element.style.display = 'inline';
						element.className = element.className.replace(/ config_out_of_stock/g, '');
						element.onmouseover = '';
						element.onmouseout = '';
						if (selected) {
							element.className += ' selected_config';
						}
						else {
							element.className = element.className.replace(/ selected_config/g, '');
						}
					}
				}
				else {
					add_option_to_menu(product_id, current_popup_menu_data, starting_popup_data[product_id][config_type][sandu_id], 'in_stock', null, null);
				}
			}
			else if (available == 'out_of_stock') {
				// check in stock against the setting for show and purchase
				// draw appropriately
				if (render_type == 'anchor') {
					if (starting_popup_data[product_id][config_type][sandu_id][1] != '' && starting_popup_data[product_id][config_type][sandu_id][1] != 'none') {
                        var tagname = starting_popup_data[product_id][config_type][sandu_id][5];
						var element = document.getElementById(tagname+'_'+sandu_id);
						if (out_of_stock_option == 'allow_purchase') {
							element.style.display = 'inline';
							element.className = element.className.replace(/ config_out_of_stock/g, '');
							element.onmouseover = '';
							element.onmouseout = '';
							if (selected) {
								element.className += ' selected_config';
							}
							else {
								element.className = element.className.replace(/ selected_config/g, '');
							}
						}
						else if (out_of_stock_option == 'do_not_allow_purchase') {
							element.style.display = 'inline';
							if (document.getElementById('configuration_selector_' + product_id + '_' + config_type + suffix).value == sandu_id) {
								clear_swatch_selection('configuration_selector_' + product_id + '_' + config_type + suffix);
								cleared = true;
							}
							element.className += ' config_out_of_stock';
							element.onmouseover = function() { show_out_of_stock_message(product_id, this.id); };
							element.onmouseout = function() { hide_out_of_stock_message(product_id); };
							if (selected) {
								element.className += ' selected_config';
							}
							else {
								element.className = element.className.replace(/ selected_config/g, '');
							}
						}
					}
				}
				else {
					if (out_of_stock_option == 'allow_purchase') {
						add_option_to_menu(product_id, current_popup_menu_data, starting_popup_data[product_id][config_type][sandu_id], 'out_of_stock', true, null);
					}
					else if (out_of_stock_option == 'do_not_allow_purchase') {
						add_option_to_menu(product_id, current_popup_menu_data, starting_popup_data[product_id][config_type][sandu_id], 'out_of_stock', false, out_of_stock_message);
					}
				}
			}
			else if (available == 'kit_out_of_stock') {
				if (render_type == 'anchor') {
					if (starting_popup_data[product_id][config_type][sandu_id][1] != '' && starting_popup_data[product_id][config_type][sandu_id][1] != 'none') {
                        var tagname = starting_popup_data[product_id][config_type][sandu_id][5];
						var element = document.getElementById(tagname+'_'+sandu_id);
						if (out_of_stock_option == 'allow_purchase') {
							element.style.display = 'inline';
							element.className = element.className.replace(/ config_out_of_stock/g, '');
							element.onmouseover = '';
							element.onmouseout = '';
							if (selected) {
								element.className += ' selected_config';
							}
							else {
								element.className = element.className.replace(/ selected_config/g, '');
							}
						}
						else if (out_of_stock_option == 'do_not_allow_purchase') {
							element.style.display = 'inline';
							if (selected_config_type != config_type && document.getElementById('configuration_selector_' + product_id + '_' + config_type + suffix).value == sandu_id) {
								clear_swatch_selection('configuration_selector_' + product_id + '_' + config_type + suffix);
								cleared = true;
							}
							element.className += ' config_out_of_stock';
							element.onmouseover = function() { show_out_of_stock_message(product_id, this.id); };
							element.onmouseout = function() { hide_out_of_stock_message(product_id); };
							element.onclick = '';
							if (selected) {
								element.className += ' selected_config';
							}
							else {
								element.className = element.className.replace(/ selected_config/g, '');
							}
						}
					}
				}
				else {
					if (out_of_stock_option == 'allow_purchase') {
						add_option_to_menu(product_id, current_popup_menu_data, starting_popup_data[product_id][config_type][sandu_id], 'out_of_stock', true, null);
					}
					else if (out_of_stock_option == 'do_not_allow_purchase') {
						add_option_to_menu(product_id, current_popup_menu_data, starting_popup_data[product_id][config_type][sandu_id], 'out_of_stock', false, out_of_stock_message);
					}
				}
						
			}
			else if (out_of_stock_option != 'do_not_display') {
				// this option does not exist!
				// draw it but do not let user select
				if (render_type == 'anchor') {
					if (starting_popup_data[product_id][config_type][sandu_id][1] != '' && starting_popup_data[product_id][config_type][sandu_id][1] != 'none') {
                        var tagname = starting_popup_data[product_id][config_type][sandu_id][5];
						var element = document.getElementById(tagname+'_'+sandu_id);
						element.style.display = 'inline';
						element.className += ' config_out_of_stock';
						element.className = element.className.replace(/ selected_config/g, '');
						element.onmouseover = function() { show_unavailable_message(product_id, this.id); };
						element.onmouseout = function() { hide_unavailable_message(product_id); };
						if (selected_config_type != config_type && document.getElementById('configuration_selector_' + product_id + '_' + config_type + suffix).value == sandu_id) {
							clear_swatch_selection('configuration_selector_' + product_id + '_' + config_type + suffix);
							cleared = true;
						}
					}
				}
				else {
					add_option_to_menu(product_id, current_popup_menu_data, starting_popup_data[product_id][config_type][sandu_id], 'not_available', false, null);
				}
			}
		}
	}

	if (cleared) {
		current_popup_menu_data = eval('get_popup_menu_data_'+product_id+suffix+'()');
		for (config_type in starting_popup_data[product_id]) {
			if (document.getElementById('configuration_selector_' + product_id + '_' + config_type + suffix).type != 'hidden') {
				continue;
			}
			for (sandu_id in starting_popup_data[product_id][config_type]) {
				if (document.getElementById('configuration_selector_' + product_id + '_' + config_type + suffix).value == sandu_id) {
					selected = true;
				}
				else {
					selected = false;
				}
				available = check_availability(sandu_id, config_type, current_popup_menu_data, product_id);
				if (available == 'in_stock' || starting_popup_data[product_id][config_type][sandu_id][1] == '' || starting_popup_data[product_id][config_type][sandu_id][1] == 'none') {
					// this is an option we need to draw!
					if (starting_popup_data[product_id][config_type][sandu_id][1] != '' && starting_popup_data[product_id][config_type][sandu_id][1] != 'none') {
                        var tagname = starting_popup_data[product_id][config_type][sandu_id][5];
						var element = document.getElementById(tagname+'_'+sandu_id);
						element.style.display = 'inline';
						element.className = element.className.replace(/ config_out_of_stock/g, '');
						element.onmouseover = '';
						element.onmouseout = '';
					}
				}
				else if (available == 'out_of_stock') {
					// check in stock against the setting for show and purchase
					// draw appropriately
					if (starting_popup_data[product_id][config_type][sandu_id][1] != '' && starting_popup_data[product_id][config_type][sandu_id][1] != 'none') {
                        var tagname = starting_popup_data[product_id][config_type][sandu_id][5];
						var element = document.getElementById(tagname+'_'+sandu_id);
						if (out_of_stock_option == 'allow_purchase') {
							element.style.display = 'inline';
							element.className = element.className.replace(/ config_out_of_stock/g, '');
							element.onmouseover = '';
							element.onmouseout = '';
						}
						else if (out_of_stock_option == 'do_not_allow_purchase') {
							element.style.display = 'inline';
							element.className += ' config_out_of_stock';
							element.onmouseover = function() { show_out_of_stock_message(product_id, this.id); };
							element.onmouseout = function() { hide_out_of_stock_message(product_id); };
						}
						if (selected) {
							element.className += ' selected_config';
						}
						else {
							element.className = element.className.replace(/ selected_config/g, '');
						}
					}
				}
				else if (available == 'kit_out_of_stock') {
					if (render_type == 'anchor') {
						if (starting_popup_data[product_id][config_type][sandu_id][1] != '' && starting_popup_data[product_id][config_type][sandu_id][1] != 'none') {

							var tagname = starting_popup_data[product_id][config_type][sandu_id][5];
							var element = document.getElementById(tagname+'_'+sandu_id);
							if (out_of_stock_option == 'allow_purchase') {
								element.style.display = 'inline';
								element.className = element.className.replace(/ config_out_of_stock/g, '');
								element.onmouseover = '';
								element.onmouseout = '';
								if (selected) {
									element.className += ' selected_config';
								}
								else {
									element.className = element.className.replace(/ selected_config/g, '');
								}
							}
							else if (out_of_stock_option == 'do_not_allow_purchase') {
								element.style.display = 'inline';
								if (selected_config_type != config_type && document.getElementById('configuration_selector_' + product_id + '_' + config_type + suffix).value == sandu_id) {
									clear_swatch_selection('configuration_selector_' + product_id + '_' + config_type + suffix);
									cleared = true;
								}
								element.className += ' config_out_of_stock';
								element.onmouseover = function() { show_out_of_stock_message(product_id, this.id); };
								element.onmouseout = function() { hide_out_of_stock_message(product_id); };
								element.onclick = '';
								if (selected) {
									element.className += ' selected_config';
								}
								else {
									element.className = element.className.replace(/ selected_config/g, '');
								}
							}
						}
					}
					else {
						if (out_of_stock_option == 'allow_purchase') {
							add_option_to_menu(product_id, current_popup_menu_data, starting_popup_data[product_id][config_type][sandu_id], 'out_of_stock', true, null);
						}
						else if (out_of_stock_option == 'do_not_allow_purchase') {
							add_option_to_menu(product_id, current_popup_menu_data, starting_popup_data[product_id][config_type][sandu_id], 'out_of_stock', false, out_of_stock_message);
						}
					}
				}
				else if (out_of_stock_option != 'do_not_display') {
					// this option does not exist!
					// draw it but do not let user select
					if (starting_popup_data[product_id][config_type][sandu_id][1] != '' && starting_popup_data[product_id][config_type][sandu_id][1] != 'none') {

						var tagname = starting_popup_data[product_id][config_type][sandu_id][5];
						var element = document.getElementById(tagname+'_'+sandu_id);
						element.style.display = 'inline';
						element.className += ' config_out_of_stock';
						element.className = element.className.replace(/ selected_config/g, '');
						element.onmouseover = function() { show_unavailable_message(product_id, this.id); };
						element.onmouseout = function() { hide_unavailable_message(product_id); };
					}
					if (selected) {
						element.className += ' selected_config';
					}
					else {
						element.className = element.className.replace(/ selected_config/g, '');
					}
				}
				if (sandu_id != '' && sandu_id != 'none' && sandu_id == document.getElementById('configuration_selector_' + product_id + '_' + config_type + suffix).value) {
					var tagname = starting_popup_data[product_id][config_type][sandu_id][5];
					var element = document.getElementById(tagname+'_'+sandu_id);
					element.className += ' selected_config';
				}
			}
		}
	}
	
	hide_unavailable_message(product_id);
	hide_out_of_stock_message(product_id);
	update_dynamic_price('configuration_selector_' + product_id + '_' + selected_config_type + suffix, selected_config_type, product_id, tagname, true, '');
}

var priceAsFloat = function (price) {
	return parseFloat(price.replace(/,/g, '').replace(/[^\d\.]/g, ''), 10);
}

var formatCurrency = function (price) {
	price = isNaN(price) || price === '' || price === null ? 0.00 : price;
	return '$' + parseFloat(price).toFixed(2);
}

var formatMoney = function(price) {
	var a = new Number(price);
	var b = a.toFixed(2); //get 12345678.90
	a = parseInt(a); // get 12345678
	b = (b-a).toPrecision(2); //get 0.90
	b = parseFloat(b).toFixed(2); //in case we get 0.0, we pad it out to 0.00
	a = a.toLocaleString();//put in commas - IE also puts in .00, so we'll get 12,345,678.00
	//if IE (our number ends in .00)
	if(a.lastIndexOf('.00') == (a.length - 3))
	{
		a=a.substr(0, a.length-3); //delete the .00
	}
	return '$' + a+b.substr(1);//remove the 0 from b, then return a + b = 12,345,678.90
}

// PS-270
function update_quantity_based_promos(qb_promo, option, config_type, product_id, tagname, legacy_mode, option_id) {
	var upgrade_price = 0;
	if(legacy_mode) {
		// Get selected sandu_id
		var sandu_id = $('#' + option + ' option:selected').val(); // select
		if (sandu_id == undefined || sandu_id == '') { // try swatch or anchor
			var sandu_id = $('#' + option).val();
		}

		if (sandu_id == undefined) {
			var sandu_id = '';
		}

		if (sandu_id != '' && sandu_id != 'none') {
			upgrade_price = parseFloat(starting_popup_data[product_id][config_type][sandu_id][6]);
		}
	}else {
		if(option_id != undefined) {
			upgrade_price = parseFloat($('#' + option + '-' + option_id).val());
		}
		else {
			upgrade_price = 0.0;
		}
	}

	if (upgrade_price != 'undefined') {
		for (i=1;i<=qb_promo;i++)
		{
			var hidden_starting_price = document.getElementById('hidden_qb_price_id_'+i);
			if (hidden_starting_price != 'undefinded') {
				starting_price = hidden_starting_price.value;
				starting_price = starting_price.substring(starting_price.indexOf("$")+1);
			}
			display_price = upgrade_price + parseFloat(starting_price);
			document.getElementById('qb_price_id_'+i).innerHTML = formatCurrency(display_price);
		}
	}
}

// PS-78
var last_upgrade_prices = new Object();
function update_dynamic_price(option, config_type, product_id, tagname, legacy_mode, option_id)
{
	var hidden_qb_promo = document.getElementById('hidden_qb_promo_count');
	var qb_promo = 0;
	if (hidden_qb_promo != null) {
		qb_promo = hidden_qb_promo.value;
	}
	if (qb_promo > 0) {
		update_quantity_based_promos(qb_promo, option, config_type, product_id, tagname, legacy_mode, option_id);
	}
	//var real_product_id = product_id.replace(/[^\d]/g, ''); // Get real product ID
	var product_id_parts = product_id.split('_');
	var real_product_id = product_id_parts[product_id_parts.length - 1];
	var dynamic_price = $('#product_dynamic_price_' + tagname + '_' + real_product_id); // This span ID must be present
	
	if (dynamic_price.length > 0) {
		var current_price_span = dynamic_price.html();
		price_formatted = false;
		if (current_price_span.match(/,/)) {
			price_formatted = true;
		}
		var current_price = priceAsFloat(current_price_span);
		var upgrade_price = 0;

		if(legacy_mode) {
			// Get selected sandu_id
			var sandu_id = $('#' + option + ' option:selected').val(); // select
			if (sandu_id == undefined || sandu_id == '') { // try swatch or anchor
				var sandu_id = $('#' + option).val();
			}

			if (sandu_id == undefined) {
				var sandu_id = '';
			}

			if (sandu_id != '' && sandu_id != 'none') {
				upgrade_price = parseFloat(starting_popup_data[product_id][config_type][sandu_id][6]);
			}
		}
		else {
			if(option_id != undefined) {
				upgrade_price = parseFloat($('#' + option + '-' + option_id).val());
			}
			else {
				upgrade_price = 0.0;
			}
		}

		if (last_upgrade_prices[option]) {
			current_price -= last_upgrade_prices[option];
		}
		current_price += upgrade_price;
		
		// update list price also, if necessary
		var current_list_price = '';
		var discount_percent = 0;
		if ($('#' + real_product_id + '_discount_percent')) {
			discount_percent = parseFloat($('#' + real_product_id + '_discount_percent').val());
		}
		if (discount_percent > 0 && discount_percent < 1) {
			var dynamic_list_price = $('#product_dynamic_list_price_' + tagname + '_' + real_product_id);
			if (dynamic_list_price.length > 0) {
				var current_list_price_span = dynamic_list_price.html();
				list_price_formatted = false;
				if (current_list_price_span.match(/,/)) {
					list_price_formatted = true;
				}
				current_list_price = priceAsFloat(current_list_price_span);
			}
			if (current_list_price != '') {
				if (last_upgrade_prices[option]) {
					current_list_price -= Math.round((last_upgrade_prices[option] / discount_percent) * 100) / 100;
				}
				current_list_price += Math.round((upgrade_price / discount_percent) * 100) / 100;
				if (list_price_formatted) {
					dynamic_list_price.html(formatMoney(current_list_price));
				} else {
					dynamic_list_price.html(formatCurrency(current_list_price))
				}
				
				var current_savings_amount = '';
				if ($('#product_dynamic_savings' + tagname + '_' + real_product_id)) {
					dynamic_savings_amount = $('#product_dynamic_savings_' + tagname + '_' + real_product_id);
					if (dynamic_savings_amount.length > 0) {
						current_savings_amount_span = dynamic_savings_amount.html();
						var savings_amount_formatted = false;
						if (current_savings_amount_span.match(/,/)) {
							savings_amount_formatted = true;
						}
						current_savings_amount = priceAsFloat(current_savings_amount_span);
					}
				}
				if (current_savings_amount != '') {
					current_savings_amount = current_list_price - current_price;
					if (savings_amount_formatted) {
						dynamic_savings_amount.html(formatMoney(current_savings_amount));
					} else {
						dynamic_savings_amount.html(formatCurrency(current_savings_amount))
					}
				}
					
				var current_discount_percent = '';
				if ($('#product_dynamic_savings' + tagname + '_' + real_product_id)) {
					dynamic_discount_percent = $('#product_dynamic_discount_percent_' + tagname + '_' + real_product_id);
					if (dynamic_discount_percent.length > 0) {
						current_discount_percent_span = dynamic_discount_percent.html();
						current_discount_percent = priceAsFloat(current_discount_percent_span);
					}
				}
				if (current_discount_percent != '') {
					current_discount_percent = Math.round(Math.floor(100 - ((current_price / current_list_price) * 100)));
					dynamic_discount_percent.html(current_discount_percent);
				}
			}
		}

		last_upgrade_prices[option] = upgrade_price;
		
		if (current_price >= 0) {
			if (price_formatted) {
				dynamic_price.html(formatMoney(current_price));
			} else {
				dynamic_price.html(formatCurrency(current_price));
			}
		}
	}
	
}

function update_selection(input_id, config_value, config_label, plugin_product_id, product_id, force_reset_link, large_image) {
	document.getElementById(input_id).value = config_value;
	document.getElementById(input_id + '_current_value').innerHTML = config_label;
	if (document.getElementById(plugin_product_id + '_out_of_stock_option').value == 'do_not_display' || force_reset_link == 'true') {
		document.getElementById(input_id + '_clear_values').style.display = 'inline';
	}
	var image_set = document.getElementById(product_id + '_current_image_set_id');
	if (document.getElementById(product_id + '_' + config_value + '_mz_image_set')) {
		if (document.getElementById(image_set.value)) {
			document.getElementById(image_set.value).style.display = 'none';
		}
		if (document.getElementById(product_id + '_mz_main_image_set')) {
			document.getElementById(product_id + '_mz_main_image_set').style.display = 'none';
		}
		document.getElementById(product_id + '_' + config_value + '_mz_image_set').style.display = 'block';
		image_set.value = product_id + '_' + config_value + '_mz_image_set';
	}
	if(large_image){
		document.getElementById('product_photo_zoom_url2').href = large_image;
	}
}

function clear_swatch_selection(input_id) {
	document.getElementById(input_id).value = '';
	document.getElementById(input_id + '_current_value').innerHTML = 'please choose';
	document.getElementById(input_id + '_clear_values').style.display = 'none';
}

function update_class(input_id) {
	if (document.getElementById(input_id).className.indexOf('selected_config') == -1) {
		document.getElementById(input_id).className += ' selected_config';
	}
}

function show_out_of_stock_message(product_id, selected_sandu_id) {
	for (config_type in starting_popup_data[product_id]) {
		for (sandu_id in starting_popup_data[product_id][config_type]) {
			if( sandu_id == selected_sandu_id && document.getElementById(product_id + '_' + config_type + '_out_of_stock_display_message') ) {
				document.getElementById(product_id + '_' + config_type + '_out_of_stock_display_message').style.display = 'inline';
				return;
			}
		}
	}
}

function hide_out_of_stock_message(product_id) {
	for (config_type in starting_popup_data[product_id]) {
		if( document.getElementById(product_id + '_' + config_type + '_out_of_stock_display_message') ) {
			document.getElementById(product_id + '_' + config_type + '_out_of_stock_display_message').style.display = 'none';
		}
	}
}

function show_unavailable_message(product_id, selected_sandu_id) {
	for (config_type in starting_popup_data[product_id]) {
		for (sandu_id in starting_popup_data[product_id][config_type]) {
			if( sandu_id == selected_sandu_id && document.getElementById(product_id + '_' + config_type + '_not_available_message') ) {
				document.getElementById(product_id + '_' + config_type + '_not_available_message').style.display = 'inline';
				return;
			}
		}
	}
}

function hide_unavailable_message(product_id) {
	for (config_type in starting_popup_data[product_id]) {
		if( document.getElementById(product_id + '_' + config_type + '_not_available_message') ) {
			document.getElementById(product_id + '_' + config_type + '_not_available_message').style.display = 'none';
		}
	}
}

function addtocartbg(model_id, callback_function, suffix, tag_name){
	if (!check_configuration_selection(model_id, suffix, tag_name)) {
		return false;
	}
	var sUrl = "ajax_targets/add_to_cart.php";
	var configurations = new Array();
	var outbuff = "";
	$("form#add_to_cart_product_" + tag_name + "_" + model_id + " select, form#add_to_cart_product_" + tag_name + "_" + model_id + " input").each(function() {
		pattern = new RegExp("configurations\\[(.*)\\]", "gi");
		matches = pattern.exec(this.name);
		if (matches != null) {
			config_label = matches[1];
			if (config_label.length > 0) {
				if (this.value != "" && this.value!='none') {
					config_label = config_label.replace(/_/, " ");
					if (config_label!=""){
						outbuff+="configurations["+config_label+"]="+this.value+"&";
					}
				}
			}
		}
	});

	var args = outbuff+"product_id="+model_id;
	args = args+"&quantity="+$('[name=quantity]').val();


	var callback_addcart = {
		success: function(o) {
			var restxt = o.responseText;
			var prod = eval('('+restxt+')');
			
			if (prod.retvalue==1){
				alert("There is no more of this product in stock!");
			}
			else if (prod.retvalue==2){
				alert("Invalid product configuration!");
			}
			else{
				if (prod.html!=''){
					if (document.getElementById('hidden_minicartholder') && document.getElementById('hidden_minicartholder').value!=''){
						eval("document.getElementById('"+document.getElementById('hidden_minicartholder').value+"').innerHTML=prod.html;");
					}
					else{
						document.getElementById('minicartblock').innerHTML=prod.html;
					}
					if (callback_function != 0) { 
						callback_function();
					}
				}
			}
		},
		failure: function(o){
			alert("Action failed. Please Try again.");
		}
	}
	var transaction = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback_addcart, args);	
	return false;
}

function addtocartbg_related(model_id)
{ 
	eval("var elhandle=$('#relpro"+model_id+"');");
	var buttontxt=elhandle.text();
	buttontxt=buttontxt.toLowerCase();
	if (buttontxt == 'add to bag'){
		addtocartbg(model_id, 0);
		elhandle.text("Item in Bag");
	}
	else{
		document.location='index/page/shopping_cart';
	}
	return false;
}

function update_price_block()
{
	var text_to_show = $('#item_base_price').val();
	if ($('#payment_plans').val())
	{
		text_to_show = $('#payment_plan_label'+$('#payment_plans').val()).val();
	}
	var re = new RegExp(/^[0-9\.\$]*$/);
	var m = re.exec(text_to_show);
	if ( m == null && ($("input[name=quantity]").val() > $('#limit_per_order'+$('#payment_plans').val()).val()))
	{
		alert($('#message').val());
		$("#payment_plans").val('0');
		return false;
	}
	$('#price_block').html(text_to_show);
}

$("input[name=quantity]").change(function(event) {
	var buf = parseInt($("input[name=quantity]").val() + String.fromCharCode(event.keyCode));
	var text_to_show = $('#item_base_price').val();
	if ($('#payment_plans').val())
	{
		text_to_show = $('#payment_plan_label'+$('#payment_plans').val()).val();
	}
	var re = new RegExp(/^[0-9\.\$]*$/);
	var m = re.exec(text_to_show);
	if ( m == null && (buf > $('#limit_per_order'+$('#payment_plans').val()).val()))
	{
		alert($('#message').val());
		$("input[name=quantity]").val($("input[name=quantity]").attr('defaultValue'));
		return false;
	}
	$('#price_block').html(text_to_show);
});
 
function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

