/* initmo.com */
/* written by allwebpromotion.com for intimo.com */

(function($) {

	/* CENTER HORIZONTAL NAV */
	
	$.fn.centerHorizontalNav = function () {
		var s = [	'paddingLeft', 'paddingRight', 'marginLeft', 'marginRight',
					'borderLeftWidth', 'borderRightWidth'];
		// each UL nav
		return this.each(function(){
			var jUl = $(this);
			var ulWidth = jUl.width();
			var liWidth = 0;
			// remove left and right margins for first and last LIs respectively
			var jLis = jUl.find('> li');
			var count = jLis.size();
			jLis.eq(0).css('margin-left','0');
			jLis.eq(count - 1).css('margin-right','0');
			// each LI
			jLis.each(function(){
				var x;
				var jLi = $(this);
				liWidth = liWidth + jLi.width();
				for (var k=0;k<s.length;k++) {
					x = parseInt(jLi.css(s[k]));
					if (!isNaN(x)) { liWidth = liWidth + x; }
				}
			});
			var x = ulWidth - liWidth;
			if (x > 0) {
				//$(this).find('li').eq(0).css('margin-left', parseInt(x / 2) + 'px');
				//$(this).css('padding-left', parseInt(x / 2) + 'px');
				var p = parseInt(jUl.css('padding-left'));
				p = isNaN(p) ? 0 : p;
				p = parseInt((x / 2) + p);
				$(this).css(	{	'padding-left'	: p + 'px',
									'width'			: 'auto'});
			}
		});
	};

	$.fn.accordian = function (opts) {
		var jLIs = $(this).find('> li');
		jLIs.each(function(){
			var jLI = $(this);
			jLI.find('> a').click(function(){
				jLI.find('> ul').slideToggle(300);
				jLIs.not(jLI).find('> ul').slideUp(300);
				return false;
			});
		});
		return $(this);
	};

	$.fn.awpDefaultInputText = function () {
		return this.each(function(){
			$(this)
				.data('colorActive', $(this).css('color'))				// save focus color
				.blur(function(){										// do blur
					var val = $(this).val();
					if (!(typeof val === 'string' && val.length > 1)) {	// set default if not value
						$(this).val($(this).metadata().text);			// set blur text
					}
					$(this).css('color', $(this).metadata().color)		// set blur color
				})
				.focus(function(){										// do focus
					$(this).css('color', $(this).data('colorActive'));	// set focus color
					if ($(this).val() == $(this).metadata().text) {
						$(this).val('');
					}
				})
				.trigger('blur');										// init
		});
	};

})(jQuery);

