$(function() {
	// site wide
	// control search query input
	$('#sQ').defaultvalue('Search');
	$('#sQ').focus(function() {
		$(this).toggleClass('focus');
	}).blur(function() {
		$(this).toggleClass('focus');
	});
	// flyout my account nav
	$('#hSub p a:eq(1)').mouseover(function(){
		$('#hSub').animate({
			width: '850px'
		},1000);
		setTimeout("$('#accntNav').fadeIn('slow')",500);
	});
	$('#accntNav img').click(function() {
		$('#hSub').animate({
			width: '375px'
		},500);
		$('#accntNav').fadeOut('fast');
	});
	// floating left nav
/*	menuYloc = parseInt($('#mainI').css("top").substring(0,$('#mainI').css("top").indexOf("px")))
	$(window).scroll(function () { 
		offset = menuYloc + $(document).scrollTop() - 130 + 'px';
		offsetN = $(document).scrollTop();
		var offB = (offsetN - $('#mainI').height()) * -1;
		//alert(offB);
		if (offsetN > 130 && offB > 325) {
			$(name).animate({top:offset},{duration:500,queue:false});
		} else if (offB < 325) {
			return;
		} else {
			$(name).animate({top: '0px'},{duration:500,queue:false});
		}
	});
*/
	
	// hero
	// adjust height of right column  based on left column or a min-height of 430
	var h = $('#mainIl').height() + 20;
	if (h > 430) {
		$('#secLandM').height(h);
		$('#secLandS').css('bottom','0px');
	} else {
		$('#secLandM').height(430);
		$('#secLandS').css('bottom','0px');
	}
	
	// product detail
	// populate swatches, assign functions, populate color select, preload images in array
	if ('object' == typeof product) 
	{

		try { 
			// create swatches, load color options and pre-load images
			for (var i=0; i<product.colors.length; i++) {
				$('#swatches ul').append('<li style="background-color: #' + product.colors[i].hex + ';"><div><span>' + product.colors[i].name + '</span></div><img src="skins/Skin_1/images/prodDetSwatch_img.png" alt="' + product.colors[i].name + '" title="" onclick="swapImg(\'' + product.colors[i].name + '\',\'' + i + '\'); popSize(getProductColorInfo(this.alt), null);" /></li>');
				$('#prodColor').append('<option class="' + i + '" value="' + product.colors[i].name + '">' + product.colors[i].name + '</option>');
				$.preload([product.colors[i].image], {
					base: 'images/product/medium/'
				});
				$('#swatches ul li img').ifixpng();
			}
			// increase z-index of colors that fall onto the second line so tool tip appears above color swatches above
			$('#swatches ul li:gt(21)').css('z-index', '2');
			// hover intent controls for tool tip
			var hIConfig = {
				sensitivity: 3,
				interval: 75,
				over: swatchesOver,
				timeout: 300,
				out: swatchesOut
			};
			// implement hoverIntent with config settings
			$('#swatches ul li img').hoverIntent(hIConfig);
			// implement url parsing if there is a query string of a color in it, and load appropriate color if so, othewise load first color in array
			var clr = $.url.param("color");
			var siz = $.url.param("size");
			if(clr != null && siz != null) {
				//try {
					var clrNum = getProductColorIndex(clr);
					var sizNum = getProductSizeIndex(product.colors[clrNum], siz);
					var colorObj = getProductColorInfo(clr);
					swapImg(clr, clrNum);
					popSize(colorObj, sizNum);
					//$('#prodSize option:eq(' + sizNum + ')').attr('selected', 'selected');
				//} catch(e) { if (-1 != navigator.userAgent.indexOf('MSIE')) alert(e.message); else alert(e); }
			} else if (clr != null && siz == null) {
				var clrNum = getProductColorIndex(clr);
				var colorObj = getProductColorInfo(clr);
				swapImg(clr, clrNum);
				popSize(colorObj, null);
			} else {
				swapImg(product.colors[0],0);
				popSize(product.colors[0], null);
			}
			// place first image in array within the box and then hide it so the box will not contract/expand when actual product image is changed
			$('#prodImg').append('<img src="images/product/medium/' + product.colors[0].image + '" alt="" title="" />');
			// change product picture from the select box
			$('#prodColor').bind('change', function(e) {
				var clr = $('#prodColor option:selected').attr('value');
				var num = $('#prodColor option:selected').attr('class');
				var colorObj = getProductColorInfo(clr);
				swapImg(clr,num);
				popSize(colorObj, null);
			});
			$('#prodSize').bind('change', function(e) { clearErrors(); });
		
			// scripted sprites for action buttons, just a little touch of class if JS is enabled
			$('#secProdRT ul').children('li').each(function() {
				$(this).children('a').css({
					backgroundImage: 'none',
					position: 'absolute',
					top: '0px',
					left: '0px'
				});
			});
			$('a.add').parent('li').addClass('add-stat').prepend('<div class="add-hov"></div>').children('a').hover(function() { $(this).siblings('div').fadeIn('fast'); }, function() { $(this).siblings('div').fadeOut('slow'); });
			$('a.check').parent('li').addClass('check-stat').prepend('<div class="check-hov"></div>').children('a').hover(function() { $(this).siblings('div').fadeIn('fast'); }, function() { $(this).siblings('div').fadeOut('slow'); });
			$('a.wish').parent('li').addClass('wish-stat').prepend('<div class="wish-hov"></div>').children('a').hover(function() { $(this).siblings('div').fadeIn('fast'); }, function() { $(this).siblings('div').fadeOut('slow'); });
			$('a.email').parent('li').addClass('email-stat').prepend('<div class="email-hov"></div>').children('a').hover(function() { $(this).siblings('div').fadeIn('fast'); }, function() { $(this).siblings('div').fadeOut('slow'); });
			
			// load croslite module
			/*$('#crosliteM').flash({
				src: 'skins/Skin_1/flash/croslite_module.swf',
				width: 178,
				height: 121
			});*/
			
			// make sizing chart popup
			$('#secProdRT p a').attr('target','_blank');
			
		} catch(e) {
			if (-1 != navigator.userAgent.indexOf('MSIE')) alert(e.message); else alert(e);
		}
	}
	
	// shop specific
	$('#prodShop').parent('#mainIr').parent('#mainIm').parent('#mainI').parent('#mainB').children('#bCrumbs').css('display','none');
	$('input[type=image]').addClass('inputImg');
	$('input[type=radio]').addClass('inputRadio');
	$('input[type=checkbox').addClass('inputCheck');
	$('#SigninForm').siblings('table').addClass('newU');
	$('#CartForm table tr td.disc-hd-1').siblings('td.lst-hd-1').addClass('co');
	$('#CartForm table tr td.lst-text-1').siblings('td').addClass('tx');
	$('#tblProdDetail tr:even').addClass('alt');
	$('#CheckoutShippingForm').siblings('div').addClass('cart');
	$('#tblProdDetail tr td.disc-hd-1').siblings('td.lst-hd-1').addClass('co');
	$('#tblProdDetail tr td.lst-text-1').siblings('td').addClass('tx');
	$('div.cart #tblProdDetail tr:even').addClass('alt');
	$('table.bg-1 tr:even').addClass('alt');
	$('#CREDITCARDDiv').append('<div class="ccvImg"><img src="skins/skin_1/images/verificationnumber.gif" alt="" title="" /></div>');
	$('#CardExtraCode').siblings('a').hover(function() { $('div.ccvImg').fadeIn('fast'); }, function() { $('div.ccvImg').fadeOut('fast'); });

});
// set variables for floating nav
var name = "#mainIl dl";
var menuYloc = null;
// product detail swap image controls
function swapImg(clr,num) {
	clearErrors();
	var img = 'images/product/medium/' + product.colors[num].image;
	$('#prodImg img.prodDet').fadeOut('fast', function(){
		$(this).attr('src',img);
		setTimeout("$('#prodImg img.prodDet').fadeIn('slow')",500);
	});
	$('#prodColor').selectOptions(clr);
}
// populate sizes within select
function popSize(colorObj, sizeNum) {
	clearErrors();
	$('#prodSize').empty().append('<option value="Size">Size</option>');
	for (var i=0; i<colorObj.sizes.length; i++) {
		var sel = (sizeNum == i) ? 'selected="selected"' : '';
		$('#prodSize').append('<option class="' + colorObj.sizes[i].isAvailable + '" value="' + colorObj.sizes[i].size + '"' + sel + '>' + colorObj.sizes[i].size + '</option>');
	}
	if ((null == sizeNum || sizeNum == 0) && (-1 == navigator.userAgent.indexOf('MSIE 6.')))
	{
		//$('#prodSize option[class="true"]:first').attr('selected', 'selected');
	}
}
// show tool tip
function swatchesOver() {
	var marg = $(this).siblings('div').width() / 2 * -1;
	$(this).siblings('div').css('margin-left', marg).css('opacity', 0.0);
	$(this).siblings('div').animate({
		top: "-23px",
		opacity: 0.9999
	}, 500).css('display', 'block');
}
// hide tool tip
function swatchesOut() {
	$(this).siblings('div').animate({
		top: "0px",
		opacity: 0.0
	}, 500, function() {
		$(this).css('display', 'none');
	});
}


