var g_initialHeight = 0;
var g_currentProduct = 0;
var g_currentColor = 0;
var g_currentColorPretty = 0;
var g_currentAngle = 0;
var g_currentImage = 0;
var g_currentZoomImage = 0;
var preAvaiText = $('div.actConfirm p:eq(0) strong').text();
var preColorText = $('div.actConfirm p:eq(1) strong').text();
var preSizeText = $('div.actConfirm p:eq(2) strong').text();
var preInStockDate = $('div.actConfirm p.date strong').text();
var preTab = $('div.actSizes .tabs-selected').text().substr(0,1);
var isJibbitz = false;
var isBisn = false;
var isColorOnly = false;

$(function() {
	
	// check for size chip sz_oneeu.png and apply a custom style to parent div
	var hasSizeChipOne = ".prodDet div.actSizes ul li label img";
	var srcSizeChipOne = "[src*='sz_oneeu.png']";	
	if ($(hasSizeChipOne).is(hasSizeChipOne + srcSizeChipOne)) {
		$('div.actSizes').addClass('szSizeOne');
	} 
	
	// Grab the title tag from the right column color chips 
	// Create a UL/LI with the results and place them into the details tab 
	if ($("#details .colorsBox").is("#details .colorsBox:has(ul)")) {
	} else {
		buildColorsBox("#details .colorsBox");
	}
	function buildColorsBox(sColorNode) {
		var uList = $('<ul class="colorsNode">');
		$(".actions ul.actColors label img").each(function() {
		uList.append($("<li>" + $(this).attr("title") + "</li>"));
		});
	$(sColorNode).append(uList);
	}
	
	// take alt and title attributes from color chips, size chips and thumbnails and create a span with the same info next to it
	// this has to be done as the tooltip function clears both so the browser does not show the standard alt/title display
	$('ul.actColors li ul li').each(function() {
		var alt = $(this).children('label').children('img').attr('alt');
		var title = $(this).children('label').children('img').attr('title');
		$(this).append('<span title="' + alt + '">' + title + '</span>');
	});
	/*$('ul.actSizes li').each(function() {
		var alt = $(this).children('label').children('img').attr('alt');
		var title = $(this).children('label').children('img').attr('title');
		$(this).append('<span title="' + title + '">' + alt + '</span>');
	});*/
	$('div.thumbs ul li').each(function() {
		var alt = $(this).children('img').attr('alt');
		var title = $(this).children('img').attr('title');
		$(this).append('<span title="' + alt + '">' + title + '</span>');															
	});
	
	// set global variables
	// Strip out spaces of the product name
	var productName = $('div.desc h1#pname').text();
    
    // uppercase all the letter which follow after a space
    var spacePos;
    // use a counter to not produce a infinite loop
    var saftyCounter = 0;
    while((spacePos = productName.indexOf(" ")) != -1) {
        productName = productName.replace(/ .?/, productName.charAt(spacePos+1).toUpperCase());
        saftyCounter++;
        if(saftyCounter > 100) { break; }
    }
    
   	// uppercase all the letter which follow after a hyphen
   	var spacePos;
   	// use a counter to not produce a infinite loop
   	var saftyCounter = 0;
   	while((spacePos = productName.indexOf("-")) != -1) {
       	productName = productName.replace(/-.?/, productName.charAt(spacePos+1).toUpperCase());
       	saftyCounter++;
       	if(saftyCounter > 100) { break; }
   	} 

	// strip out special characters
	productName = productName.replace(/[^a-zA-Z 0-9]+/g,'');

	// Lower case the first letter of the product name
	productName = productName.charAt(0).toLowerCase() + productName.substring(1);

	g_currentProduct = productName;
	g_currentPID = $('div.prodBx span.prodID').attr('title');
	// get selected color: this is the typical scenario
	g_currentColor = $('ul.actColors li ul li.sel span:first').attr('title');
	// if no selected color: special case - could be an unavailable variation product (with suppressed color chip), but it was requested from the Product Detail Page 
	if (g_currentColor == null) { 
		g_currentColor = $('ul.actColors li ul span#unavailvariant').attr('title');
		//$('ul.actColors li:first').append('<span class="nfoTxt">This color is currently out of stock.</span>');
	}
	// if still null: special case - a master product, get the first color chip's color
	if (g_currentColor == null) { 
		g_currentColor = $('ul.actColors li ul li span:first').attr('title'); 
		$('ul.actColors li:eq(0) ul li:nth-child(1)').addClass('sel');
	}
	// if still null, it's for Jibbitz product that never has color swatches, defaulting it to "001"
	if (g_currentColor == null) { g_currentColor = "001"; isJibbitz = true; }
	
	g_currentColorPretty = $('ul.actColors li ul li.sel span:first').text();
	g_currentAngle = $('div.thumbs ul li.sel span').attr('title');
	g_currentImage = g_path+'product-images/standard/' + g_currentPID + '_' + g_currentAngle + '_' + g_currentColor + '.jpg';
	g_currentZoomImage = g_path+'product-images/large/' + g_currentPID + '_' + g_currentAngle + '_' + g_currentColor + '.jpg';
	
	// colors
	$('ul.actColors li ul li:nth-child(10n)').css('margin-right','0px');	
	$('ul.actColors li p').text(g_currentColorPretty);
    $('.prodFR h3').text(g_currentColorPretty);
	$('div.actConfirm p:eq(1) strong').text(g_currentColorPretty);
	// size
	$('div.actConfirm p:eq(2) strong').text($('ul.actSizes li.sel span').text());
	
	// on page load - variant without size attribute: get the currently selected color
	if ($('div.actSizes span#size').text() != "") {
		var curSzValue = $('div.actSizes span#size').text();
		isColorOnly = true;

		$('div.actConfirm p.size').hide();
		
		// update the pid field and enable add to basket if product is in stock
		updateVariationProduct({"variationSize": curSzValue, "variationColor": g_currentColor, "colorOnly": isColorOnly});
	}
	else {
		// on page load - update display of color and size chips for default selection
		updateVariationProduct({"variationSize": $('ul.actSizes li.sel input').attr("value"), "variationColor": g_currentColor, "onpageload": true});
	}
	
	// on page load - display default selected color's price and applicable promotions/tiered pricing applied (set in the PriceBook)
	if (!isJibbitz) {
		$('div.priceBL>div').css('display','none');
		$('#'+g_currentColor).css('display','block');
	}
	
	$('ul.actColors li ul li img').click(function() {		
		if(!$(this).parents('li').hasClass('oos_inAllSizes')) {
			if($(this).parents('li').hasClass('oos')) {
				// color is not in stock - disable add to cart and unselect size
				$('div.actConfirm button').attr('disabled','disabled').css('cursor','default').children('span').addClass('disabled').parents('button').siblings('strong').show();
				$('a#addtowishlistlink').attr('style', 'display: none;');
				$('div.ps p.acts span.dis').attr('style', 'display: block;');
				$('ul.actSizes li').removeClass('sel');
			}

			// slide up the BISN if it was slide down previously
			$('div.actConfirm div.notify').slideUp('fast');
			
			$('ul.actColors li ul li').removeClass('sel');
			$(this).parents('li').addClass('sel');
			
			var curClr = $(this).parent().siblings('span').text();
	        $('.prodFR h3').text(curClr);
			var curClrID = $(this).parent().siblings('span').attr('title');
			// display selected color in both color selectors
			$('label[for=color-'+curClrID+']').children('img').parents('li').addClass('sel');
			
			// set new email a friend link
			setColorEmailFriend(g_currentPID,curClrID);
			
			$('ul.actColors li p').text(curClr);
			// replace all the thumbs images if another color is selected
			$('div.thumbs ul li img').each(function () {
					var $this = $(this);
					var angle = $this.siblings('span').attr('title');
					$this.attr('src', g_path+'product-images/mini/' + g_currentPID + '_' + angle + '_' + curClrID + '.jpg');
				}
			);
			
			var g_currentImage;
			if ($('div.prod').hasClass('zoom')) {
				g_currentImage = g_path+'product-images/large/' + g_currentPID + '_' + g_currentAngle + '_' + curClrID + '.jpg';
			} else {
				g_currentImage = g_path+'product-images/standard/' + g_currentPID + '_' + g_currentAngle + '_' + curClrID + '.jpg';
			}
			
			$('div.prod img').attr('src', g_currentImage);
			$('div.actConfirm p:eq(1) strong').text(curClr);
			
			// display selected color's price and applicable promotions/tiered pricing applied (set in the PriceBook)
			$('div.priceBL>div').css('display','none');
			$('#'+curClrID).css('display','block');
			
			// get the currently selected colors <div class="actSizes">
			var curSzValue;
			isColorOnly = false;
			if ($('div.actSizes span#size').text() == "") {
		        if ($('div.actSizes .tabs-selected').text().substr(0,1) == preTab && $('ul.actSizes li.sel span').text() != "") {
					curSzValue = $('ul.actSizes li.sel input').attr("value");
		        	$('div.actConfirm p:eq(0) strong').text(preAvaiText);
					$('div.actConfirm p:eq(2) strong').text($('ul.actSizes li.sel span').text());
		        	//$('div.actConfirm p:eq(2) strong').text(preSizeText);
		        }
		        else {
		        	$('div.actConfirm p:eq(0) strong').text("");
		        	$('div.actConfirm p:eq(2) strong').text("");
		        }
			}
			else {
				curSzValue = $('div.actSizes span#size').text(); // for variant without size attribute
				isColorOnly = true;
			}
			var curClrValue = $('ul.actColors li ul li.sel input').attr("value");
			// update the pid field and enable add to basket if product is in stock
			updateVariationProduct({"variationSize": curSzValue, "variationColor": curClrValue, "colorOnly": isColorOnly});
		}
	});
	// sizes
	if (!$('ul.actSizes').hasClass('mixed') && !$('ul.actSizes').hasClass('alpha')) {
		$('ul.actSizes li:nth-child(10n)').css('margin-right','0px');
	}
	
	
    
    updateTooltips();
    var selectedTab = 0;
    
    // try to select default size panel
	try {
		// mainCategory could be Women, Men, Girls, Boys, Outlet 
		var mainCategory = $('#crumbs a:eq(1)').text();
		for(var i = 0;i<$('div.actSizes ul.tabs li a').length;i++) {
			var tabName = $('div.actSizes ul.tabs li a:eq('+i+')').text();
			if(tabName == mainCategory || (tabName == "Children" && (mainCategory == "Girls" || mainCategory == "Boys"))) {
				selectedTab = i;
				break;
			}
		}
	} catch(e) {
		// an error happened :-(
		alert(e);
	}
	
	var sizeTabs = $('div.actSizes').tabs(selectedTab+1, {
		onShow: function () {
		// set the current shown tab
        $('#sizeLabelInput').val($('div.actSizes .tabs-selected').text());
        //alert ($('div.actSizes .tabs-selected').text());
		//alert($('ul.actColors li ul li.sel span').text() + ":" + preColorText);
		
        if ($('div.actSizes .tabs-selected').text().substr(0,1) == preTab && $('ul.actColors li ul li.sel span').text() == preColorText && $('ul.actSizes li.sel span').text() == preSizeText && (preAvaiText == "In Stock" || preAvaiText == "Pre-Order" || preAvaiText == "Backorder") ) {
			if (isBisn) $('div.actConfirm div.notify').slideDown('fast');
			
        	$('div.actConfirm button:disabled').removeAttr('disabled').css('cursor','pointer').children('span').removeClass('disabled').parents('button').siblings('strong').hide();
    		$('a#addtowishlistlink').attr('style', 'display: block;');
    		$('div.ps p.acts span.dis').attr('style', 'display: none;');
    		$('div.actConfirm p:eq(0) strong').text(preAvaiText);
        	$('div.actConfirm p:eq(2) strong').text(preSizeText);
    		if((preAvaiText == "Pre-Order" || preAvaiText == "Backorder") && preInStockDate != "") {
    			$('div.actConfirm p.date strong').text(preInStockDate);
    			$('div.actConfirm p.date').attr('style', 'display: block;');
    		}
        }
        
        else {
			// slide up the BISN if it was slide down previously
			$('div.actConfirm div.notify').slideUp('fast');
			
            $('div.actConfirm button').attr('disabled','disabled').css('cursor','default').children('span').addClass('disabled').parents('button').siblings('strong').show();
    		$('a#addtowishlistlink').attr('style', 'display: none;');
    		$('div.ps p.acts span.dis').attr('style', 'display: block;');
        	$('div.actConfirm p:eq(0) strong').text("");
        	$('div.actConfirm p:eq(2) strong').text("");
    		$('div.actConfirm p.date').attr('style', 'display: none;');

			// get the currently selected colors <div class="actSizes">
			var curSzValue;

	        if ($('div.actSizes .tabs-selected').text().substr(0,1) == preTab && $('ul.actSizes li.sel span').text() != "") {
				curSzValue = $('ul.actSizes li.sel input').attr("value");
	        	$('div.actConfirm p:eq(0) strong').text(preAvaiText);
				$('div.actConfirm p:eq(2) strong').text($('ul.actSizes li.sel span').text());
	        }
	        else {
	        	$('div.actConfirm p:eq(0) strong').text("");
	        	$('div.actConfirm p:eq(2) strong').text("");
	        }
	
			var curClrValue = $('ul.actColors li ul li.sel input').attr("value");
			// update the pid field and enable add to basket if product is in stock
			updateVariationProduct({"variationSize": curSzValue, "variationColor": curClrValue});
        }
    }});
	
    // set the tab which is initially shown
    $('#sizeLabelInput').val($('div.actSizes .tabs-selected').text());
    
	$('ul.actSizes li img').click(function() {
        var variant = getVariantByColorAndSize($('ul.actColors li ul li.sel span').attr('title'), $(this).parent().siblings('span').attr('title'));
        if (variant != undefined && variant.isBisn) isBisn = true;

		if(!$(this).parents('li').hasClass('oos') || isBisn) {
			// slide up the BISN if it was slide down previously
			$('div.actConfirm div.notify').slideUp('fast');

            $('ul.actSizes li').removeClass('sel');
    		$(this).parents('li').addClass('sel');
    		var curSz = $(this).parent().siblings('span').text();
    		$('div.actConfirm p:eq(2) strong').text(curSz);
    		var curSzValue = $('ul.actSizes li.sel input').attr("value");
    		var curClrValue = $('ul.actColors li ul li.sel input').attr("value");
    		updateVariationProduct({"variationSize": curSzValue, "variationColor": curClrValue});
        }
	});
	
	// confirm
	$('div.actConfirm p:has(button:disabled) strong').tooltip({
		delay: 0,
		track: true,
		showURL: false,
		fixPNG: true,
		top: -45,
		left: -130,
		extraClass: 'dis',
		bodyHandler: function() {
			if (!isColorOnly) {
	        	c = $('#addcartselectcolor').text();
	    	}
			else {
				c = $('#addcartselectcolorsize').text();
			}
	        return c;
    	}
	});
	
	$('div.actConfirm p:has(button:disabled)').mouseover(function(){
		isBisn = $('div.actConfirm span#isBisn').text() == "true" ? true : false;

		if(isJibbitz && isBisn) {
			$('div.actConfirm div.notify').slideDown('fast');
		}
	});
	
	$('div.ps p.off a').tooltip({
		delay: 0,
		track: true,
		showURL: false,
		fixPNG: true,
		top: -80,
		left: -9,
		extraClass: 'img',
		bodyHandler: function() {
			c = '<img src="' + g_path + $(this).attr('name') + '" alt="" title="" width="90" height="60"/>';
			return c; 
    }
	});
	// content
	// product box
	$('div.thumbs ul li img').tooltip({
		delay: 0,
		track: true,
		showURL: false,
		fixPNG: true,
		top: -30,
		left: -9
	});
	var isIE6 = ($.browser.msie && parseInt($.browser.version.substr(0,1)) < 7);
    
    // ugly hack to make the img line work in internet explorer 6
    if(isIE6) {
	   $('.prodBx').css('position', 'static');
	}
    
    $('<img>').appendTo('div.prod').addClass('p').attr('src', g_currentImage);
	
    if(isIE6) {
        $('.prodBx').css('position', 'absolute');
    }
    
    $('div.prod').onImagesLoad({
		itemCallback: firstImageLoaded
	});

    $('div.thumbs ul li img:not(div.thumbs ul li.sel img)').fadeTo('fast', 0.5);
	var hiCfg = {
		sensitivity: 3,
		interval: 75,
		over: thumbOvr,
		timeout: 300,
		out: thumbOut
	};
	$('div.thumbs ul li img').hoverIntent(hiCfg);
	
	//enlarge
	$('div.prodF a').click(function() {
		$('div.zoomedPicker').show();
		$('div.prod').empty().addClass('zoom');
		$('div.prodBx').animate({
			width: '720px',
			height: '432px'
		}, 'slow', function() { 
			$('div.prodF a').animate({
				width: '0px'
			}, 'fast');
			$('div.zoomCls').animate({
				width: '67px'
			}, 'fast');
			$('div.zoomBrdr').fadeIn('fast');
			
			g_currentColor = $('ul.actColors li ul li.sel span').attr('title');
			if (g_currentColor == null) { 
				g_currentColor = $('ul.actColors li ul li span').attr('title'); 
				$('ul.actColors li ul li:nth-child(1)').addClass('sel');
				// for Jibbitz product that never has color swatches
				if (g_currentColor == null) { g_currentColor = "001";}
			}
			
			g_currentAngle = $('div.thumbs ul li.sel span').attr('title');
			
			$('<img>').appendTo('div.zoom').addClass('z').attr('src', g_path+'product-images/large/' + g_currentPID + '_' + g_currentAngle + '_' + g_currentColor + '.jpg');
			$('div.zoom img.z').onImagesLoad({
				itemCallback: zoomImageLoaded
			});
		});
		$('div.prod').animate({
			width: '718px',
			height: '399px',
			marginLeft: '1px',
			marginTop: '1px'
		}, 'slow');
		$('div.thumbs').animate({
			marginRight: '85px'
		}, 'slow');
		$('div.desc').animate({
			marginTop: '442px'
		}, 'slow');
        //$('div.zoomCls img').css('visibility', 'visible');
	});
	
	// close enlarge
	$('div.zoomCls img').click(function() {
		$('div.zoomedPicker').hide();
		$('div.prod').empty().removeClass('zoom');
		$('div.zoomBrdr').fadeOut('fast');
		$('div.prodF a').animate({
			width: '67px'
		}, 'fast');
		$('div.zoomCls').animate({
			width: '0px'
		}, 'fast', function() {
			$('div.prodBx').animate({
				width: '503px',
				height: g_initialHeight + 32 + 'px'
			}, 'slow');
			$('div.prod').animate({
				width: '503px',
				height: g_initialHeight,
				marginLeft: '0px',
				marginTop: '0px'
			}, 'slow', function() {
				g_currentColor = $('ul.actColors li ul li.sel span').attr('title');
				
				if (g_currentColor == null) { 
					g_currentColor = $('ul.actColors li ul li span').attr('title'); 
					$('ul.actColors li ul li:nth-child(1)').addClass('sel');
					// for Jibbitz product that never has color swatches
					if (g_currentColor == null) { g_currentColor = "001";}
				}
				
				g_currentAngle = $('div.thumbs ul li.sel span').attr('title');
				
				$('<img>').appendTo('div.prod').addClass('p').attr('src', g_path+'product-images/standard/' + g_currentPID + '_' + g_currentAngle + '_' + g_currentColor + '.jpg');
				$('div.prod img.p').onImagesLoad({
					itemCallback: imageLoaded
				});
			});
			$('div.thumbs').animate({
				marginRight: '4px'
			}, 'slow');
			$('div.desc').animate({
				marginTop: g_initialHeight + 42 + 'px'
			}, 'slow');
		});
	});
	
	$('div.descCont').tabs();
	
	var curClr = $('.actColors li.sel label').attr('for');
	var curSz = $('.actSizes label:first-child').attr('for');
	var curLink = $('#emailfriendlink').attr('href');
	if (curClr != undefined && curSz != undefined) {
		var curClrArray = curClr.split('-');
		var curSzArray = curSz.split('-');
		$('#emailfriendlink').attr('href',curLink + '-' + curClrArray[1] + '-' + curSzArray[1]);
	}
	
});