//-------------------------------------------------------------------------------------------------
var mysite = {

	'settings' : {
		'lensWidth'					: 150,
		'lensHeight'				: 150,
		'mainImageTransitionTime'	: 200,		// total time
		'homeBannerTransitionTime'	: 600,
		'homeBannerShowTime'		: 5000,
		'accordianMenuTime'			: 300,
		'messageHoldTime'			: 5000,
		'messageFadeTime'			: 1500,
		'totalPriceTransitionTime'	: 200,		// total time
		'sizeNotSelectedValue'		: 'Size',
		'defaultInputTextSel'		: '.default-input-text',
		'addtcartMessageSel'		: '#item-addtocart-message',
		'colorDescSel'				: '.item-image-color-description',
		'validateFormSel'			: '.email-signup, .email-signup-form',
		'textImageProgramUrl'		: 'http://site.intimo.com/awplib/ti.php',
		'colorNameValue'			: {	'black'			: '#000000',
										'white' 		: '#f0f0f0',
										'smoke grey' 	: '#788F9F',
										'silver grey'	: '#C0C0C0',
										'gold'			: '#FFD700',
										'wine'			: '#800000',
										'red'			: '#f00000',
										'hot pink'		: '#FF69B4',
										'light pink'	: '#FFB6C1',
										'navy'			: '#000080',
										'royal blue'	: '#4169E1',
										'medium blue'	: '#0000CD',
										'light blue'	: '#ADD8E6',
										'forest green'	: '#228B22',
										'kelly green' 	: '#4CBB17',
										'green'			: '#008000'},

		// dynamic values
		'isLessThanIE9'				: false,
		'isItemPage'				: false,
		'isSeparatesPage'			: false,
		'jItemContainers'			: null,
		'jHomeBannerImages'			: null,
		'jAddtocartMessage'			: null,
		'timer'						: null,
		'hasMultiOptions'			: false

	},

	'getCurrentHomeBannerIndex' : function () {
		var me = this;
		me.settings.jHomeBannerImages.each(function(i){
			if ($(this).is(':visible')) {
				return i;
			}
		});	
		return null;
	},
	
	//---------------------------------------------------------------------------------------------
	'start' : function () {
	
		var	me = this,
			homeBannerImageCount, jObj, dims;

		me.settings.isItemPage			= $('#itemarea').size() > 0;
		me.settings.isSeparatesPage		= $('#tbitemarea').size() > 0;
		me.settings.isCustomFitPage		= $('body').hasClass('customfit');
		me.settings.isLessThanIE9		= $.browser.msie === true && $.browser.version < 9;
		me.settings.jHomeBannerImages	= $('#home-banner-images .image-container');
		me.settings.jItemContainers		= $('#itemarea, #tbitemarea .tbitem-container');

		// CENTER HORIZONTAL NAV UL
		$('#top-nav').centerHorizontalNav();
		$('#footer-nav').centerHorizontalNav();
		
		// EQUAL HEIGHTS FOR CONTENTS IMAGES
		me.equalHeightContentsImages();

		// ACCORDIAN LEFT NAV
		$('.left-nav.accordian').accordian();
		
		/*// ACCORDIAN LEFT NAV
		if (!$('body').hasClass('customer-service-layout')) {
			$('.left-nav').accordian();
		}*/
		
		// DEFAULT INPUT TEXT
		$(me.settings.defaultInputTextSel).awpDefaultInputText();

		// REVIEWS LIMIT
		me.reviewsLimit();
		
		// FORM VALIDATION
		$(me.settings.validateFormSel).validate({
			'rules': {
				'Email'					: {	'required'	: true,
											'email'		: true}
			},
			'messages': {
				'Email'					: 'Please enter a valid email address'
			}
		});
		
		// HOME ROTATING BANNERS
		homeBannerImageCount = me.settings.jHomeBannerImages.size();
		if (homeBannerImageCount > 0) {
			$('#home-banner-images').cycle({
				'fx'		: 'fade', 
				'pause'		: 1,
				'speed'		: me.settings.homeBannerTransitionTime, 
				'timeout'	: me.settings.homeBannerShowTime,
				'next'		: '#home-banner-control-next',
				'prev'		: '#home-banner-control-prev'
			});
		}
		
		//-----------------------------------------------------------------
		// ITEM OR SEPARATES PAGE

		if (me.settings.isItemPage || me.settings.isSeparatesPage) {

			me.settings.jAddtocartMessage	= $(me.settings.addtcartMessageSel);
			me.settings.jAddtocartMessage
				.find('.message')
					.css('display','none');

			// each item container, either #itemarea or .tbitem-container
			me.settings.jItemContainers.each(function(){
		
				var	baseprice, val, jObj,
					jItemContainer		= $(this),
					jItemImageLink		= jItemContainer.find('.item-image-link'),
					jItemImage			= jItemContainer.find('.item-image img'),
					jItemInsets			= jItemContainer.find('.item-insets .item-inset'),
					jColorRows			= jItemContainer.find('.color-row'),
					jCustomRows			= jItemContainer.find('.custom-row'),
					hasMultiOptions		= me.hasMultiOptions(jItemContainer),
					hasPersonalization	= jItemContainer
											.find('.item-multi-options-table')
												.find('.custom-row').size() > 0,
					item = {
						'jContainer'			: jItemContainer,
						'jImageLink'			: jItemImageLink,
						'jImage'				: jItemImage,
						'jInsets'				: jItemInsets,
						'jColorRows'			: jColorRows,
						'jCustomRows'			: jCustomRows,
						'hasMultiOptions'		: hasMultiOptions,
						'hasPersonalization'	: hasPersonalization,
						'jCustomText'			: (jItemContainer.find('.item-image-custom-text')),
						'jColorDesc'			: (jItemContainer.find('.item-image-color-desc'))
					};

				// set main setting
				me.settings.hasMultiOptions = hasMultiOptions;
					
				// NO MAIN IMAGE
				if (!(jItemImage.size() > 0)) {
					jItemImage = null;
				}
				
				// BASE PRICE
				baseprice = jItemContainer.find('.item-base-price').eq(0).val(); // eq(0) jic
				if (baseprice) {
					baseprice = parseFloat(baseprice) * 1;
					if (isNaN(baseprice)) {
						baseprice = null;
					}
					jItemContainer.data('baseprice', baseprice);
				}
				
				// NO TOTAL PRICE IF NO BASE PRICE
				if (!baseprice) {
					$('#item-price-total').css('display', 'none');
				}

				// OUT OF STOCK
				// body width
				/*jObj = jItemContainer.find('.item-outofstock .body');
				val  = jItemContainer.find('.item-outofstock .title').innerWidth();
				val -= parseInt(jObj.css('borderLeft'), 10);
				val -= parseInt(jObj.css('borderRight'), 10);
				val -= parseInt(jObj.css('paddingLeft'), 10);
				val -= parseInt(jObj.css('paddingRight'), 10);
				jObj.css('width', val + 'px');*/
				// hover
				jItemContainer.find('.item-outofstock .title').hoverIntent({
					'interval'	: 50,
					'over'		: function(){jItemContainer.find('.item-outofstock .body').slideDown(200)},
					'out'		: function(){jItemContainer.find('.item-outofstock .body').slideUp(200)}
				});

				// SETUP IMAGES
	
				// has main image
				if (jItemImage) {
	
					// MAIN IMAGE - no click
					jItemImageLink
						.click(function(){return false;});
	
					// MAIN IMAGE - save image src and href
					jItemImage.data(	'src',			jItemImage.attr('src'));
					jItemImage.data(	'href',			jItemImageLink.attr('href'));
					jItemImage.data(	'isFirstTime',	true);
									
					// INSETS
					
					// each inset
					jItemInsets.each(function(){
					
						var	jInset			= $(this),
							jInsetLink		= jInset.find('.item-inset-link'),
							src				= jInsetLink.attr('href'),
							href			= jInsetLink.metadata().enlargedImageRef, // is set in RTML
							preload1		= new Image(25,25),
							preload2		= new Image(25,25);
						preload1.src		= src;
						preload2.src		= href;
						
						// no default click
						jInsetLink.click(function(){return false;});
						
						jInsetLink.hoverIntent({    
     						'out'		: function(){},	// required    
     						'timeout'	: 0,			// number = milliseconds delay before mouseout, default 0
     						'interval'	: 50,			// number = milliseconds delay for doing
     						'over'		: function(){	// required
							
								me.insetHover(item, jInset);
							
     							/*// clear current from insets
								jItemInsets.removeClass('current');	
								// clear current from color rows
								me.clrColorImage(item, false);
								if (!src) {return;} // jic
								jInset.addClass('current');
								me.changeImage(item, src, href);*/
								
     						} 
						});
						
					});
	
					/*// init image using first inset
					if (!hasMultiOptions) {
						jItemInsets.eq(0)
							.find('.item-inset-link')
								.trigger('mouseover');
					}*/

				} // end if jItemImage
				
				// setup multi options
				if (hasMultiOptions) {
					me.setupMultiOptions(item);
				}

				// init personalization
				if (hasPersonalization) {
					jColorRows.find('.custom-cell select')
						.trigger('change');
					jCustomRows
						.find('.item-option-custom-item.custom-text')
							.find('.value .custom-monogram-style')
								.trigger('change');
				}
	
				// init using quantity
				jColorRows.find('.quantity-cell input[type=text]')
					.trigger('keyup');
					
				// init custom fit sizes
				jColorRows.find('.combo-size-cell select')
					.trigger('change');
				
				// init image
				me.insetHover(item, jItemInsets.eq(0));
				/*if (jItemImage) {
					jItemInsets.eq(0)
						.find('.item-inset-link')
							.trigger('mouseover');
				}*/
								
			}); // end each item container

			// setup multi option form submit
			// or setup quantity for simple item
			
			if (me.settings.hasMultiOptions) {

				// setup multi options			
				me.setupMultiAddFormSubmit();
				
			} else {

				// setup single quantity
				$('#item-quantity input[type=text]')
					.keyup(function(){
						var val = $(this).val();
						me.killMessage();
						if (val) {
							val = parseInt(val, 10);
							if (isNaN(val)) {
								$(this).val('0');
							}
						}
						me.updateTotalPrice();
					})
					.blur(function(){
						var val = parseInt($(this).val(), 10);
						if (isNaN(val)) {
							$(this).val('0');
						}
					});
					
				// init using quantity
				$('#item-quantity input[type=text]')
					.trigger('keyup');
				
			}

		} // end is ITEM PAGE
						
	}, // end start()

	//---------------------------------------------------------------------------------------------
	'reviewsLimit' : function () {
	
		var	me = this,
			jReviewsContainer		=	$('.pr-contents'),
			reviewsControlsHtml		=	'<div class="reviews-controls">' +
										'<a href="#" class="show">show more reviews</a>' +
										'<a href="#" class="hide" style="display: none;">show less reviews</a>' +
										'</div>';
										
		// each set of reviews, usually only one set
		jReviewsContainer.each(function(){

			var	jControls,
				jReviews		= $('.pr-review-wrap'),
				jReviewsNav		= $('.pr-pagination-top'),
				jReviewsCount	= jReviewsNav.find('.pr-page-count strong');
		
			// continue if not more than one review
			if (!(jReviews.size() > 1)) {return;}
			
			// continue if no nav
			if (!(jReviewsNav.size() == 1)) {return;}
			
			// add show/hide controls
			if (jReviewsNav.find('.pr-clear').size() > 0) {
				jReviewsNav
					.find('.pr-clear')
						.before(reviewsControlsHtml);
			} else {
				jReviewsNav
					.append(reviewsControlsHtml)
			}
			
			// save numbers text
			if (jReviewsCount.size() > 0) {
				jReviewsCount.data('text', jReviewsCount.text());
			}
			
			// show reviews
			jReviewsNav.find('.reviews-controls .show').click(function(){
				$(this).hide();
				jReviewsCount.text('');
				jReviews
					.not(':first')
						.slideDown(500, function(){
							jReviewsNav
								.find('.reviews-controls .hide')
									.show();
							jReviewsCount.text(jReviewsCount.data('text'));
						});
				return false;
			});
			
			// hide reviews
			jReviewsNav.find('.reviews-controls .hide').click(function(){
				$(this).hide();
				jReviewsCount.text('');
				jReviews
					.not(':first')
						.slideUp(500, function(){
							jReviewsNav
								.find('.reviews-controls .show')
									.show();
							jReviewsCount.text(jReviewsCount.data('text').replace('-', ' of '));
					});
				return false;
			});

			// init
			jReviewsNav.find('.reviews-controls .hide').trigger('click');
			
		});
										
	},

	//---------------------------------------------------------------------------------------------
	'insetHover' : function (item, jInset) {
		var me = this,
			jInsetLink		= jInset.find('.item-inset-link'),
			src				= jInsetLink.attr('href'),
			href			= jInsetLink.metadata().enlargedImageRef; // is set in RTML
		// clear current from insets
		item.jInsets.removeClass('current');	
		// clear current from color rows
		me.clrColorImage(item, false);
		if (!src) {return;} // jic
		jInset.addClass('current');
		me.changeImage(item, src, href);	
	
	},
	
	//---------------------------------------------------------------------------------------------
	'showMessage' : function (msg) {
		var	me = this, i, msgstr;
		if (msg) {
			msgstr = '';
			for (i=0;i<msg.length;i++) {
				if (i > 0) {
					msgstr = msgstr + '<br />';
				}
				msgstr = msgstr + msg[i];
			}
			me.settings.jAddtocartMessage
				.find('.message')
					.css('display','none')
					.end()
				.find('.message.default')
					.css('display','inline')
					.html(msgstr)
					.end()
				.css({'opacity':1})
				.slideDown(200);
			me.settings.timer = setTimeout(	function(){me.fadeMessage()},
											me.settings.messageHoldTime);
		}
	},
	
	//---------------------------------------------------------------------------------------------
	'killMessage' : function () {
		var me = this;
		clearTimeout(me.settings.timer);
		$(me.settings.addtcartMessageSel)
			.slideUp(300);
	},

	//---------------------------------------------------------------------------------------------
	'fadeMessage' : function () {
		var me = this;
		me.settings.jAddtocartMessage
			.animate({'opacity': 0}, me.settings.messageFadeTime,
				function() {
					me.killMessage();
				});
	},


	/*//'setupSimpleFormSubmit'
					// simple item
				if (!me.settings.hasMultiOptions) {
					if (me.getQuantity() > 0) {
						foundAnyQty = true;
					}
				}*/


	
	//---------------------------------------------------------------------------------------------
	'setupMultiAddFormSubmit' : function () {
	
		var  me = this;
	
		// form submit
		$('.addtocart-form').submit(function(){

			var	msg						= [],
				msgIndex				= 0,
				qtyHasSize				= true,
				foundAnyQty				= false,
				foundAnySize			= false,
				monogramTextLetters		= 0,
				embroideryNeedsText		= false,
				customFitSizeIsSelected = false;
				
			me.killMessage();
					
			// check each item container for size and qty selections
		
			me.settings.jItemContainers.each(function(){

				var	jItemContainer	= $(this),
					jColorRows		= jItemContainer.find('.color-row');

				// each color row
				jColorRows.each(function(){
					var	jColorRow		= $(this),
						jCustomRow		= jColorRow.next('.custom-row'),
						jCustom			= jCustomRow.find('.item-option-custom'),
						kind			= me.getKind(jColorRow),
						hasQty			= false,
						hasSize			= false,
						quantity, size, baseItemId, colorCode, val, txt, jTextInput, jSize,
						parts, itemcode, upc, jInput;
						
					// check quantity
					quantity = jColorRow.find('.quantity-cell input[type=text]').val();
					quantity = parseInt(quantity, 10);
					if (!isNaN(quantity) && (quantity > 0)) {
						foundAnyQty = true;
						hasQty = true;
					}

					if (me.settings.isCustomFitPage) {
						
						jSize = jColorRow.find('.combo-size-cell select');
						
						if (jSize.val() != jSize.find('option:first').val()) {
							customFitSizeIsSelected = true; 
						}
				
					} else {
				
						jSize		= jColorRow.find('.size-cell select');
						size		= jSize.val();
						itemcode	= jSize.find('option:selected').data('itemcode');
						upc			= jSize.find('option:selected').data('upc');
						//hasSize		= !(size == me.settings.sizeNotSelectedValue);
						hasSize		= jSize.val() != jSize.find('option:first').val();
												
						// itemcode
						jInput = jColorRow.find('.item-code-value');
						if (itemcode) {
							jInput
								.attr('name', jInput.metadata().name)
								.val(itemcode);
						} else {
							jInput.removeAttr('name');
						}
						
						// upc
						jInput = jColorRow.find('.upc-value');
						if (upc) {
							jInput
								.attr('name', jInput.metadata().name)
								.val(upc);
						} else {
							jInput.removeAttr('name');
						}

						if (!hasSize && hasQty) {
							// has quantity but no size selected
							qtyHasSize = false;
							jColorRow.find('.size-cell select').addClass('error');
						}
						/*} else if (hasSize) {
							// size selected so make and set item code
							baseItemId = jColorRow.find('.quantity-cell input').filter('.base-item-id').val();
							//colorCode = jColorRow.find('.quantity-cell .color-code').val();
							colorCode = me.getColorCode(jColorRow);
							jColorRow.find('.item-code-value')
								.val((baseItemId +'-'+ colorCode +'-'+ size).toUpperCase());
						}*/
		
						// embroidery
						if (me.getKind(jColorRow) == 'embroidery' && hasQty) {
							// get embroidery text input
							jTextInput = jCustom
											.find('.item-option-custom-item.custom-text')
												.find('.value input.custom-text')
													.filter(me.makeKindSel('embroidery'));
							// get embroidery text
							txt = jTextInput.val();
							if (!(txt.length > 0)) {
								embroideryNeedsText = true;
								jTextInput.addClass('error');
							}
						}
	
						// monogram
						// get monogram text input
						jTextInput = jCustom
										.find('.item-option-custom-item.custom-text')
											.find('.value input.custom-text')
												.filter(me.makeKindSel('monogram'));
						
						if (me.getKind(jColorRow) == 'monogram') {
							if (hasQty) {
								// get monogram style
								val = jCustom
										.find('.item-option-custom-item.custom-text')
											.find('.value .custom-monogram-style')
												.val();
								val = val.split(',');
								// get monogram text
								txt = jTextInput.val();
								// validate monogram text
								if (txt.length != val[1]) {
									monogramTextLetters = val[1];
									jTextInput.addClass('error');
								} else {
									// ok, so set name attr
									jTextInput
										.attr('name', val[0]);	
								}
							}
						} else {
							jTextInput
								.removeAttr('name');
						}

					} // end if isCustomFile
					
				}); // end each color row

			}); // end each item container
			
			// get msg
			if (!foundAnyQty) {
				msg[msgIndex] = 'Please enter a quantity.';
				msgIndex++;
			}
			
			if (me.settings.isCustomFitPage) {
				if (!customFitSizeIsSelected) {
					msg[msgIndex] = 'Please select a size.';
					msgIndex++;
				}
			} else {
				if (!qtyHasSize) {
					msg[msgIndex] = 'Please select a size.';
					msgIndex++;
				}
				if (embroideryNeedsText) {
					msg[msgIndex] = 'Enter text for Embroidery.';
					msgIndex++;
				}
				if (monogramTextLetters > 0) {
					msg[msgIndex] = 'Enter ' + monogramTextLetters + ' letter(s) for Monogram.';
					//msgIndex++;
				}
			}
			
			// show msg
			if (msg.length > 0) {
				me.showMessage(msg);
				return false;
			}
			
			// else ok
			return true;
			
		}); // end form submit

	},

	//---------------------------------------------------------------------------------------------
	'getOptionPrice' : function (optionText) {
		var diff;
		if (typeof optionText != 'string') {return 0;}
		diff = optionText.match(/\((.*)\)/);
		if (diff) {
			diff = diff[1];
			diff = diff.replace('\$', '');
			diff = parseFloat(diff);
			diff = isNaN(diff) ? 0 : diff;	
		} else {
			diff = 0;
		}
		return diff;
	},

	//---------------------------------------------------------------------------------------------
	'removeOptionPrice' : function (optionText) {
		return optionText.replace(/\([\+|\-](.*)\)/, '');
	},
		
	//---------------------------------------------------------------------------------------------
	'formatCurrency' : function (priceAmount) {
		var price;
		if (isNaN(priceAmount)) {return '';}
		price = new Number(priceAmount);
		return '$' + price.toFixed(2);
	},
		
	//---------------------------------------------------------------------------------------------
	'getQuantity' : function (jColorRow) {
		var me = this, val;
		if (jColorRow) {
			val = jColorRow.find('.quantity-cell input[type=text]').val();
		} else {
			val = me.settings.jItemContainers.eq(0)
					.find('#item-quantity input[type=text]')
						.val();
		}
		val = val * 1;
		val = isNaN(val) ? 0 : val;
		return val;
	},

	//---------------------------------------------------------------------------------------------
	'getBasePrice' : function (jItemContainer) {
		//var val = jItemContainer.data('baseprice');
		var val = jItemContainer.find('.item-base-price').val();
		val = val * 1;
		val = isNaN(val) ? 0 : val;
		return val;
	},

	//---------------------------------------------------------------------------------------------
	'hasMultiOptions' : function (jItemContainer) {
		if (jItemContainer) {
			return jItemContainer.find('.item-multi-options-table').size() > 0;
		}
		// else
		return false;
	},

	//---------------------------------------------------------------------------------------------
	'getKind' : function (jColorRow) {
		var	kind,
			val = jColorRow.find('.custom-cell select').val();
			if (jColorRow.hasClass('embroidery')) {
				kind = 'embroidery';
			} else if (jColorRow.hasClass('monogram')) {
				kind = 'monogram';
			} else {
				kind = null;
			}
		return kind;
	},

	//---------------------------------------------------------------------------------------------
	'makeKindSel' : function (kind) {
		if (kind) {
			return '.' + kind;
		} else {
			return null;
		}
	},

	//---------------------------------------------------------------------------------------------
	'getColorCode' : function (jColorRow) {
		//return jColorRow.metadata().colorCode;
		return jColorRow.find('.quantity-cell .color-code').val();
	},

	//---------------------------------------------------------------------------------------------
	'updateTotalPrice' : function () {
		var	me				= this,
			totalquantity	= 0,
			totalprice		= 0,
			totaldiffprice	= 0,
			qty;
			
		// get it
		// each item container
		me.settings.jItemContainers.each(function(){
			var jItemContainer	= $(this),
				jColorRows		= jItemContainer.find('.color-row'),
				baseprice		= me.getBasePrice(jItemContainer),
				hasMultiOptions	= me.hasMultiOptions(jItemContainer);
			if (baseprice) {
				if (hasMultiOptions) {
					// each color row
					jColorRows.each(function(i){
						var	jColorRow		= $(this),
							qty				= me.getQuantity(jColorRow);
							val				= jColorRow.find('.custom-cell select').val(),
							diffprice		= me.getOptionPrice(val);
						// add this row's diff price and quantity
						totaldiffprice	= totaldiffprice + (diffprice * qty);
						totalquantity	= totalquantity + qty;
					});	
					// calc total price
					totalprice = (baseprice * totalquantity) + totaldiffprice;
				} else {				
					qty = me.getQuantity();
					totalprice = baseprice * qty;
				}
			}
		});

		// set it
		$('#item-price-total span')
			.css('opacity', 1)
			.animate(
				{'opacity' : 0},
				me.settings.totalPriceTransitionTime / 2,
				function(){ // animation complete
					$(this)
						.text(me.formatCurrency(totalprice))
						.animate(
							{'opacity' : 1},
							me.settings.totalPriceTransitionTime / 2);
				});
	},

	//---------------------------------------------------------------------------------------------
	'changeImage' : function (item, src, href) {

		var me = this,
			isFirstTime = item.jImage.data('isFirstTime');

		// no href
		if (!href) {href = '';}
		
		// if no src then use first inset or saved main image
		if (!src) {
			if (item.jInsets.size() > 0) {
				item.jInsets.eq(0)
					.find('.item-inset-link')
						.trigger('mouseover');
				return;
			} else {
				src		= item.jImage.data('src');
				href	= item.jImage.data('href');
			}
		}

		// change the image if different
		if ((item.jImage.attr('src') != src) || isFirstTime) {

			// disable magnify
			me.ableMagnify(item, false);
			
			item.jImage
				.css('opacity', 1)
				.animate(
					{'opacity': 0},
					me.settings.mainImageTransitionTime,
					function(){ // hide animation complete
						if (href) {
							item.jImageLink.attr('href', href);
							item.jContainer
								.find('.item-image-controls .item-magnify')
									.show();
						} else {
							item.jImageLink.removeAttr('href');
							item.jContainer
								.find('.item-image-controls .item-magnify')
									.hide();
						}
						$(this)
							.css('opacity', 0)
							.attr('src', src)
							.animate(
								{'opacity': 1},
								me.settings.mainImageTransitionTime,
								function(){
									// enable magnify
									if (href) {
										me.ableMagnify(item, true);
									}
								} // show animation complete
							);
					}
				);
				
		} // end change image

		item.jImage.data('isFirstTime', false);
		
	}, // end changeImage()

	//---------------------------------------------------------------------------------------------
	'ableMagnify' : function (item, enable) {
	
		var	me = this,
			isLeft =		item.jContainer.hasClass('bottoms')
						||	item.jContainer.hasClass('bottom')
						||	item.jContainer.hasClass('right');

		if (me.settings.isSeparatesPage) {return;}
						
		if (enable) {
			item.jContainer.find('.item-image-magnify').show();
			//item.jImageLink.magnify();
			item.jImageLink.magnify({
				'position'		: (isLeft ? 'left' : 'right'),
				'adjustX'		: (isLeft ? -13 : 7),
				'adjustY'		: 0,
				'stageWidth'	: 370,
				'stageHeight'	: 370,
				//'fadeTime'	: 300,
				'tint'			: '#707090',
				'tintOpacity'	: 0.6,
        		'lensOpacity'	: 1,
        		'softFocus'		: false,
				'smoothMove'	: 3
				//'wrapperClass'	: 'item-image',
			});
		} else {
			item.jContainer.find('.item-image-magnify').hide();
			item.jImageLink.magnify('remove');
		}
	},

	//---------------------------------------------------------------------------------------------
	/*	cell classes :	color-name-cell
						color-swatch-cell
						quantity-cell
						size-cell
						custom-cell
	*/
	'setupMultiOptions' : function (item) {
	
		var	me = this;

		/*// check for IMG in custom text
		if (!(item.jCustomText.find('img').size() > 0)) {
			me.settings.jCustomText.append('<img />');
		}*/
		
		// each color row
		item.jColorRows.each(function(){
		
			var	preload1		= new Image(25,25),
				preload2		= new Image(25,25),
				jColorRow		= $(this),
				jCustomRow		= jColorRow.next('.custom-row'),
				jCustom			= jCustomRow.find('.item-option-custom');
			
			// size codes
			jColorRow.find('.size-cell select option').each(function(){
				var parts = $(this).val();
				parts = parts.split('|');
				// size
				$(this).val($.trim(parts[0]));
				// itemcode
				if (parts.length > 1) {
					$(this).data('itemcode', $.trim(parts[1]));
				}
				// upc
				if (parts.length > 2) {
					$(this).data('upc', $.trim(parts[2]));
				}
			});

			// size
			jColorRow.find('.size-cell select').change(function(){
				me.killMessage();
				if ($(this).val() != me.settings.sizeNotSelectedValue) {
					$(this).removeClass('error');
				}
			});
						
			// custom fit combo size
			jColorRow.find('.combo-size-cell select').change(function(){
				me.killMessage();
				if ($(this).val() != me.settings.sizeNotSelectedValue) {
					$(this).removeClass('error');
				}
				me.updateCustomFitSize(item, $(this));
			});
		
			// swatch click
			jColorRow.find('.item-swatch-image-link').click(function(){
				//me.setColorDesc(item, jColorRow);
				me.setColorImage(item, jColorRow);
				return false; // no default click
			});

			// preload color images
			preload1.src = jColorRow.find('.item-swatch-image-link').attr('href');
			preload2.src = jColorRow.find('.item-swatch-image-link').attr('rel');

			// quantity
			jColorRow.find('.quantity-cell input[type=text]')
				.keyup(function(){
					var val = $(this).val();
					me.killMessage();
					$(this).removeClass('error');
					if (val) {
						val = parseInt(val, 10);
						if (isNaN(val)) {
							$(this).val('0');
						}
					}
					me.updateTotalPrice();
				})
				.blur(function(){
					var val = parseInt($(this).val(), 10);
					if (isNaN(val)) {
						$(this).val('0');
					}
				});

			// setup all kind elements
			jCustom.find('.embroidery,.monogram').each(function(){
				// save name attr value to data
				$(this).data('name', $(this).attr('name'));
			});

			/*// set height of all item rows so they don't collapse during hide/show
			jCustom.find('.item-option-custom-item').each(function(){
				// save name attr value to data
				$(this).css('height', $(this).width() + 'px');
			});*/
				
			// font
			jCustom.find('.item-option-custom-item.font .value select').change(function(){
				me.updateCustomText(item, jColorRow);
			});

			// thread color
			jCustom.find('.item-option-custom-item.thread-color .value select').change(function(){
				me.updateCustomText(item, jColorRow);
			});

			// custom text
			jCustom
				.find('.item-option-custom-item.custom-text')
					.find('.value input.custom-text')
						.keyup(function(){
							var	len,
								val = $(this).val();
							if ($(this).hasClass('embroidery')) {
								if (val.length > 0) {
									$(this).removeClass('error');
								}
							}
							if ($(this).hasClass('monogram')) {
								val = val.toUpperCase();
								$(this).val(val);
								len = jCustom
										.find('.item-option-custom-item.custom-text')
											.find('.value .custom-monogram-style')
												.val();
								if (len) { // jic
									len = len.split(',')[1];
									if (val.length == len) {
										$(this).removeClass('error');
									}
								}
							}
							me.updateCustomText(item, jColorRow, val);
							me.killMessage();
						});

			// monogram style
			jCustom
				.find('.item-option-custom-item.custom-text')
					.find('.value .custom-monogram-style')
						.change(function(){
							var val	= $(this).val(),
								jInputText = jCustom
												.find('.item-option-custom-item.custom-text')
													.find('.value input.custom-text')
														.filter(me.makeKindSel('monogram'));
							if (val) { // jic
								val = val.split(',');
								jInputText
									.attr('maxlength', val[1]);
								if (jInputText.val().length > val[1]) {
									jInputText.val('');
								}
								me.updateCustomText(item, jColorRow);
							}
						});

			// preview button
			jCustom.find('.item-option-custom-preview-button').click(function(){
				me.setColorImage(item, jColorRow);
				return false; // no default click
			});
			
			// kind
			jColorRow.find('.custom-cell select').change(function(){
				var	kind,
					val = $(this).val();
				if (val.indexOf('embroidery') != -1) {
					kind = 'embroidery';
				} else if (val.indexOf('monogram') != -1) {
					kind = 'monogram';
				} else {
					kind = null;
				}
				me.changeCustomKind(kind, jColorRow, item);
				me.updateTotalPrice();
			});

			// hide all kind elements
			me.ableKindElements(jCustom);

		}); // end each color row

	}, // end setupMultiOptions()

	//---------------------------------------------------------------------------------------------
	'setColorDesc' : function (item, jColorRow) {
		var	me = this,
			colorCode, colorName,
			jColorDesc = item.jContainer.find(me.settings.colorDescSel);
			
		if (jColorRow) {
			colorCode = me.getColorCode(jColorRow);
			colorName = jColorRow.find('.color-name-cell').text();
			jColorDesc
				.data('colorName', colorName)
				.data('colorCode', colorCode)
				.hide(me.settings.mainImageTransitionTime,
					function(){ // hide is complete
						$(this)
							.text(colorName +' ('+ colorCode +')')
							.show(me.settings.mainImageTransitionTime,
								function(){}); // show is complete
					});
		} else {
			jColorDesc
				.hide()
				.text('')
				.data('colorCode', '')
				.data('colorName', '');
		}
	},

	//---------------------------------------------------------------------------------------------
	'clrColorImage' : function (item, useDefaultImage) {
		var me = this;
		// clear and hide color desc
		me.setColorDesc(item);
		// clear and hide custom text
		me.updateCustomText(item);
		// clear current from color rows
		item.jColorRows.removeClass('current');
		item.jCustomRows.removeClass('current');
		// change main image to default
		if (useDefaultImage) {
			me.changeImage(item);
		}
	},

	//---------------------------------------------------------------------------------------------
	// set main image as a preview of this color
	// called by: swatch click, preview button, changeCustomKind (when hiding custom row)
	/*	IF jColorRow:
			clear other preview buttons
			set this row as current
			set main image
			set color desc
			set custom text
			set insets as not current
		IF NOT jColorRow:
			clear color desc
			clear custom text
			default main image
	*/
	'setColorImage' : function (item, jColorRow) {

		var	me = this;

		// no preview
		if (!jColorRow) {
			// clear and hide color desc and custom text
			// make color rows not current
			// change main image to default
			me.clrColorImage(item, true);
			return;
		}

		var src, href, 
			jCustomRow			= jColorRow.next('.custom-row'),
			jCustom				= jCustomRow.find('.item-option-custom');
			
		// exit if main image is this color
		if (me.isRowCurrent(item, jColorRow)) {return;}

		// here: clear other preview buttons

		// set this row as current
		item.jColorRows.removeClass('current');
		item.jCustomRows.removeClass('current');
		jColorRow.addClass('current');
		jCustomRow.addClass('current');
		
		// clear insets, they are now not current
		item.jInsets.removeClass('current');

		// set main image using this color row
		src		= jColorRow.find('.item-swatch-image-link').attr('rel');
		href	= jColorRow.find('.item-swatch-image-link').attr('href');
		if (src) { // jic
			me.changeImage(item, src, href);
		}

		// set color desc
		me.setColorDesc(item, jColorRow);

		// for personalization
		if (item.hasPersonalization) {
			// update custom text for this color
			me.updateCustomText(item, jColorRow);
		}
				
	},

	//---------------------------------------------------------------------------------------------
	// update custom text
	// if no custom text input then use existing text
	// if no jColorRow or no kind then hide
	'updateCustomText' : function (item, jColorRow, customText) {

		var	me = this,
			kind, val, url, metadata, rad, cos, sin,
			boxheight, boxwidth, boxangle, fontheight,
			jCustomRow, jCustom,
			jCustomText 	= item.jCustomText
			jImage			= item.jImage,
			monogramformat	= null,
			bgurl			= null,
			alignment		= 'c';

		if (jColorRow) {
			kind = me.getKind(jColorRow);
		}
		
		// hide and exit
		// check jImageImg jic
		if (!jColorRow || !kind || !(jImage.size() > 0)) { 
			jCustomText
				.hide()
				.find('img')
					.removeAttr('src');
			return;
		}

		// get custom row and custom container
		jCustomRow	= jColorRow.next('.custom-row');
		jCustom		= jCustomRow.find('.item-option-custom');
		metadata	= jColorRow.metadata();
				
		// exit if main image is not this color
		if (!me.isRowCurrent(item, jColorRow)) {
			return;
		}
		
		// get color image specific dims
		alignment	= 'c';
		boxtop		= metadata[kind + 'Top'];
		boxleft		= metadata[kind + 'Left'];
		boxheight	= metadata[kind + 'Height'];
		boxwidth	= metadata[kind + 'Width'];
		boxangle	= metadata[kind + 'Angle'];
		if (typeof boxangle == 'string') {
			boxangle = boxangle * 1;
		}
		fontsize	= boxheight;
		
		// get selected monogram format
		if (kind == 'monogram') {
			monogramformat = jCustom
								.find('.item-option-custom-item.custom-text')
									.find('.value .custom-monogram-style')
										.val();
			if (monogramformat.toLowerCase().indexOf('3 letters plus') != -1) {
				monogramformat = 'b';
			} else {
				monogramformat = null;
			}
		}
		
		// MAKE IMAGE URL

		// text image program url
		url = me.settings.textImageProgramUrl;

		// text
		if (typeof customText != 'string') {
			// get old text
			customText = jCustom
							.find('.item-option-custom-item.custom-text')
								.find('.value input.custom-text')
									 .filter(me.makeKindSel(kind))
										.val();
			if (typeof customText != 'string') {
				customText = '';
			}
		}
		url += '?t=' + escape(customText);

		// font face
		val =	jCustom	
					.find('.item-option-custom-item.font .value select.'+ kind)
						.val()
		url += '&f=' +	val;

		// thread color
		val =	jCustom
					.find('.item-option-custom-item.thread-color .value select.'+ kind)
						.val();
		val = typeof val === 'string' ? me.settings.colorNameValue[val] : '#e9e9e9';		
		url += '&c=' + escape(val);

		// using the height to determine font size
		/*// font size
		url += '&s=' + fontsize;*/

		/*// angle
		if (!isNaN(boxangle)) {
			url += '&a=' + boxangle;
		}*/

		if (!boxtop || !boxleft) {
			boxtop = 30;
			boxleft = 10;
			boxheight = 30;
			boxwidth = 200;
			alignment = null;
			bgurl = jColorRow
						.find('.item-swatch-image-link')
							.metadata().largeSwatchUrl;		
		}
		
		// set top in css
		jCustomText
			.css('top', boxtop + 'px');

		// set left in css
		jCustomText
			.css('left', boxleft + 'px');

		// height
		url += '&h=' + boxheight;

		// width
		url += '&w=' + boxwidth;

		// monogram format
		if (monogramformat) {
			url += '&m=' + monogramformat;
		}

		// alignment centered.
		// centered creates an image that's always boxwidth wide.
		// this is necessary to keep image in same position independent of text length.
		if (alignment) {
			url += '&n=' +	alignment;
		}
		
		// set angle in css, else remove properties
		if (!isNaN(boxangle)) {
		
			//alert('< IE9: '+ me.settings.isLessThanIE9);
		
		/*.rotate {
		  -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.86602540, M12=0.50000000, M21=-0.50000000, M22=0.86602540,sizingMethod='auto expand')";
		  filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.86602540, M12=0.50000000, M21=-0.50000000, M22=0.86602540,sizingMethod='auto expand');
		  -moz-transform:  matrix(0.86602540, -0.50000000, 0.50000000, 0.86602540, 0, 0);
		  -webkit-transform:  matrix(0.86602540, -0.50000000, 0.50000000, 0.86602540, 0, 0);
		  -o-transform:  matrix(0.86602540, -0.50000000, 0.50000000, 0.86602540, 0, 0);
		}*/

		
			if (me.settings.isLessThanIE9) {
				//rad = (boxangle * Math.PI) / 180.0,
				rad = boxangle * Math.PI * 2 / 360.0,
				cos = Math.cos(rad),
				sin = Math.sin(rad);
				val =	'progid:DXImageTransform.Microsoft.Matrix(sizingMethod = "auto expand", '
						+ 'M11 = ' + cos + ', M12 = ' + (-sin) + ', M21 = ' + sin + ', M22 = ' + cos + ')';
						
				//alert(val);
						
				jCustomText
					.css({'-ms-filter' : val, 'filter' : val});
			} else {
				val = 'rotate('+ boxangle +'deg)';
				jCustomText
					.css({	'-moz-transform'		: val,
							'-o-transform'			: val,
							'-opera-transform'		: val,
							'-webkit-transform'		: val,
							'-khtml-transform'		: val,
							'-ms-transform'			: val,
							'transform'				: val});
			}
			
		} else {

			val = null;
			jCustomText
				.css({	'-moz-transform'		: val,
						'-o-transform'			: val,
						'-opera-transform'		: val,
						'-webkit-transform'		: val,
						'-khtml-transform'		: val,
						'-ms-transform'			: val,
						'transform'				: val,
						'filter'				: val});

		} // end set angle in css
			
		// set img url
		jCustomText
			//.addClass('loading');
			.find('img')
				.attr('src', url);
				/*.onload(function(){
					jCustomText.removeClass('loading');
				});*/

		if (bgurl) {
			val = "url('"+ bgurl +"') no-repeat 50% 50%";
			jCustomText.addClass('default');
		} else {
			val = 'transparent';
			jCustomText.removeClass('default');
		}
		jCustomText.css('background', val);
				
		// show
		jCustomText.show(200);
		
		/*// show color image if not current
		if (!me.isRowCurrent(item, jColorRow)) {
			me.setColorImage(item, jColorRow);
		}*/
		
	},

	//---------------------------------------------------------------------------------------------
	// is this row the current color of the main image
	'isRowCurrent' : function (item, jColorRow) {
		var me = this,
			jColorDesc		= item.jContainer.find(me.settings.colorDescSel),
			valRow			= me.getColorCode(jColorRow)		// row color value
			valCurrent		= jColorDesc.data('colorCode');		// preview color code
		return valRow == valCurrent;
	},

	//---------------------------------------------------------------------------------------------
	'ableKindElements' : function (jCustom, kind) {
		var me = this;
		// hide	all kind
		jCustom.find('.embroidery,.monogram').each(function(){
			$(this).hide(me.settings.mainImageTransitionTime);
			$(this).removeAttr('name');
		});
		// show kind
		if (kind) {
			jCustom.find(me.makeKindSel(kind)).each(function(){
				$(this).attr('name', $(this).data('name'));
				$(this).show(me.settings.mainImageTransitionTime);
			});
		}
	},

	//---------------------------------------------------------------------------------------------
	// change custom row to embroidery or monogram, or hide the row
	// called by color row kind SELECT
	/*
		show/hide custom row
		show/hide custom row controls
		set/clear color desc
		set/hide custom text
	*/
	'changeCustomKind' : function (kind, jColorRow, item) {

		var	me				= this,
			kindSel			= me.makeKindSel(kind),
			kindWas			= me.getKind(jColorRow),
			kindWasSel		= me.makeKindSel(kindWas),
			jCustomRow		= jColorRow.next('.custom-row'),
			jCustom			= jCustomRow.find('.item-option-custom');
			//jPreviewButton	= jCustom.find('.preview-button'),

		// hide previous kind
		if (kindWas) {
			jColorRow		.removeClass(kindWas);
			jCustomRow		.removeClass(kindWas);
			jCustom			.removeClass(kindWas);
			me.ableKindElements(jCustom);
			me.updateCustomText(item);
		}
	
		if (!kind) {												// no kind, so hide and exit

			// slideup active custom
			jCustom
				.slideUp(300, function(){							// done animation
					var classNames = 'custom-active current embroidery monogram';
					// remove classes
					jColorRow.removeClass(classNames);		
					jCustomRow.removeClass(classNames);		
					jCustom.removeClass(classNames);		
				});
			// clear color image, color desc, custom text
			me.setColorImage(item);
	
			return;

		} else if (kind !== kindWas) {								// else show selected kind

			// add classes
			jColorRow
				.addClass('custom-active')
				.addClass(kind);
			jCustomRow
				.addClass('custom-active')
				.addClass(kind);
			jCustom
				.addClass('custom-active')
				.addClass(kind);
				
			// show kind objects
			me.ableKindElements(jCustom, kind);

			// show custom
			jCustom.slideDown(300);
			
			// update preview text if this is the current color
			if (me.isRowCurrent(item, jColorRow)) {
				jCustom
					.find('.item-option-custom-item.custom-text')
						.find('.value input.custom-text')
							.filter(kindSel)
								.trigger('keyup');			
			}
			
		}
	},

	//---------------------------------------------------------------------------------------------
	'updateCustomFitSize' : function (item, jSize) {
	
		var	val,
			data = jSize.find('option:selected').metadata(),
			jColorSizes = item.jContainer.find('.item-multi-options .color-size-option');

		// set the size SELECT of each color to the value of the main size SELECT
		jColorSizes.val(jSize.val());
	
		// dimensions
		if (data && (typeof data.dims != 'undefined')) {
			for (var i=0;i<data.dims.length;i++) {
				//val = data.dims[i][1] || '-';
				if (typeof data.dims[i] != 'undefined') {
					if (typeof data.dims[i][1] == 'string') {
						val = data.dims[i][1];
					} else {
						val = '-';
					}
					$('#' + data.dims[i][0]).text(val);
				}
			}
		} else {
			// clear all dimensions
			item.jContainer
				.find('.tbitem-dimensions-container td.value span')
					.text('-');
		}
		
	},

	//---------------------------------------------------------------------------------------------
	'equalHeightContentsImages' : function () {
		// each table row
		$('#contents-table tr').each(function(){
			var	h = 0,
			jCellImageContainers = $(this).find('td .image');
			// each table cell
			jCellImageContainers.each(function(){
				h = Math.max(h, $(this).height());
			});
			// set height of all
			jCellImageContainers.css('height', h + 'px');
		});	
	}

};		

//-------------------------------------------------------------------------------------------------
$(function(){ // doc ready
	mysite.start();
});