//**********************************************************************
//	Form Validation Functions used by product detail
//**********************************************************************
function validateCartForm(frm, bWishList)
{
    if ('object' != typeof frm)
        return true;
    // else
    
    submitonce(frm);
    
    // validate quantity
    var iQty = parseInt(frm['Quantity'].value);
    if ((isNaN(frm['Quantity'].value)) || (iQty <= 0))
    {
        alert('Quantity must be a valid non-negative number!');
        frm['Quantity'].value = '1';
        submitenabled(frm);
        return false;
    }
    // check combos for posterity
    if ((frm['Color'].selectedIndex < 0) || (frm['Size'].selectedIndex <= 0))
    {
		$('#prodSize').fadeOut(100, function() { $(this).fadeIn(100) });
		$('#prodDet').append('<div id="warnSize" class="warning"><p>A size must be selected!</p><img src="skins/Skin_1/images/warning_close.gif" alt="Close" title="Close" /></div>').children('#warnSize').fadeIn('fast').children('img').click(function() { $('#prodDet div.warning').fadeOut('fast') });
		//alert('A size must be selected!');
		//frm['Color'].selectedIndex = frm['Size'].selectedIndex = 0;
		submitenabled(frm);
		return false;
    }
    
    // check for availability (only if not adding to wishlist)
    var color = frm['Color'].options[frm['Color'].selectedIndex].text;
    var size = frm['Size'].options[frm['Size'].selectedIndex].text;
    var isAvail = ('true' == getProductAvailability(color, size));
    var qtyAvail = getProductQuantity(color, size);
    if ((!bWishList) && (!isAvail))
    {
		$('#prodDet').append('<div id="warnOut" class="warning"><p>' + sOFSM + '</p><img src="skins/Skin_1/images/warning_close.gif" alt="Close" title="Close" /></div>').children('#warnOut').fadeIn('fast').children('img').click(function() { $('#prodDet div.warning').fadeOut('fast') });
		//alert('The product is out of stock in the size and color selected!');
		frm['Color'].focus();
		submitenabled(frm);
		return false;
    }
    
    // check for qty vs qty avail
    if ((!bWishList) && (iQty > qtyAvail))
    {
		alert('The quantity entered is greater than the quantity available.');
		frm['Quantity'].select();
		submitenabled(frm);
		return false;
    }
    
    // otherwise allow the form to be submitted
    submitenabled(frm);
    return true;
}