function thumbOvr() {
	$('div.thumbs ul li.sel').removeClass('sel');
	$('div.thumbs ul li img:not(div.thumbs ul li.sel img)').fadeTo('fast', 0.5);
				
	g_currentColor = $('ul.actColors li ul li.sel span').attr('title');
	if (g_currentColor == null) { 
		g_currentColor = $('ul.actColors li ul li span').attr('title'); 
		$('ul.actColors li ul li:nth-child(1)').addClass('sel');
		// for Jibbitz product that never has color swatches
		if (g_currentColor == null) { g_currentColor = "001";}
	}
	
	g_currentAngle = $(this).siblings('span').attr('title');
	
	if ($('div.prod').hasClass('zoom')) {
		$('<img>').appendTo('div.zoom').addClass('z').attr('src', g_path+'product-images/large/' + g_currentPID + '_' + g_currentAngle + '_' + g_currentColor + '.jpg');
		$('div.loading').show();
		$('div.zoom img.z').onImagesLoad({
			itemCallback: newZoomImageLoaded
		});
	} else {
		$('<img>').appendTo('div.prod').addClass('p').attr('src', g_path+'product-images/standard/' + g_currentPID + '_' + g_currentAngle + '_' + g_currentColor + '.jpg');
		$('div.prod img.p').onImagesLoad({
			itemCallback: newImageLoaded
		});
	}
	
	$(this).parents('li').addClass('sel');
	$(this).fadeTo('fast', 0.99);
}
function thumbOut() {
	
}

