var imageCache = new Array();
var title_pre = ' :: ';
var title_none = 'none';

jQuery.fn.extend({
	setTitle: function(value) {
		$(this).parent().parent().prev('dt').children('span').text(title_pre+value);
	}
});

jQuery.extend({
	checkStock: function(attr1, attr2) {
		var inventory;
		var attrs = new Array();
		// Check for required attribute choices
		$('#product-attributes dd.required').each(function(){
			var attr = $(this).attr('class').split(' ')[0];
			var item = $('input[type!="radio"], input[type="radio"]:checked, select').filter('[name="prod_attr['+attr+']"]');
			var val = item.val() || ' ';
			var tmp = {};
			var c = item.attr('class').split('-');
			tmp.attr = c[1];
			tmp.option = c[2] || val;
			if (!val.match(/^\s+$/)) {
				attrs.push(tmp);
			}
		});
		
		// Check for stock
		if (pInventory) {
			// Get attributes with selected options
			$.each(pInventory, function(){
				if (typeof(this.attributes) == 'object') {
					var iCount = this.attributes.length;
					var matches = 0;
					$.each(this.attributes, function(){
						var inv = this;
						$.each(attrs, function(){
							if (this.attr == inv.attr && inv.option == this.option) {
								matches++;
							}
						});						
					});
				
					if (matches == iCount) {
						inventory = this;
						return false;
					}
				}
			});
		}
		
		return inventory;
	}
});

