(function($){

$(document).ready(function(){
	var original_img_src = undefined;
	var main_img = $(".main-image-wrapper img");
	$("#productAttributesImages .attribImg img, #productAdditionalImages img").mouseenter(function(){
		var _color = $(this).next(".color-name").text();
		//console.info("+ "+this.src+" "+_color);
		if (_color) {
			$("#main-image-color").text(_color);
			var _lg = this.src.replace(/-sm/, "-lg");
			if (_lg) main_img.parents("a[rel=lightbox-g]").eq(0).attr('title', _color).attr('href', _lg);
			var _color_select = $(".wrapperAttribsOptions select");
			_color_select.val(_color_select.find("option").filter(function(){ return ( new RegExp(_color, "i").test($(this).text()) ) }).val());
			//jQuery(".wrapperAttribsOptions select option").filter(function(){ return /Painted DESERT/i.test(jQuery(this).text()) })
		}
		else if (original_img_src == undefined)//not yarn page, restore image on exit
			original_img_src = main_img.attr('src');
		var _src = this.src;
		if (/bmz.cach/.test(_src))
			_src = $(this).parent("a").attr("href");
		var _md = _src.replace(/-sm/, "-md");
		if (_md) main_img.attr('src', _md);
	});
	// change yarn select list
	$(".wrapperAttribsOptions select").change(function(){
		var _color = $(this).find(":selected").text().replace(/ *\(.*$/, "");
		// escape meta-chars for jquery selector
		// as of Oct 3 2010, Sizzle (jquery selector lib) can't handle
		//  escaped apostrophes & unescaped spaces in same selector
		// BAD: [title=Georgia O\\'Keeffe]
		//  OK: [title=Georgia\\ O\\'Keeffe]
		//      [title='Georgia O\\'Keeffe']
		//  either escape spaces or single quote relevant portion
		//var _metachar_rx = new RegExp("[][#;&,.+*~':\"!^$()=>|/@]", "g");
		_color = _color.replace(/[#;&,.+*~':"!^$()[\]=>|\/@]/g, "\\$&");
		//if (typeof console != 'undefined') console.info( "Changed "+_color );
		//$("#productAttributesImages a[title='"+_color+"'] .attribImg img").mouseenter();
		var _selector = "#productAttributesImages a[title='"+_color+"'] .attribImg img";
		$(_selector).mouseenter();
	});
	// default's arbitrary and need to populate yarn color name
	$("#productAttributesImages .attribImg img").eq(0).mouseenter();
	$("#productAdditionalImages").mouseleave(function(){
		if (original_img_src != undefined) {
			main_img.attr('src', original_img_src);
			original_img_src = undefined;
		}
	});
	//$("body").css('background-color', "orange");
});

})(jQuery);