function firstImageLoaded() {
	g_initialHeight = $('div.prod img').height();
	$('div.prod').animate({
		height: g_initialHeight + 'px'
	}, 'fast', function() {
		$('div.prod img.p').fadeIn('fast').removeClass('p');
		$('div.desc').animate({
			marginTop: g_initialHeight + 42 + 'px'
		});
	});
}
function imageLoaded() {
	$('div.prod img.p').fadeIn('fast').removeClass('p');
}
function newImageLoaded() {
	$('div.prod img.p').fadeIn('fast', function() { $('div.prod img:first-child').remove(); }).removeClass('p');
}
function zoomImageLoaded() {
	$('div.zoom img.z').fadeIn('fast').removeClass('z');
}
function newZoomImageLoaded() {
	$('div.loading').hide();
	$('div.zoom img.z').fadeIn('fast', function() { $('div.zoom img:first-child').remove(); }).removeClass('z');
}

function updateVariationProduct(attrs) {
	// hide the no size available message, just in case it was shown before
	$('div.actSizes span#noSizeAtAll').hide();
	
	// remove swatches which are not available and mark swatches which are out of stock
    // as out of stock
    if(attrs["variationColor"] !== undefined && attrs["variationColor"] !== "") {	
    	// get all size line items
    	jQuery("ul.actSizes li").each(function () {
    		var $this = jQuery(this);
    		var size = $this.children("span").attr("title");
    		var variant = getVariantByColorAndSize(attrs["variationColor"], size);
    		// if the variant exists
    		if(variant !== undefined) {
	    		// show it, just in case it is not shown yet
	    		$this.show();
	    		// if the variant is not in stock
	   			if(!variant.inStock) {
	   				$this.addClass("oos");
	   			} else {
	   				// mark it as in stock, just in case it was marked out of stock before
	   				$this.removeClass("oos");
	   			}
	   			//alert(variant.avStatus + ":" + variant.inStockDate);
	   		// if the variant does not exists in this size mark it as hidden
    		} else {
    			$this.hide();
    		}
    	});

    	// show the no size available message, if all sizes are not available in the gender tab
    	if ($('div.actSizes .tabs-container ul li:visible').length == 0 && !attrs["onpageload"]) {
    		$('div.actSizes span#noSizeAtAll').attr('style', 'display: block;');
    	}
    }

    /* if it's on page load, just return and skip the rest
    if (attrs["onpageload"]) {
    	return;
	}*/

    // do nearly the same with size
    if(attrs["variationSize"] !== undefined && attrs["variationSize"] !== "") {
    	// get all color line items
    	jQuery("ul.actColors li ul li").each(function () {
    		var $this = jQuery(this);
    		//$this.show();
    		var color = $this.children("span").attr("title");
    		var variant = getVariantByColorAndSize(color, attrs["variationSize"]);
    		// if the variant exists
    		if(variant !== undefined) {
	    		// show it, just in case it is not shown yet
	    		$this.show();
	    		// if the variant is not in stock
	   			if(!variant.inStock) {
	   				$this.addClass("oos");
	   			} else {
	   				// mark it as in stock, just in case it was marked out of stock before
	   				$this.removeClass("oos");
	   			}
    		} else {
    			$this.addClass("oos");
    		}
    	});
    }
    
	// if not all properties are set in attrs just return.
	if (!attrs["colorOnly"]) {
	    for(var property in attrs) {
			if(attrs[property] === undefined || (property != "colorOnly" && attrs[property] == "")) {
				updateTooltips();
				return;
			}
		}
	}
	// append all the attribute values to one string
	// size: "L", color: "010"
	// becomes: "L010"
	// FIXME: What happens if I have color 00, 0 and size 00, 0. What would '000' be?
	var attrToStr = function(attrObj) {
		var result = "";
		jQuery.each(variations.variations.attributes, function(){
			result += attrObj[this.id];
		});
		return result;
	}
	
	var avaiText = "";
	var inStockDate = "";
	var attrsStr = attrToStr(attrs);
	var found;
	for (var i=0; i< variations.variations.variants.length; i++) {
		variant = variations.variations.variants[i];
		if (attrToStr(variant.attributes) === attrsStr) {
			found = variant;
			avaiText = found.avStatus;
			inStockDate = found.inStockDate;
			isBisn = found.isBisn;
		}
	}
		
	// TODO: add other price display
	// jQuery("#price").html(found.price);
	if(found === undefined || !found.inStock) {
		if (isBisn) $('div.actConfirm div.notify').slideDown('fast');
		$('div.actConfirm p:eq(0)').html('Availability: <strong class="oos">' + $('#oostext').text() + '</strong>'); // <a href="">(?)</a>');
		$('div.actConfirm button').attr('disabled','disabled').css('cursor','default').children('span').addClass('disabled').parents('button').siblings('strong').show();
		$('a#addtowishlistlink').attr('style', 'display: none;');
		$('div.ps p.acts span.dis').attr('style', 'display: block;');
		
		if (!found.inStock) {
			jQuery("#pid").val(found.id);
			preAvaiText = $('div.actConfirm p:eq(0) strong').text();
			preColorText = $('div.actConfirm p:eq(1) strong').text();
			preSizeText = $('div.actConfirm p:eq(2) strong').text();
			preInStockDate = $('div.actConfirm p.date strong').text();
			preTab = $('div.actSizes .tabs-selected').text().substr(0,1);
		}
		
	} else {
		jQuery("#pid").val(found.id);
        // update the price display
        jQuery("#standard-price-label").text((found.pricing.currencyCode == "USD" ? "$" : "") + ( found.pricing.standard == 0.0 ? found.pricing.sale : found.pricing.standard));
        $('div.actConfirm div.notify').slideUp('fast');
		$('div.actConfirm p:eq(0) strong').removeClass('oos').text(avaiText).parents('p').children('a').remove();
		$('div.actConfirm button:disabled').removeAttr('disabled').css('cursor','pointer').children('span').removeClass('disabled').parents('button').siblings('strong').hide();
		$('div.ps p.acts span.dis').attr('style', 'display: none;');
		$('a#addtowishlistlink').attr('style', 'display: block;');
		preAvaiText = $('div.actConfirm p:eq(0) strong').text();
		preColorText = $('div.actConfirm p:eq(1) strong').text();
		preSizeText = $('div.actConfirm p:eq(2) strong').text();
		preInStockDate = $('div.actConfirm p.date strong').text();
		preTab = $('div.actSizes .tabs-selected').text().substr(0,1);
	}
	
	// Display date for Pre-Order or Backorder
	if((avaiText == "Pre-Order" || avaiText == "Backorder") && inStockDate != "") {
		$('div.actConfirm p.date strong').text(inStockDate);
		$('div.actConfirm p.date').attr('style', 'display: block;');
	}
	else {
		$('div.actConfirm p.date').attr('style', 'display: none;');
	}
	
    updateTooltips();
}