$(function(){

	$('#product-add').click(function(){
		var error = false;
		var attrs = new Array();
		// Check for required attribute choices
		$('#product-attributes dd.required').each(function(){
			var attr = $(this).attr('class').split(' ')[0];
			var item = $('input[type!="radio"], input[type="radio"]:checked, select').filter('[name="prod_attr['+attr+']"]');
			var val = item.val() || ' ';
			var tmp = {};
			if (val.match(/^\s+$/)) {
				$(this).prev('dt').addClass('error');
				error = true;
			}
			var c = item.attr('class').split('-');
			tmp.attr = c[1];
			tmp.option = c[2] || val;
			attrs.push(tmp);
		});
		
		if (error) {
			alert('Please make sure all attributes have been selected before adding this to your basket.');
		} else {
			if (typeof($.checkStock()) == 'object' && $.checkStock().inv_count <= 0) {
				alert('This item is out of stock. Please choose a different option.');
			} else {
				$(this).parents('form').submit();
			}
		}
		return false;
	});
	
	$('#product-photos li:first-child').addClass('first');

	if ($.browser.msie) {
		$(window).load(function(){
			$('#product-wrap, #additional-products').corner('top');
		});
	} else {
		$('#product-wrap, #additional-products').corner('top');
	}
	
	$('#size-link a').click(function(){
		newWin($(this).attr('href'), 470, 165);
		return false;
	});
	
	var mainImage = $('#product-image');
	var mainThumb = false;
	if ($('#product-photos li').size() > 0) {
		mainThumb = $($('#product-photos li').get(0)).addClass('selected');
	}
	
	$('#product-attributes li').hover(function(){
		var title_text = '';
		$(this).addClass('over');
		
		if ($(this).parent().parent().is('.color')) {
			thumbSwap(mainImage, $('img', this));
			$(this).setTitle($('img', this).attr('alt'));
		} else {
			$(this).setTitle($(this).text());
		}
		
	}, function(){
		$(this).removeClass('over');
		
		if ($(this).parent().parent().is('.color')) {
			thumbSwap(mainImage, $('#product-photos li.selected img'));
		} else {
			
		}
		
	}).click(function(){
		if ($(this).is('.selected')) return false;
		var value = $(this).text() || $('img', this).attr('alt');
		if ($(this).parent().parent().is('.color')) {
			thumbSwap($('img', mainThumb), $('img', this));
			thumbSwap('#focus-section img', $('img', this));
			console.log($(this).attr('class').split(' ')[0]);
			$('input.'+$(this).attr('class').split(' ')[0]).attr('checked', true);
		} else if ($(this).parent().parent().is('.size') || $(this).parent().parent().is('.amount')) {
			var options = $(this).attr('class').split(' ')[0].split('-');
			$('select.'+options[0]+'-'+options[1]).val(options[2]);
		}
		$(this).siblings('.selected').removeClass('selected');
		$(this).addClass('selected');
		$('#product-photos li.selected').removeClass('selected');
		$(this).parent().parent().prev('dt').removeClass('error');
		if (mainThumb) {
			$(mainThumb).addClass('selected');
		}
	}).mousedown(function(){
		this.onselectstart = function() { return false; };
		return false;
	});
	
	$('#product-photos li').mouseover(function(){
		$(this).siblings('.selected').removeClass('selected');
		$(this).addClass('selected');
		thumbSwap(mainImage, $('img', this));
		thumbSwap('#focus-section img', $('img', this));
	}).click(function(){
		return false;
	});
	
	if ($('#focus-section').size() > 0) {
		// Zoom
		var dragImg = $('#focus-section');
		var dragImgWidth = dragImg.outerWidth(), dragImgHeight = dragImg.outerHeight();
		var coords = $('#image-wrap').offset();
		var maxLeft = coords.left;
		var maxTop = coords.top;
		var maxRight = maxLeft + 263;
		var maxBottom = maxTop + 395;
		var prodH = 395, prodW = 263;
		var hRatio = 800 / (prodH - dragImgWidth);
		var vRatio = 1200 / (prodW - dragImgHeight);
	
		// Image zoom
		$(window).load(function(){
			$('#image-wrap').hover(function(){
				$('#shade').css('zIndex', '10').dequeue().animate({
					opacity: '.65'
				});
				$('#focus-section').css('visibility', 'visible');
		
				coords = $(this).offset();
				maxLeft = coords.left;
				maxTop = coords.top;
				maxRight = maxLeft + prodW;
				maxBottom = maxTop + prodH;
		
			}, function(){
				$('#shade').dequeue().animate({
					opacity: 0
				}, function(){ $(this).css('zIndex', '-10'); });
				$('#focus-section').css('visibility', 'hidden');
			}).mousemove(function(e){
				var cursorX = e.pageX, cursorY = e.pageY;
				var eLeft, eTop, iLeft, iTop;
		
				if ((cursorX - (dragImgWidth / 2) < maxLeft) || (cursorX + (dragImgWidth / 2) > maxRight)) {
					if (cursorX - (dragImgWidth / 2) < maxLeft) {
						eLeft = 0;
					} else {
						eLeft = maxRight - dragImgWidth - maxLeft;
					}
				} else {
					eLeft = cursorX - (dragImgWidth / 2) - maxLeft;
				}
		
				if ((cursorY - (dragImgHeight / 2) < maxTop) || (cursorY + (dragImgHeight / 2) > maxBottom)) {
					if (cursorY - (dragImgHeight / 2) < maxTop) {
						eTop = 0;
					} else {
						eTop = maxBottom - dragImgHeight - maxTop;
					}
				} else {
					eTop = cursorY - (dragImgHeight / 2) - maxTop;
				}
				$('#focus-section').css({ left: eLeft, top: eTop});
		
				iLeft = eLeft / (prodW - dragImgWidth);
				iTop = eTop / (prodH - dragImgHeight);
				if (!$.browser.msie) {
					if (iLeft >= 0) {
						iLeft = iLeft * -640;
						iTop = iTop * -1060;
					}
				} else {
					if (iLeft >= 0) {
						iLeft = iLeft * -640;
						iTop = iTop * -1064;
					}
				}
				$('#focus-section img').css({ left: iLeft, top: iTop});
			});
		});
	}
});

function thumbSwap(iTarget, iSrc) {
	var iT = getCmdSrc($(iTarget).attr('src'));
	var iS = getImgSrc($(iSrc).attr('src'));
	if (imageCache[iT+iS] == 'undefined') {
		imageCache[iT+iS] = new Image();
		imageCache[iT+iS].src = iT+iS;
	}
	return $(iTarget).attr('src', iT+iS);
}

function getImgSrc(image) {
	var offset = 3;
	var search = '//img.christa-taylor.com';
	if (image.indexOf(search) != -1) {
		offset += search.length;
	}
	if (image.indexOf('/', offset) == -1) {
		return false;
	} else {
		return image.substr((image.indexOf('/', offset)+1));
	}
}

function getCmdSrc(image) {
	return image.replace(getImgSrc(image), '');
}