// FUNCTIONS

function trim(s) {
  return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
	re = /^.+@.+\..{2,6}$/;
	return re.test(email);
}

function getBaseImgSrcById( element_id )
{
	var imgObj = document.getElementById( element_id );	
	var imgSrcPath = imgObj.src;
	//remove parent path info;
	var pathDelim = "/";
	var delimPos = imgSrcPath.lastIndexOf( pathDelim );
	var imageFilename;
	if( delimPos > 0 )
		imageFileName = imgSrcPath.substr( delimPos+1, imgSrcPath.length-delimPos+1 );
	else
		imageFileName = imgSrcPath;

	return imageFileName;
}

// SCRIPTS

// defeat the background image flicker for image-replaced links in IE 6
if ( $.browser.msie && parseInt($.browser.version) <= 6 ) {
	try {
	 document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}
}

// extra divs for  background images
$(function(){
	$("body").wrapInner('<div id="background-1"><div id="background-2"></div></div>');
});

// new windows
$(function(){
	$("a[rel='external']").click(function() {
		window.open($(this).attr('href'));
		return false;
	});
});

// ToggleVal (plugin)
$(function(){
	$("input#search-1, input#retail-1").toggleVal({
		populateFrom: "label",
		removeLabels: true
	});
});

// accordion
$(function(){
	// initialize accordion
	$(".accordion > *")
		.filter(":even").addClass("accordion-topic").wrapInner("<span class=\"inner\"></span>").end()
		.filter(":odd").addClass("accordion-panel").hide();
	// click functionality
	$(".accordion > :even").click(function(){
		if (!$(this).hasClass("on")) {
			$(".accordion > :even.on").removeClass("on");
			$(this).addClass("on");
			$(".accordion > :odd:visible").slideUp("fast");
			$(this).next().slideDown("fast");
		}
	}).filter(":first").click();
	// mouseover highlighting
	$(".accordion > :even").hover(function(){
		$(this).not(".on").addClass("hover");
	}, function(){
		$(this).removeClass("hover");
	});	
});

// footer
// function setFooter() {
	// // get height of div#header (had to work around the fact that div#header has 'min-height')
	// var offset = $("ul#tnav li:last").offset()
	// var header_height = offset.top + $("ul#tnav li:last").height();
	// var header_actual_height = $("#header").height();
	// // get height of div#body
	// var body_height = $("#body").height();
	// // set the height at which footer stops sticking to bottom of window
	// if (body_height > header_height) {
		// var break_height = body_height;
	// }
	// else {
		// var break_height = header_actual_height;
	// }
	// // stop the footer at the point window height is less than div height
	// if (break_height > $(window).height()) {
		// $("#footer").css({ bottom: "auto", top: break_height + "px"});
	// }
	// else {
		// $("#footer").css({ bottom: 0, top: "auto" });
	// }
	// console.log(header_height);
// }
// $(function(){
	// setFooter();
	// $(window).resize(function(){
		// setFooter();
	// });
// });

// faq page
$(function(){
	$(".s-3.p-1 dl > *").css("margin-left", "22px");
	// add numbers to each question
	$(".s-3.p-1 dt").css("position", "relative").each(function(i){
		i++;
		var numeral = "<span style=\"";
		if (i < 10) {
			numeral += "padding:0 0 0 .6em; ";
		}
		numeral += "position:absolute; left:-22px; color:#666;\">" + i + "</span>";
		$(this).prepend(numeral);
	});
});