function updateTooltips() {
    $('ul.actColors li ul li img:not(ul.actColors li ul li.oos img)').tooltip({
        delay: 0,
        track: true,
        showURL: false,
        fixPNG: true,
        top: -30,
        left: -9,
        extraClass: 'chip',
        bodyHandler: function() {
            c = $(this).parent().siblings('span').text();
            return c;
        }
    });

    $('ul.actColors li ul li.oos img').tooltip({
        delay: 0,
        track: true,
        showURL: false,
        fixPNG: true,
        top: -63,
        left: -130,
        extraClass: 'oos',
        bodyHandler: function() {
            c = $(this).parent().siblings('span').text();

            if (isColorOnly) {
                var variant = getVariantByColorAndSize($(this).parent().siblings('span').attr('title'), $('div.actSizes span#size').text());

            	if(variant.isBisn) {
            		//.tooltip.top = -73;
            		c = c + $('#ooscolorbisn').text();
            	}else
            		c = c + $('#ooscolornotbisn').text();
            }
            else {
            	c = c + $('#ooscolorsize').text();
            }
            return c;            
    	}
    });

	$('ul.actSizes li img:not(ul.actSizes li.oos img)').tooltip({
		delay: 0,
		track: true,
		showURL: false,
		fixPNG: true,
		top: -30,
		left: -9
	});
	
    $('ul.actSizes li.oos img').tooltip({
    	delay: 0,
        track: true,
        showURL: false,
        fixPNG: true,
        top: -80,
        left: -130,
        extraClass: 'oos',

    	bodyHandler: function() {
        	c = $('#oossize').text();
        	c = c + $(this).parent().siblings('span').text();
            var variant = getVariantByColorAndSize($('ul.actColors li ul li.sel span').attr('title'), $(this).parent().siblings('span').attr('title'));
            
            if(variant.isBisn) {
            	isBisn = true; // must update this value when mouseover
            	c = c + $('#oossizebisn').text();
            }
        	else {
        		isBisn = false; // must update this value when mouseover
            	c = c + $('#ooscolorsize').text();
            }
            return c;
    	}
    });
}

