// Applies starting text to text boxes
function textbox_pretext(jquery_css_selector, start_value) {
	$(document).ready(function () {
		$(jquery_css_selector).attr("value", start_value);
		$(jquery_css_selector).click(function () {
			if ($(this).val() == start_value) {
				$(this).attr("value","");
			}
		});
		$(jquery_css_selector).blur(function () {
			if ($(this).val() == "") {
				$(jquery_css_selector).attr("value", start_value);
			}
		});
		if ($('form.shopping_cart_form ' + jquery_css_selector).size()) {
			$('form.shopping_cart_form').submit(function() {
				if ($('form.shopping_cart_form ' + jquery_css_selector).attr("value") == start_value) {
					$('form.shopping_cart_form ' + jquery_css_selector).attr("value", "");
				}
			});
		}
	});
}

function form_error_messages_popup(section) {
	$(document).ready(function() {
		var messages = (section ? section + ' ' : '') + '#form_errors .error_message';
		var error_messages = '';
		if ($(messages).size()) {
			$(messages).each(function() {
				error_messages += $(this).text() + "\n";
			});
			if (error_messages) {
				alert(error_messages);
			}
		}
	});
}

// Extend String object so it can remove the selected category option text
String.prototype.remove_unselect_text = function() {
	var remove_unselect_text = new RegExp("\\[Remove\\]", "gi");
	return jQuery.trim(this.replace(remove_unselect_text, ''));
}

// Extend String object so it can render a DOM friendly string
String.prototype.dom_friendly_string = function() {
	var invalid_chars = new RegExp("[^a-z0-9]", "gi");
	var spacer = new RegExp("[_]+", "gi");
	return jQuery.trim(this.remove_unselect_text().replace(invalid_chars, '_')).toLowerCase().replace(spacer, '_');
}

// Extend String object to check whether a search option is selected
String.prototype.is_selected = function() {
	var is_selected = new RegExp("\\[Remove\\]", "gi");
	return is_selected.test(this); 
}

function in_array(the_value, the_array) {
	for (var i = 0; i < the_array.length; i++) {
		if (the_array[i] == the_value) {
			return true;
		}
	}
	return false;
}

// Adds an onclick function to the sidebar menu items, allowing them to expand when picking
// criteria and close any other open items when doing so. Also adds classes and ID's so 
// the color swatch picker works.
function setup_search_display() {
	var auto_show_search_category = ['color_family', 'color_family_picker', 'finish', 'finish_picker'];
	$("div.search_category h3").each(function() {
		var search_category_name = $(this).text().dom_friendly_string();
		if (search_category_name == "") {
			return;
		} 
		var search_anchors = $(this).next("div.search_terms div").children("div.search_anchor a");

		// Add appropriate classes and ID's to the search category
		if (!$(this).parent().attr('id')) {
			switch(search_category_name) {
				case 'color_family':
				case 'finish':
					// Use the picker logic if nothing is selected in super search
					if (!search_anchors.text().is_selected()) {
						search_category_name += '_picker';
						$(this).parent().attr('id', search_category_name);
					} else {
						$(this).parent().attr('id', search_category_name + '_category');
					}
					break;
				default:
					$(this).parent().attr('id', search_category_name + '_category');
					break;
			}
		}
		if (!$(this).attr('rel')) {
			$(this).attr('rel', search_category_name);
			$(this).addClass('search_category_' + search_category_name);
			$(this).html('<div style="float:left; width:165px; display:block; height:20px;" class="expander"></div>');
		}

		if (search_anchors.size() && search_anchors.text()) {
			// Check if a search category is selected or not
			if (in_array(search_category_name, auto_show_search_category) || search_anchors.text().is_selected()) {
				$(this).addClass("selected");
				search_category_expand($(this).children("div.expander"));
			}

			// Process search category options
			search_anchors.each(function() {
				$('div.search_anchor', this).each(function() {
					var search_anchor_name = jQuery.trim($(this).text());
					var search_anchor_dom_name = search_anchor_name.dom_friendly_string();
					var search_option = $(this).children('a');

					// Add appropriate ID's to search category options
					if (!$(this).attr('id')) {
						$(this).attr('id', search_category_name + '_' + search_anchor_dom_name);
					}

					// Special search category option processing
					switch(search_category_name) {
						// Search categories that should be modified
						case 'color':
						case 'color_family_picker':
						case 'finish_picker':
							if (search_anchors.text().is_selected()) {
								// Reconstruct the remove link
								$(this).html('<a href="' + search_option.attr('href') + '" onclick="' + search_option.attr('onclick') + '" rel="' + search_option.attr('rel') + '" rev="' + search_option.attr('rev') + '" title="Remove ' + search_anchor_name.remove_unselect_text() + '"></a>'); 
							} else {
								search_option.attr('title', search_anchor_name);
								search_option.text('');
							}
							break;

						// All other search categories
						default:
							// Do nothing
							break;
					}
				});
			});
		}
	});

	// Expand search category if selected
	$("div.search_category h3 div.expander").click(function() {
		search_category_expand($(this));
	});
}