function getProductAvailability(colorName, size)
{
	var color = getProductColorInfo(colorName);
	if ('object' == typeof color)
	{
		var size = getProductSizeInfo(color, size);
		if ('object' == typeof size)
		{
			return size.isAvailable;
		}
	}
	return null;
}

function getProductQuantity(colorName, size)
{
	var color = getProductColorInfo(colorName);
	if ('object' == typeof color)
	{
		var size = getProductSizeInfo(color, size);
		if ('object' == typeof size)
		{
			return parseInt(size.quantity);
		}
	}
	return null;
}

function getProductColorInfo(colorName)
{
	if ('object' == typeof product)
    {
		var ct = product.colors.length;
		for (var i = 0; i < ct; i++)
		{
			if (product.colors[i].name.toLowerCase() == colorName.toLowerCase())
			{
				return product.colors[i];		
			}
		}
    }
    else
    {
		return null;
    }
}

function getProductColorIndex(colorName)
{
	if ('object' == typeof product)
    {
		var ct = product.colors.length;
		for (var i = 0; i < ct; i++)
		{
			if (product.colors[i].name.toLowerCase() == colorName.toLowerCase())
			{
				return i;		
			}
		}
    }
    else
    {
		return null;
    }
}

function getProductSizeInfo(colorObject, size)
{
	if ('object' == typeof colorObject)
	{
		var ct = colorObject.sizes.length;
		for (var i = 0; i < ct; i++)
		{
			if (colorObject.sizes[i].size.toLowerCase() == size.toLowerCase())
			{
				return colorObject.sizes[i];
			}
		}
	}
	else
	{
		return null;
	}
}

function getProductSizeIndex(colorObject, size)
{
	if ('object' == typeof colorObject)
	{
		var ct = colorObject.sizes.length;
		for (var i = 0; i < ct; i++)
		{
			if (colorObject.sizes[i].size.toLowerCase() == size.toLowerCase())
			{
				return i;
			}
		}
	}
	else
	{
		return null;
	}
}

function DonotSubmit(e)
{
    var key;
    if(window.event)
        key = window.event.keyCode;
    else
        key = e.which;
    if(key == 13)
        return false;
    else
        return true;
}

function clearErrors() {
	$('div.warning').fadeOut('slow');
	$('#prodSize').removeClass('error');
}