function getVariantByColorAndSize(color, size) {
	for (var i=0; i< variations.variations.variants.length; i++) {
		var variant = variations.variations.variants[i];
		// alert(attrToStr(variant.attributes)+" === "+attrsStr);
		if (variant.attributes.variationColor === color && variant.attributes.variationSize === size) {
			return variant;
		}
	}
	return undefined;
}

function setColorEmailFriend(pid,cid) {
	// add the color id to the email a friend link
	var currentLink = $('#emailfriendlink').attr('href');
	var linkArray = currentLink.split('&');
	var sizeCode = $('.actSizes label:first-child').attr('for');
	var sizeArray = sizeCode.split('-');
	var updateLink = linkArray[0] + '&' + linkArray[1] + '&' + 'pid=' + pid + '-' + cid + '-' + sizeArray[1]; 
	$('#emailfriendlink').attr('href',updateLink);
}

/*
 * jQuery 'onImagesLoaded' plugin v1.1.0
 * Fires callback functions when images have loaded within a particular selector.
 *
 * Copyright (c) Cirkuit Networks, Inc. (http://www.cirkuit.net), 2008.
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * For documentation and usage, visit "http://includes.cirkuit.net/js/jquery/plugins/onImagesLoad/1.1/documentation/"
 */
(function($){$.fn.onImagesLoad=function(options){var self=this;self.opts=$.extend({},$.fn.onImagesLoad.defaults,options);self.bindEvents=function($imgs,container,callback){if($imgs.length===0){if(self.opts.callbackIfNoImagesExist&&callback){callback(container);}}else{var loadedImages=[];if(!$imgs.jquery){$imgs=$($imgs);}$imgs.each(function(i,val){$(this).bind('load',function(){if(jQuery.inArray(i,loadedImages)<0){loadedImages.push(i);if(loadedImages.length==$imgs.length){if(callback){callback(container);}}}}).each(function(){if(this.complete||this.complete===undefined){this.src=this.src;}});});}};var imgAry=[];self.each(function(){if(self.opts.itemCallback){var $imgs;if(this.tagName=="IMG"){$imgs=this;}else{$imgs=$('img',this);}self.bindEvents($imgs,this,self.opts.itemCallback);}if(self.opts.selectorCallback){if(this.tagName=="IMG"){imgAry.push(this);}else{$('img',this).each(function(){imgAry.push(this);});}}});if(self.opts.selectorCallback){self.bindEvents(imgAry,this,self.opts.selectorCallback);}return self.each(function(){});};$.fn.onImagesLoad.defaults={selectorCallback:null,itemCallback:null,callbackIfNoImagesExist:false};})(jQuery);