// Expands search category
function search_category_expand(search_category) {
	if (search_category.parent().hasClass("search_header_active")) {
		search_category.parent().next().slideUp(300).removeClass("activeChildren");
		search_category.parent().removeClass("search_header_active");
		$("div.search_help").hide();
	}
	else {
		$("div.search_category h3").children("div.expander").each(function() {
			if ($(this).parent().hasClass("search_header_active") && !$(this).parent().hasClass("selected")) {
				$(this).parent().next("div.search_terms").slideUp(300).removeClass("activeChildren");
				$(this).parent().removeClass("search_header_active");
			}
		});
		search_category.parent().next("div.search_terms").slideToggle(300).addClass("activeChildren");
		search_category.parent().addClass("search_header_active");
		$("div.search_help").hide();
	}
}

function setup_search_popups() {
	$(document).ready(function() {

		// Search help popups
		$('div.search_category').each(function() {
			var search_section_obj = $(this).children('h3');
			var search_section = search_section_obj.attr('rel');
			var source_id = 'search_help_content_' + search_section;
			var show_id = 'search_help_popup_' + search_section;
			var search_help_content = $('#' + source_id).text();

			if (search_help_content) {
				var question_mark_html = '<div class=\'search_question\'><a href=\'#\' onclick=\'return raise_help_popup("' + show_id + '");\'><img alt=\'?\' src=\'static/images/question.png\'/></a></div>';
				search_section_obj.append(question_mark_html);

				var search_help_content_html = '<div id="' + show_id + '" class="search_help">' + search_help_content + '</div>';
				$(this).append(search_help_content_html);
			}
		});

	});
}

function setup_help_popups() {
	$(document).ready(function() {

		// Quick help popups
		$('.questionButton').each(function() {
			var show_id = $(this).attr('rel');
			if (show_id) {
				var source_id = show_id.replace('quick_help_', 'quick_help_content_');
				var quick_help_content = $('#' + source_id).text();

				if (quick_help_content) {
					var quick_help_html = '<div id="' + show_id + '" class="quick_help">' + quick_help_content + '</div>';
					$(this).after(quick_help_html);
					$(this).click(function() {
						return raise_help_popup(show_id);
					});
				}
			} else {
				return false;
			}
		}).blur(function() {
			$('.quick_help').hide();
		});

	});
}

function raise_help_popup(id) {
	$('#' + id).toggle();
	return false;
}

$(document).ready(function() {

	// Tiny piece of JS to detect presence and version of Internet Explorer

	var is_ie/*@cc_on = {
		// quirksmode : (document.compatMode=="BackCompat"),
		version : parseFloat(navigator.appVersion.match(/MSIE (.+?);/)[1])
	}@*/;


	// Adds an onhover function to each of the criteria in a given section, displaying an expanded
	// view of the criterion to one side.

	$("div.search_anchor").hover( function() {

			if ($(this).parent().next("div.search_popout").attr("id") != null) {

				var subcatname = $.trim($(this).children().html());
				subcatname = subcatname.toLowerCase().replace(/ /, "_");
				var catname = $(this).parent().next("div.search_popout").attr("id");
				catname = catname.substr(catname.indexOf("_") + 1);
				$("#popout_image_" + catname).attr("src", "static/images/" + catname + "/" + subcatname + ".png");
				$("#popout_" + catname).css("display", "block");
			}
		},
		function() {

			$(this).parent().next("div.search_popout").css("display", "none");
		}
	);

	// Vanishes the "product search" filler text when the search input is focused.

	$("input#freetext_search_box").focus( function() {

		if (this.value == "Product Search") { this.value = ""; }
	} );

	$("input#customerSearchInput").focus( function() {

		if (this.value == "Product Search") { this.value = ""; }
	} );

	// Automatically sizes and makes semitransparent the popup scrim when a criterion is added.

	$("#scrim").css("height", document.documentElement.scrollHeight);

	if (is_ie) {

		$("#scrim").css("filter", "alpha(opacity=80)");

		// Also makes semitransparent the background of the popup scrolling specials bar on the homepage.

		$("#shadeSpecialsBackground").css("filter", "filter: alpha(opacity = 50);");

		// ... and the breadcrumb background.

		$("#breadcrumbLine div.breadcrumbBackground").css("filter", "filter: alpha(opacity = 50);");
	}

});