// detail page 'add to cart' functionality
$(function(){
	var img_dir = "/images/";
	var lg_img_dir = "/images/large/";
	// hide 'color select' drop-down
	$("select#addcart-1").css("display", "none");
	// insert enlarge icon
	var product_href = $("a#product_shot").attr("href");
	$(".detail .box").prepend("<a href=\"" + product_href + "\" class=\"enlarge\" rel=\"enlarge\">Enlarge</a>");
	// enlarge functionality
	$("a[rel='enlarge']").click(function (e) {
		e.preventDefault();
		$("<img src=\"" +  $(this).attr("href") + "\" />").modal();
	});
	// insert color selection container
	$("<span class=\"color_selection\"></span>").appendTo("label[for='addcart-1']");
	// insert color swatch container
	$("<div class=\"color\"></div>").insertAfter("select#addcart-1");
	// insert color swatches and preload product images
	$("select#addcart-1 option").each(function(){
		var color = $(this).attr("class");
		var color_desc = $(this).text();
		var prod_id = $(this).val();
		$("<span id=\"" + prod_id + "\" class=\"" + color + "\" title=\"" + color_desc + "\"></span>").appendTo("div.color");
		var preload_image = new Image(); 
		preload_image.src = img_dir + prod_id + ".png";
	});
	// color swatch click functionality
	$("div.color span:not(.selected)").click(function(){
		var color_desc = $(this).attr("title");
		// mark as 'selected'
		$(this).addClass("selected").siblings(".selected").removeClass("selected");		
		// update 'color selection' text
		$("span.color_selection").empty().append(" " + color_desc);
		// update image
		var prod_id = $(this).attr("id");
		var img_src = img_dir + prod_id + ".png";
		$("#product_shot img").attr("src",img_src);
		// update enlarge links
		var enlarge_src = lg_img_dir + getBaseImgSrcById( "imgProduct" );
		$(".detail a#product_shot, .detail a.enlarge").attr("href", enlarge_src);
		// reflect selection in the 'color select' drop-down (so the value will  get passed to the cart)
		$("select#addcart-1").val(color_desc);
	}).filter(":first").click();
	
	// color dropdown change functionality
	$("div.color select").change(function(){
		var color_desc = $("div.color select option:selected").attr("title");
		// mark as 'selected'
		$("div.color select option:selected").addClass("selected").siblings(".selected").removeClass("selected");		
		// update 'color selection' text
		$("span.color_selection").empty().append(" " + color_desc);
		// update image
		var prod_id = $("div.color select option:selected").attr("id");
		var img_src = img_dir + prod_id + ".png";
		$("#product_shot img").attr("src",img_src);
		// update enlarge links
		var enlarge_src = lg_img_dir + getBaseImgSrcById( "imgProduct" );
		$(".detail a#product_shot, .detail a.enlarge").attr("href", enlarge_src);
		// reflect selection in the 'color select' drop-down (so the value will  get passed to the cart)
		$("select#addcart-1").val(color_desc);
	}).filter(":first").change();
});

// contact  page form validation
$(function(){
	// submit button click
	$('#contact :button[type="submit"]').click(function () {
		var current_container = $(this).parent();
		var current_fields = current_container.find(':input');
		var error = '';
		// remove any previous error indicators
		$('ul.error').remove();
		current_container.find('.error').removeClass('error');
		// validate form
		current_fields.each(function(){
			var value = trim($(this).val());
			var label_element = $(this).prevAll('label');
			// if there is a 'title' attribute, use that for the error label instead of the 'label'
			if ($(this).is('*[title]')) {
				var label = $(this).attr('title');
			}
			else {
				var label = label_element.text().replace(/\*/,'');
			}
			// required fields
			if ($(this).hasClass('required') && value == '') {
				error += '<li>'+label+' is a required field</li>';
				label_element.addClass('error');
			}
			// email
			if ($(this).is('.email') && value != '') {
				if (!validateEmail(value)) {
					error += '<li>'+label+' is not a valid format</li>';
					label_element.addClass('error');
				}
			}
		});
		// display error message or advance to next form section
		if (error != '') {
			$('<ul class="error">'+error+'</ul>').hide().prependTo(current_container).fadeIn();
			return false
		}
	});
}); // end contact us form


// drop shadows
$(function(){
	$(".box").each(function() {
		margin_t = $(this).css("marginTop");
		margin_r = $(this).css("marginRight");
		margin_b = $(this).css("marginBottom");
		margin_l = $(this).css("marginLeft");
		margin = margin_t + " " + margin_r + " " + margin_b + " " + margin_l;
		// width = parseInt($(this).css("width"));
		// width -= 4;
		// width += "px";
		$(this)
			.wrap("<div class=\"shadow\" style=\"margin: " + margin + "\"></div>")
			.css("margin", "0");
	});
});
