var a = {
	userFirstName:'',
	isTouch:0,
	shopOn:1,
	init:function(){
		$(window).bind('hashchange',function(e){ a.nav.onHashChange(); });
		
		a.isTouch = ($('#istouch').val() === '1')?true:false;
		
		a.ui.anim.setup();
		a.ui.touch.init();
		$(window).load(function(){
			//setTimeout(function(){ a.ui.anim.showHeader(); },250);
			//setTimeout(function(){ a.ui.anim.showBody(); },500);
			//setTimeout(function(){ a.ui.anim.showFooter(); },750);
			$(window).trigger('hashchange');
		});
		
		a.facebook.init();
		
		// initial logged in state for js
		if ($('.sm-links .user .firstname').html() !== '') {
			$(document.body).addClass('-is-logged-in');
			a.userFirstName = $('.sm-links .user .firstname').html();
		}
		
		// a.deals.init();
		a.slides.init();
		a.form.init();
		a.ui.menu.init();
		a.weblist.init();
		a.bag.init();
		a.product.init();
		a.products.init();
		a.login.init();
		a.search.init();
		a.brand.init();
		
		jc.form.init(document.body,a.form.onFieldError,a.form.onFieldSuccess);
	},
	nav:{
		currentHash:null,
		currentLocation:null,
		bgLocation:null,
		history:[],
		onHashChange:function(){
			
			// we need to make sure that the checkout process takes place in an https version of the site
			if (a.nav.manageSSL()) { return; }			
			
			var hash = window.location.hash.substr(window.location.hash.indexOf('#')+1),
				hashParams = '';
				
			// ---- BUG because of how dialogs mimic the back button when you close them -----
			// try to detect whether they've clicked the back button
			// and they're about to pull up a divalog... if so, skip 
			// the divalog but click 'back' again
			/*if (a.nav.history.length > 0) {
				if (window.location.href === a.nav.history[2].h) {
					alert('bug fix');
					history.go(-1);
				}
			}*/
			
			a.nav.logHistory();
			
			// analytics
			if (typeof _gaq !== 'undefined') {
				_gaq.push(['_trackPageview','/index.cfm'+window.location.hash]);
			}
			
			if (window.location.hash.indexOf('?') > -1) {
				hash = window.location.hash.substr(window.location.hash.indexOf('#')+1,window.location.hash.indexOf('?')-1);
				hashParams = window.location.hash.substr(window.location.hash.indexOf('?')+1,window.location.hash.length);
			}
			
			if (hash === '') { hash = 'home'; }
			var params = $.deparam.fragment(hashParams);
			
			// close a custom function (if it exists AND if your not openning the same hash again)
			if (typeof a.nav.custom[a.nav.currentHash] !== 'undefined' && hash !== a.nav.currentHash) {
				a.nav.custom[a.nav.currentHash].close(params, hash, a.nav.currentHash);
			}
			
			// open home in teh background by default
			/*if (a.nav.currentHash === null) {
				//a.nav.goTo('home',{});
			}*/
			
			scroll(0,0);
			
			// hide preview windows for price alert, bag, wishlist
			a.weblist.hideAll();
			
			// open a custom function (login, etc)
			if (typeof a.nav.custom[hash] !== 'undefined') {
				if (hash === a.nav.currentHash) {
					a.nav.custom[hash].reopen(params, hash, a.nav.currentHash);
				} else {
					a.nav.custom[hash].open(params, hash, a.nav.currentHash);
				}
					
				a.nav.bgLocation = a.nav.currentLocation;
				a.nav.currentHash = hash;
				a.nav.currentLocation = String(window.location.toString());
				
			// open a background page
			} else if (a.nav.bgLocation === String(window.location.toString())) {
				a.nav.bgLocation = null;
				a.nav.currentHash = hash;
				a.nav.currentLocation = String(window.location.toString());
				
			// content from cfm (normal nav use)
			} else {
				a.nav.goTo(hash,params);
			}
		},
		goTo:function(page,params){
			if (typeof params !== 'object') { params = {}; }
			
			a.ui.menu.toggleMenu('');
			a.ui.anim.showLoading();
			a.ui.anim.hideBody(function(){
				$('.body').html('');
				$('.body').load('/cf/'+page+'.cfm',params,function(){
					$('.pList').css({display:'none'});
					$('.body').css({display:'block'});
					a.ui.anim.hideLoading();
					a.ui.anim.showBody();
				});
			});
			a.nav.currentHash = page;
			a.nav.currentLocation = String(window.location.toString());
			a.nav.bgLocation = null;
		},
		custom:{
			login:{
				isDiv:1,
				open:function(params){ a.login.open(); },
				reopen:function(params){ },
				close:function(params,hash){ a.ui.divalog.close($('#divalog_login')); }
			},
			/*forgot:{
				open:function(params){ a.forgot.open(); },
				reopen:function(params){ },
				close:function(params,hash){ a.ui.divalog.close($('#divalog_forgot')); }
			},*/
			signup:{
				isDiv:1,
				open:function(params){ a.signup.open(params); },
				reopen:function(params){ },
				close:function(params,hash){ a.ui.divalog.close($('#divalog_signup')); }
			},
			feedback:{
				isDiv:1,
				open:function(params,newHash,oldHash){ a.feedback.open(params,newHash,oldHash); },
				reopen:function(params,newHash,oldHash){ },
				close:function(params,hash){ a.ui.divalog.close($('#divalog_feedback')); }
			},
			availability:{
				isDiv:1,
				open:function(params,newHash,oldHash){ a.availability.open(params,newHash,oldHash); },
				reopen:function(params,newHash,oldHash){ },
				close:function(params,hash){ a.ui.divalog.close($('#divalog_availability')); }
			},
			herbrands:{
				isDiv:1,
				open:function(params,newHash,oldHash){ a.brand.show('her'); },
				reopen:function(params,newHash,oldHash){ },
				close:function(params,hash){ a.ui.divalog.close($('#divalog_brands')); }
			},
			hisbrands:{
				isDiv:1,
				open:function(params,newHash,oldHash){ a.brand.show('his'); },
				reopen:function(params,newHash,oldHash){ },
				close:function(params,hash){ a.ui.divalog.close($('#divalog_brands')); }
			},
			product:{
				isDiv:0,
				open:function(params,newHash,oldHash){ a.product.open(params,newHash,oldHash); },
				reopen:function(params,newHash,oldHash){ a.product.open(params,newHash,oldHash); },
				close:function(params,hash){ a.product.close(params,hash); }
			},
			products:{
				isDiv:0,
				open:function(params,newHash,oldHash){ a.products.open(params,newHash,oldHash); },
				reopen:function(params,newHash,oldHash){ a.products.open(params,newHash,oldHash); },
				close:function(params,hash){ a.products.close(params,hash); }
			}
		},
		logHistory:function(){
			a.nav.history.push({d:new Date(),h:window.location.href});
			// console.log(a.nav.history.slice(0));
		},
		back:function(){
						
			var goToUrl = '';
			
			// if there is no history to work w/, use browser back function
			if (a.nav.history.length <= 1) {
				//console.log(a.nav.history);
				history.go(-1);	
				
			// if we have history to work with
			// not truly a back button - you're going forward to a page you were just at
			} else {
				// take the last item, pop it off (because that's the page we're CURRENTLY on)
				a.nav.history.pop();
				
				// the new last item in the array is now the page we want to go back to... store it
				goToUrl = a.nav.history[a.nav.history.length-1].h+'';
				
				// remove the item we're going to as it will get relogged into the history
				a.nav.history.pop();

				// go to url
				window.location = goToUrl;
			}
			
			//console.log(window.history.previous);
			//console.log(window.history.next);
			//history.go(-1);	
			/*
			// not truly a back button - you're going forward to a page you were just at
			var history = a.nav.history.slice(0).reverse(); // copy of the array, reversed
			history.shift(); // kills the first element in the array (our current URL)
			
			// loop through and find the next history item that is NOT an dialog
			$.each(history,function(i,e){
				console.log(e.h);
			});
			*/
			/*if (a.nav.history.length > 1) {
				var previousUrl = a.nav.history[a.nav.history.length-2].h;
				
				if () {
					
				}
				
				window.location = a.nav.history[a.nav.history.length-2].h;
			} else {
				history.go(-1);	
			}*/
		},
		manageSSL:function(){
			var loc = window.location,
				url = loc.href,
				isssl = (loc.protocol === 'https:');
			
			// force ssl
			if (!isssl && url.indexOf('#checkout') > -1) {
				window.location.href = loc.href.replace('http:','https:');
				return true;
				
			// otherwise force non-ssl (except for login and signup dialogs which are accessed through checkout screen)
			} else if (isssl && url.indexOf('#checkout') === -1 && url.indexOf('#login') === -1 && url.indexOf('#signup') === -1) {
				window.location.href = loc.href.replace('https:','http:');
				return true;
			}
			
			return false;
		}
	},
	ui:{
		touch:{
			init:function(){
				if (!$.browser.webkit) { return; }
				$("#mainPane").swipe({
					swipeLeft:function(){ a.products.mainPane.next(); },
					swipeRight:function(){ a.products.mainPane.previous(); },
					threshold:20
				});
			}
		},
		divalog:{
			open:function(str,fn,close){
				var dlg = $(str);
				dlg.fadeIn(150,function(){ if (typeof fn === 'function') { fn(); } });
				if (close === 1) {
					dlg.find('.dlg-x').unbind('click').click(function(){
						if (a.checkout.isComplete === true) { window.location = 'http://www.shopwarrens.com'; }// hack for after checkout
						a.ui.divalog.close(dlg);
					});
				} else {
					dlg.find('.dlg-x').unbind('click').click(function(){
						a.nav.back();
						// history.go(-1); <-- behaves strangely in IE and FF
					});
				}
				return $(str);
			},
			close:function(e){
				var d = $(e).closest('.dlg');
				d.fadeOut(200);
			}
		},
		menu:{
			init:function(){
				var cats = $('#hisher-cats');
				
				// his menu selection
				$('#his').click(function(){
					a.ui.menu.toggleMenu('his');
					$('#her, #his').unbind('mouseover').unbind('mouseout');
					$('.srch').removeClass('wasHis wasHer').addClass('wasHis');
				}).mouseover(function(){
					if (a.isTouch) { return false; }
					$(this).parent().addClass('his').removeClass('her');
				}).mouseout(function(){
					if (a.isTouch) { return false; }
					$(this).parent().removeClass('his');
				});
				
				// her menu selection
				$('#her').click(function(){
					a.ui.menu.toggleMenu('her');
					$('#her, #his').unbind('mouseover').unbind('mouseout');
					$('.srch').removeClass('wasHis wasHer').addClass('wasHer');
				}).mouseover(function(){
					if (a.isTouch) { return false; }
					$(this).parent().addClass('her').removeClass('his');
				}).mouseout(function(){
					if (a.isTouch) { return false; }
					$(this).parent().removeClass('her');
				});
				
				// identify each main categories drop menu
				$('.mnu .cats li').not('.noDrop').each(function(i,e){
					var d = $('#'+$(e).attr('id')+'_drop');
					d.data({mainLI:$(e)});
					$(e).data({dropDIV:$(d)});
				});
				
				// mouse over for bg effect
				$('.mnu .cats li').mouseover(function(ev){ $(this).addClass('over'); }).mouseout(function(ev){ $(this).removeClass('over'); });
				
				// click to see menu
				$('.mnu .cats li').not('.noDrop').click(function(){
					a.ui.menu.toggleCatMenu(this);
					$(this).siblings().removeClass('over');
				});
				
				// hide menu when you click an option
				$('.dMnu li').click(function(ev){ $(this).parents('.drp').slideUp(100); });
				
				// when you click an item in the dropdown menus, make the category menu item active
				$('.dMnu .drp li').click(function(ev){ $('#hisher-cats li').removeClass('on'); $(this).parents('.drp').data().mainLI.addClass('on'); });
				 
				/*if (a.isTouch) { 
					$('.mnu .cats li').not('.noDrop').click(function(){ a.ui.menu.toggleCatMenu(this); $(this).siblings().removeClass('over'); }); //.click(function(){ a.ui.menu.toggleCatMenu(this); })
				} else {
					$('.mnu .cats li').mouseover(function(ev){ $(this).addClass('over'); }).mouseout(function(ev){ $(this).removeClass('over'); });
					$('.mnu .cats li').not('.noDrop').mouseover(function(){ a.ui.menu.toggleCatMenu(this); }); //.click(function(){ a.ui.menu.toggleCatMenu(this); })
				}*/
				
				//$('.mnu .cats li').click(function(ev){ $(this).addClass('on').siblings('li').removeClass('on'); });
				
				
				// hide menus if you click anywhere else on the screen
				//if (a.isTouch) {
					$(document).click(function(ev){
						if ($(ev.target).parents('.mnu').length === 0 && $(ev.target).parents('.dMnu').length === 0) {
							$('.dMnu .drp').slideUp(100).removeClass('active');
						}
					});
				//}
			},
			toggleMenu:function(type){
				var hh = $('#hisher'),
					cats = $('#hisher-cats');
					
				if (type === 'his') {
					hh.removeClass('her');
					hh.addClass('his');
					cats.animate({'top':'-44px'});
				} else if (type === 'her') {
					hh.removeClass('his');
					hh.addClass('her');
					cats.animate({'top':'-84px'});
				} else if (type === '') {
					hh.removeClass('her his');
					cats.animate({'top':'0px'});
				}
			},
			toggleCatMenu:function(li){
				var d = $(li).data().dropDIV,
					l2 = 0;
				//$('.mnu li.active').removeClass('active');
				
				$(li).addClass('over');
				d.siblings().css({'z-index':1}).slideUp(100);
				l2 = $(li).position().left+188;
				l2 = (l2 > 880)?880:l2;
				d.css({'left':l2,'z-index':2});
				d.slideDown(300);
				
				if (!a.isTouch) {
					// drop down actions
					d.unbind('mouseout').unbind('mouseover').mouseout(function(ev){
						var d = $(this).data(),
							el = $(this);
						if (typeof d.timer !== 'undefined') {
							clearTimeout(d.timer);
						}
						timer = setTimeout(function(){ el.slideUp(100); $(li).removeClass('over'); },1500);
						$(this).data('timer',timer);
					}).mouseover(function(){
						var d = $(this).data();
						if (typeof d.timer !== 'undefined') {
							clearTimeout(d.timer);
						}
					});
					
					// li actions
					$(li).unbind('mouseout').mouseout(function(ev){
						var drp = $('#'+$(this).attr('id')+'_drop'),
							d = drp.data(),
							el = $(this);
						if (typeof d.timer !== 'undefined') {
							clearTimeout(d.timer);
						}
						timer = setTimeout(function(){
							drp.slideUp(100);
							el.removeClass('over');
							// normal mouse out function
							el.unbind('mouseout').mouseout(function(ev){ $(this).removeClass('over'); });
						},1500);
						drp.data('timer',timer);
					});
				}
			}
		},
		tooltip:{
			init:function(e){
				$.each($(e).find('.tip'),function(i,f){
					var tip = $(f).find('.tipText').html();
					$(f).mouseover(function(){ a.ui.tooltip.show(tip); });
					$(f).mouseout(function(){ a.ui.tooltip.hide(); });
				});
			},
			show:function(html, e){
				var tt = $('<div class="productTip"><div class="box"><div class="txt">'+html+'</div></div><div class="point"></div></div>');
				$(document.body).append(tt);
				$(document).mousemove(function(e){ tt.css({display:'block',left:e.pageX+'px',top:e.pageY+'px'}); });
			},
			hide:function(){
				$('.productTip').remove();
			}
		},
		anim:{
			setup:function(){
				//$('.a').css({display:'none'});
				$('.b').css({height:'40px',display:'block'});
				//$('.c').css({width:'1px',display:'none'});
			},
			showHeader:function(){
				//$('.a').fadeIn(500);
			},
			showBody:function(){
				$('.b').css({display:'block'});
				$('.b').animate({height:'535px'},500,'easeOutCubic');
			},
			hideBody:function(fn){
				$('.b').css({display:'block'});
				$('.b').animate({height:'40px'},500,'easeOutCubic',function(){ if (typeof fn === 'function') { fn(); } });
			},
			showFooter:function(){
				/*$('.c .fade').css({display:'none'});
				$('.c').css({display:'block'});
				$('.c').animate({width:'980px'},500,'easeOutCubic',function(){
					$.each($('.c .fade'),function(i,e){
						setTimeout(function(){ $(e).fadeIn(250); },(250*i));
					});
				});*/
			},
			showLoading:function(){
				$('.loading').slideDown(500);
			},
			hideLoading:function(){
				$('.loading').slideUp(100);
			}
		}
	},
	facebook:{
		init:function(){
			window.fbAsyncInit = function() { FB.init({appId:$('#fb-appid').html(), status:true, cookie:true, xfbml:true}); };
			(function() {
				var e = document.createElement('script');
				e.id = '-fb-script';
				e.type = 'text/javascript';
				e.src = document.location.protocol+'//connect.facebook.net/en_US/all.js';
				e.async = true;
				document.getElementById('fb-root').appendChild(e);
			}());
		},
		publish:function(headline,desc,img){
			FB.ui({
				method: 'stream.publish',
				message: 'Warren\'s has the stuff I want!',
				display:'popup',
				attachment: {
					name: headline,
					caption: desc,
					description: 'ROCKIN\' the sweet looks at Warren\'s. The BEST BRANDS, the BEST PRICES and the BEST STAFF!',
					href: window.location.href,
					user_prompt_message: 'Share your thoughts about ShopWarrens.com',
					media:[{type:'image', src:img, href:window.location.href}]
				}
			},
			function(response) {
			});	
		}
	},
	form:{
		init:function(){
			$.each($('input.hint'),function(i,e){
				$(e).val($(e).attr('alt'));
			});
			$('input.hint').focus(function(){
				if ($.trim($(this).val()) === $(this).attr('alt')) { $(this).removeClass('hint'); $(this).val(''); }
			});
			$('input.hint').blur(function(){
				if ($.trim($(this).val()) === '') { $(this).addClass('hint'); $(this).val($(this).attr('alt')); }
			});
		},
		onFieldError:function(e,msg){
			$(e).addClass('error');
			// error message div
			var msgDiv = $(e).data('hintError');
			if (msgDiv === null) {
				msgDiv = $('<div />').addClass('hint-error');
				if ($(e).attr('type') === 'checkbox' || $(e).attr('type') === 'radio') {
					$(e).siblings('.label').append(msgDiv);
				} else {
					$(e).after(msgDiv);
				}
				$(e).data('hintError',msgDiv);
			}
			
			if (typeof msgDiv !== 'undefined') {
				msgDiv.html(msg);
			}
		},
		onFieldSuccess:function(e){
			$(e).removeClass('error');
			var msgDiv = $(e).data('hintError');
			if (msgDiv !== null) { 
				$(msgDiv).remove();
				$(e).removeData('hintError');
			}
		}
	},
	products:{
		zIndex:1,
		init:function(p){
			a.products.sidePane.init();
			a.products.mainPane.init();
		},
		open:function(params, newHash, oldHash){
			if ($('.pList').data().hash === window.location.href) {
				$('.pList').animate({top:'0px'});
			} else {
				a.ui.anim.hideBody();
				a.ui.anim.showLoading();
				a.products.load(params);
			}
			$('.pDetail').css({top:'-496px'});
		},
		close:function(p,newHash){
			if (newHash === 'product') {
				$('.pList').animate({top:'500px'});
			} else if (newHash !== 'feedback' && newHash !== 'login' && newHash !== 'forgot' && newHash !== 'signup' && newHash !== 'herbrands' && newHash !== 'hisbrands' && newHash !== 'availability') {
				$('.mnu li.active').removeClass('active');
				a.products.mainPane.pd.find('.product').remove(); // clear all product
				a.products.mainPane.pd.css({left:'0px'}); // reset page position
				a.products.mainPane.pr.css({height:'1px',display:'block'}); // hide promo image
				$('.mainPane .message').css({opacity:0,display:'none'}); // hide message
				$('.pList').css({display:'block',top:'500px'}).data({'hash':''});
				$('.body').css({display:'block',top:'0px'});
			}
		},
		load:function(p){
			if (typeof p.c !== 'undefined') {
				var catLI = $('.cat_'+p.c).parents('.drp'),
					isDeal = 0,
					isNew = 0,
					mainLI = (catLI.length > 0)?catLI.data().mainLI:[],
					isHer = (mainLI.length > 0)?(mainLI.parents('ul.her').length > 0):0,
					isHis = (mainLI.length > 0)?(mainLI.parents('ul.his').length > 0):0;
				
				if (typeof p.n !== 'undefined') {
					if (p.n === '1') {
						isNew = 1;
					}
				} else if (typeof p.d !== 'undefined') {
					if (p.d === '1') {
						isDeal = 1;
					}
				}
				
				// set top menu properly
				if (isHer) {
					$('#her').click();
				} else if (isHis) {
					$('#his').click();
				}
				
				if (isNew) {
					if (isHis) { mainLI = $('#cat_himnew'); }
					else if (isHer) { mainLI = $('#cat_hernew'); }
					else { mainLI = []; }
				} else if (isDeal) {
					if (isHis) { mainLI = $('#cat_himclearance'); }
					else if (isHer) { mainLI = $('#cat_herclearance'); }
					else { mainLI = []; }
				} 
				
				if (mainLI.length > 0) {
					$('#hisher-cats li').removeClass('on over');
					mainLI.addClass('on');	
				}
			} else if (typeof p.q !== 'undefined') {
				$('#hisher-cats li').removeClass('on over');
				if (p.q.indexOf('his') > -1) { $('#his').click(); }
				else if (p.q.indexOf('her') > -1) { $('#her').click(); }
			}

			// load results
			$.post('/cf/ajax/product.list.cfm',p,function(r){
				a.products.sidePane.update(r.f,r.c,r.p.length);
				a.products.mainPane.update(r.p,r.c);
				a.products.onFilterChange();
				$('.pList').css({display:'block',top:'0px'}).data({'hash':window.location.href});
				$('.body').css({display:'none'});
				a.ui.anim.showBody();
				a.ui.anim.hideLoading();
			},'json');
		},
		onFilterChange:function(){
			a.products.mainPane.applyFilter(a.products.sidePane.collectFilterData());
		},
		showPreview:function(el,d){
			var brand = null,
				price = null,
				details = null,
				pos = el.position();
			
			a.products.hideAllPreviews();
			prev = $('<div />').addClass('pvw').append(
					$('<div />').addClass('bg')
				).append(
					$('<div />').addClass('thb').append(
						$('<img />').attr({src:'/images/pPreview.shadowTop.png',width:'130',height:'6'})
					).append(
						$('<div />').addClass('picHolder').append(
							$('<img />').addClass('pic').attr({src:'//img.shopwarrens.com/product/130x173/'+d.pi,width:'155',height:'206',alt:d.b+' '+d.n+' ('+d.s+')'})
						)
					).append(
						$('<img />').attr({src:'/images/pPreview.shadowBottom.png',width:'130',height:'6'})
					)
				).append(
					$('<div />').addClass('brd')
				).append(
					$('<div />').addClass('dtl').append(
						$('<div />').addClass('nm').html(d.n)
					).append(
						$('<div />').addClass('sk').html(d.s)
					).append(
						$('<div />').addClass('pr')
					)
				);
			
			// higher res image
			prev.find('.picHolder').append($('<img />').addClass('pic').attr({src:'//img.shopwarrens.com/product/250x333/'+d.pi,width:'155',height:'206'}));
			
			// brand name vs logo
			brand = prev.find('.brd');
			if (d.bi === '') {
				brand.append(d.b);
			} else {
				brand.append(
					$('<img />').attr({src:'//img.shopwarrens.com/brand/'+d.bi,height:'13'})
				);
			}
			
			// price 
			price = prev.find('.pr');
			if (d.d === 1) {
				price.append(
					$('<span />').addClass('old').html(d.op)
				).append(
					$('<span />').addClass('new').html(d.sp+' CDN')
				);
			} else {
				price.html(d.sp+' CDN');	
			}
			
			if ($(el).hasClass('bottom')) {
				prev.offset({top:pos.top-130});
			} else if ($(el).hasClass('top')) {
				prev.offset({top:pos.top-10});
			} else {
				prev.offset({top:pos.top-50});
			}
			
			if ($(el).hasClass('left')) {
				prev.offset({left:pos.left-2});
			} else if ($(el).hasClass('right')) {
				prev.offset({left:pos.left-33});
			} else {
				prev.offset({left:pos.left-17});
			}
			
			$(el).parent().append(prev);
			$(el).data({preview:prev});
			prev.mouseout(function(){ a.products.hideAllPreviews(); }); 
			prev.click(function(){ window.location = '#product?i='+d.i+'&s='+d.t; }); 
			prev.css({display:'block'});
		},
		hidePreview:function(el){
			var prev = $(el).data().preview;
			if ($(prev).length !== 0) {
				//$(prev).css({display:'none'});
				$(prev).remove();
				$(el).removeData('preview');
			}
		},
		hideAllPreviews:function(el){
			$('.pvw').remove();
		},
		mainPane:{
			page:0,
			pages:0,
			ispaging:0,
			pd:null,
			pr:null,
			init:function(){
				a.products.mainPane.pd = $('.products');
				a.products.mainPane.pr = a.products.mainPane.pd.find('.promo');
				$('.arrows .left').click(function(){ a.products.mainPane.previous(); });
				$('.arrows .right').click(function(){ a.products.mainPane.next(); });
			},
			update:function(p,c){
				// clear exising products
				a.products.mainPane.pd.find('.product').remove();
				// display new product
				$.each(p,function(i,e){
					var el = $('<div />').addClass('product').addClass(e._c);
					el.append($('<div />').addClass('productid hidden').html(e.i));
					//el.append($('<div />').addClass('photoBg'));
					el.append($('<div />').addClass('photo').append($('<img />').attr({'src':'//img.shopwarrens.com/product/130x173/'+e.pi,'alt':e.n+' '+e.b})));
					a.products.mainPane.pd.append(el);
					el.click(function(){ window.location = '#product?i='+e.i+'&s='+e.t; /*if (a.isTouch) { a.products.showPreview($(this),e); } else { window.location = '#product?i='+e.i+'&s='+e.t; }*/ });
					el.mouseover(function(){ if (a.isTouch) { return false; } a.products.showPreview($(this),e); });
					//el.mouseout(function(){ a.products.hidePreview($(this),e); });
				});
				// display category image
				if (a.products.mainPane.pr.length === 0) {
					a.products.mainPane.pr = $('<div />').addClass('promo').appendTo(a.products.mainPane.pd);
				}
				if (c.i !== '') {
					a.products.mainPane.pr.removeClass('-noImg');
					a.products.mainPane.pr.css({'background-image':'url("'+c.i+'")'});
				} else {
					a.products.mainPane.pr.addClass('-noImg');
					a.products.mainPane.pr.css({'background-image':'none'});
				}
				a.products.mainPane.animateToShow($('.mainPane .product'));
			},
			applyFilter:function(f){
				var p_all = $('.mainPane .product'),
					p_is = [],
					p_isnot = [],
					opts = [
						{name:'brandids',prefix:'-b_'},
						{name:'colorids',prefix:'-c_'},
						{name:'priceids',prefix:'-p_'},
						{name:'sizeids',prefix:'-z_'},
						{name:'lengthids',prefix:'-l_'}
					],
					x;
				
				p_is = p_all;
				
				// filter down tags by group
				$.each(f.attributeids,function(i,e){
					x = [];
					$.each(e,function(j,e2){
						x.push('.-a_'+e2);
					});
					if (x.length > 0) {
						p_is = p_is.filter(x.join(', '));
					}
				});
				
				// filter down brands, colors, price
				$.each(opts,function(i,e){
					x = [];
					$.each(f[e.name],function(j,e2){
						x.push('.'+e.prefix+e2);
					});
					if (x.length > 0) {
						p_is = p_is.filter(x.join(', '));
					}
				});
				
				p_isnot = p_all.not(p_is);
				
				a.products.mainPane.animateToShow(p_is,(p_isnot.length > 0));
				a.products.mainPane.animateToHide(p_isnot);
				
				if (p_is.length === 0) {
					$('.mainPane .message').css({display:'block',opacity:0}).animate({opacity:1.0});
				} else if ($('.mainPane .message').css('display') === 'block') {
					$('.mainPane .message').animate({opacity:0},function(){ $(this).css({display:'none'}); });
				}
				
				a.products.mainPane.configUiElements();
			},
			configUiElements:function(){
				var i;
				
				if (a.products.mainPane.isPaging) {
					$('.paging .page').remove();
					
					for (i=0; i<a.products.mainPane.pages; i++) {
						$('.paging').append($('<div class="page" />'));
					}
					$.each($('.paging .page'),function(j,e){
						$(e).click(function(){ a.products.mainPane.go(j+1); });
					});
					var x1 = ((808-($('.paging .page').outerWidth()*a.products.mainPane.pages))/2)-2;
					$('.paging').css({left:x1+'px'});
					$('.arrows').css({display:'block'});
					$('.paging').css({display:'block'});
				} else {
					$('.arrows').css({display:'none'});
					$('.paging').css({display:'none'});
				}
				a.products.mainPane.go(1);
			},
			go:function(i) {
				var l = 0;
				
				if (typeof i !== 'undefined') { a.products.mainPane.page = i; }
				if (a.products.mainPane.page > a.products.mainPane.pages) { a.products.mainPane.page = 1; }
				if (a.products.mainPane.page < 1) { a.products.mainPane.page = a.products.mainPane.pages; }
				
				l = -(980*(a.products.mainPane.page-1));
				a.products.mainPane.pd.animate({left:l+'px'},650,'easeInOutQuint');
				a.products.mainPane.updatePageIndicator();
			},
			next:function() {
				a.products.mainPane.page++;
				a.products.mainPane.go();
			},
			previous:function() {
				a.products.mainPane.page--;
				a.products.mainPane.go();
			},
			updatePageIndicator:function() {
				var l = 16*(a.products.mainPane.page-1);
				$('.pageIndicator').animate({left:l+'px'},500,'easeInOutQuint');
			},
			animateToShow:function(els,isSomeHidden){
				var rows = 3,
					cols = 7,
					perPage = null,
					p = 0,
					prodWidth = 98,
					prodHeight = 130,
					padX = 10,
					padY = 10,
					offsetTop = 0,
					offsetLeft = 18,
					paneW = 980,
					paneH = (prodHeight*rows)+(padY*rows),
					showCatImg = (!isSomeHidden && !a.products.mainPane.pr.hasClass('-noImg') && $(els).length > 0),
					promoImgShowing = !$('.products .promo').hasClass('-noImg');
					
				a.products.hideAllPreviews();
				perPage = rows*cols;				
				a.products.mainPane.pages = (promoImgShowing)?Math.ceil(($(els).length+6)/perPage):Math.ceil($(els).length/perPage);
				a.products.mainPane.isPaging = (a.products.mainPane.pages > 1);
				a.products.mainPane.page = 1;
				
				if (!showCatImg) {
					a.products.mainPane.pr.css({height:'1px',display:'none'});
				} else {
					setTimeout(function() { 
						a.products.mainPane.pr.css({height:'1px',display:'block'});
						a.products.mainPane.pr.animate({height:'270px'},200,'easeInOutQuint');
					},300);
				}
				
				$.each($(els),function(i,e){
					var lo = 0,
						to = 0,
						l = 0,
						t = 0;

					// special paging to fit per cat image
					// i dictates the position of each product
					// if we're showing the category promo image,
					// manipulate i accordingly to leave space
					if (showCatImg) {
						if (i >= 0) { i += 3; }
						if (i >= 7) { i += 3; }
					}
					
					p = Math.ceil((i+1)/perPage);
					lo = offsetLeft+(paneW*(p-1));
					to = offsetTop+(-paneH*(p-1));
					l = lo+((i%cols)*(prodWidth+padX));
					t = to+((Math.ceil((i+1)/cols)-1)*(prodHeight+padY));
					
					$(e).css({display:'block'});
					$(e).animate({opacity:1.0,top:t+'px',left:l+'px'},500,'easeInOutQuint');
					
					// update clases for the product preview box to use (see preview js code, NOT CSS)
					if (t > 200) { $(e).addClass('bottom'); } else { $(e).removeClass('bottom'); }
					if (t < 10) { $(e).addClass('top'); } else { $(e).removeClass('top'); }
					if (i === 0 || i % 7 === 0) { $(e).addClass('left'); } else { $(e).removeClass('left'); }
					if (i === 6 || i % 7 === 6) { $(e).addClass('right'); } else { $(e).removeClass('right'); }
				});
			},
			animateToHide:function(els){
				$(els).css({display:'none',opacity:0,top:'0px',left:'0px'});
				/*$.each($(els),function(i,e){
					$(e).animate({opacity:0},100,function(){ $(this).css({opacity:0,top:'0px',left:'0px'}); });
				});*/
			}
		},
		sidePane:{
			filterTimer:null,
			filterLatency:1,
			domEl:null,
			init:function(){
				a.products.sidePane.domEl = $('.sidePane');
				$(document).click(function(ev){
					if ($(ev.target).closest('.options').length > 0) { return; }
					a.products.sidePane._closeAllBubbles();
				});
			},
			update:function(f,c,n){
				var ul = $('.sidePane .options > ul');
				ul.find('li').remove();
				
				$('.sidePane .heading .new, .sidePane .heading .clearance').remove();
				$('.sidePane .heading .p1').html(c.s); //.html(c.s+': '+c.c2);
				$('.sidePane .heading .p2').html(c.c1);
				$('.sidePane .heading').removeClass('new clearance');
				if (c.n === 1) {
					$('.sidePane .heading .p1').html($('.sidePane .heading .p1').html()+' NEW'); //.html(c.s+': '+c.c2);
					$('.sidePane .heading').addClass('new');
				} else if (c.d === 1) {
					$('.sidePane .heading .p1').html($('.sidePane .heading .p1').html()+' CLEARANCE'); //.html(c.s+': '+c.c2);
					$('.sidePane .heading').addClass('clearance');
				}
				
				if (n === 0) {
					$('.sidePane .inr .filterActions').css({display:'none'});
					return;
				} else {
					$('.sidePane .inr .filterActions').css({display:'block'});
				}
				
				$.each(f,function(i,e){
					if (e.o.length === 0) { return; }
					
					var el = $('<li />'),
						ul_opts = $('<ul />');
						
					if (!isNaN(e.id)) { el.addClass('-tag'); }
					
					$.each(e.o,function(j,g){
						var x = $('<input />').attr({type:'hidden',value:g.i});
						if (e.t === 1) {
							x.addClass('AttributeID');
						} else {
							if (e.n === 'Brand') { x.addClass('BrandID'); }
							else if (e.n === 'Color') { x.addClass('ColorID'); }
							else if (e.n === 'Price') { x.addClass('PriceID'); }
							else if (e.n === 'Size' || e.n === 'Waist') { x.addClass('SizeID'); }
							else if (e.n === 'Length') { x.addClass('LengthID'); }
						}
						ul_opts.append($('<li />').html(g.n).append(x));
					});
					
					el.append(
						$('<span />').addClass('li').html(e.n)
					).append(
						$('<ul />').addClass('selectedOptions')
					).append(
						$('<div />').addClass('mr').css({overflow:'visible'}).append(
							$('<div />').addClass('mr2').append(
								$('<div />').addClass('mr3').append(
									$('<table />').append(
										$('<tr />').append(
											$('<td />').append(ul_opts)
										)
									)				
								)
							)
						).append(
							$('<div />').addClass('close')
						).append(
							$('<div />').addClass('tip')
						)
					);
					ul.append(el);
				});
				
				if ($('.sidePane .inr .filterActions').length === 0) {
					$('.sidePane .inr').append(
						$('<div />').addClass('filterActions').append(
							$('<button />').html('Reset').click(function(){ a.products.sidePane.resetFilter(); })
						)/*.append(
							$('<button />').html('Save').click(function(){ alert('Phase 2 - Allow people to save their filters.\n\nWe would also need to add a new menu item (beside price alerts?) to list their saved filters.  We should brand it with something like "My Style"'); })
						)*/
					);
				}
				a.products.sidePane.applyFns();
			},
			resetFilter:function(){
				$('.sidePane ul.selectedOptions li.checked').remove();
				$('.sidePane .mr3 li.checked').removeClass('checked');
				$('.sidePane ul.selectedOptions').css({display:'none'});
				a.products.onFilterChange();
			},
			collectFilterData:function(){
				var o = {
					attributeids:[],
					colorids:[],
					brandids:[],
					priceids:[],
					sizeids:[],
					lengthids:[]
				};
				$('.selectedOptions').each(function(i,e){
					var x = [];
					$(e).find('.checked .AttributeID').each(function(i2,e2){
						x.push(parseInt($(e2).val(),10));
					});
					if (x.length > 0) { o.attributeids.push(x); }
				});
				$('.selectedOptions .checked .BrandID').each(function(i,e){ o.brandids.push(parseInt($(e).val(),10)); });
				$('.selectedOptions .checked .ColorID').each(function(i,e){ o.colorids.push(parseInt($(e).val(),10)); });
				$('.selectedOptions .checked .PriceID').each(function(i,e){ o.priceids.push($(e).val()); });
				$('.selectedOptions .checked .SizeID').each(function(i,e){ o.sizeids.push($(e).val()); });
				$('.selectedOptions .checked .LengthID').each(function(i,e){ o.lengthids.push($(e).val()); });
				return o;
			},
			applyFns:function(){
				var ul = a.products.sidePane.domEl.find('.options > ul'),
					showmenu = function(){
						var mr = $(this).siblings('.mr');
						if (mr.hasClass('showing')) { return; }
						if ($.browser.msie) {
							mr.css({display:'block'});
						} else {
							mr.css({opacity:0,'margin-left':'-20px',display:'block'}).animate({opacity:1.0,'margin-left':'0px'},250);
						}
						a.products.sidePane._closeAllBubbles();
						mr.addClass('showing');
					};
				
				ul.find('li:not(.-config) .li').click(showmenu);
				ul.find('li:not(.-config) .mr li').each(function(i,li){
					li = $(li);
					li.click(function(){
						li.toggleClass('checked');
						isChecked = li.hasClass('checked');
						attrID = li.find('input').val();
						selectedList = $(this).parents('.mr').siblings('.selectedOptions');
						selectedList_li = selectedList.find("li input[value="+attrID+"]").parent();
						
						if (isChecked && selectedList_li.length === 0) {
							newLi = li.clone();
							selectedList.append(newLi);
							newLi.click(function(){
								$(this).toggleClass('checked');
								a.products.sidePane._resetFilterTimer();
								li.toggleClass('checked');
								var self = $(this);
								if (!self.hasClass('checked')) {
									setTimeout(function(){ 
										self.slideUp(function(){
											self.remove(); 
											if (selectedList.find('li').length === 0) {
												selectedList.css({display:'none'});	
											} else {
												selectedList.css({display:'block'});	
											}
										}); 
									},100);
								}
							});
							
						} else if (!isChecked && selectedList_li.length > 0) {
							selectedList_li.remove();
						}
						
						if (selectedList.find('li').length === 0) {
							selectedList.css({display:'none'});	
						} else {
							selectedList.css({display:'block'});	
						}
						
						a.products.sidePane._resetFilterTimer();
					});
				});
				ul.find('li:not(.-config) .mr .close').click(a.products.sidePane._closeAllBubbles);
				ul.find('li:not(.-config) .mr').unbind('mouseout').unbind('mouseover').mouseout(function(ev){
					var d = $(this).data(),
						el = $(this);
					if (typeof d.timer !== 'undefined') {
						clearTimeout(d.timer);
					}
					timer = setTimeout(function(){ a.products.sidePane._closeAllBubbles(); },250);
					$(this).data('timer',timer);
				}).mouseover(function(){
					var d = $(this).data();
					if (typeof d.timer !== 'undefined') {
						clearTimeout(d.timer);
					}
				});
				
				ul.find('li:not(.-config)').addClass('-config');
			},
			show:function(){
				
			},
			hide:function(){
				
			},
			_closeAllBubbles:function(){
				if ($.browser.msie) {
					$('.mr.showing').css({display:'none'}).removeClass('showing');
				} else {
					$('.mr.showing').animate({opacity:0,'margin-left':'-20px'},250,function(){ $(this).css({display:'none'}).removeClass('showing'); });
				}
				a.products.sidePane.collectFilterData();
			},
			_resetFilterTimer:function(){
				if (a.products.sidePane.filterTimer !== null) {
					clearTimeout(a.products.sidePane.filterTimer);
					a.products.sidePane.filterTimer = null;
				}
				a.products.sidePane.filterTimer = setTimeout(a.products.onFilterChange,a.products.sidePane.filterLatency);
			}
		}
	},
	product:{
		el:null,
		ui:{}, // getUI();
		init:function(){
			a.product.el = $('.pDetail');
			a.product.el.css({top:'-500px'});
		},
		open:function(params,newHash,oldHash){
			var ui = a.product.getUI(),
				sizeid = '';
			$('.pList').animate({top:'500px'});
			if ($('.pDetail').data().hash === window.location.href) {
				a.product.el.animate({top:'0px'});
				$('#social').fadeIn();
			} else {
				if (a.product.el.position().top === 0) {
					a.product.disappear();
				} else {
					a.ui.anim.showBody();
					ui.loading.css({display:'block',opacity:1,'margin-top':'0px'});
					ui.col1.css({display:'none'});
					ui.col2.css({display:'none'});
					$('.content .body').animate({top:'500px'});
					//$('.content .pList').animate({top:'500px'});
					a.product.el.css({top:'-500px'}).animate({top:'0px'});
				}
				sizeid = (typeof params.z === 'undefined')?'':params.z;
				a.product.load(params.i,params.s,sizeid);
			}
		},
		load:function(productid,styleid,sizeid){
			if (typeof sizeid === 'undefined') { sizeid = ''; }
			$.post('/cf/ajax/product.get.cfm',{i:productid,s:styleid,z:sizeid},function(j){
				$('.pDetail').data({'hash':window.location.href});
				a.product.populateUI(j);
				a.product.applyUIFunctions();
				a.product.appear();
			},'json');
		},
		getUI:function(){
			var o = {},
				p = a.product.el;
			
			if (p.children().length === 0) {
				p.append(
					$('<div />').addClass('loadAnimation')
				).append(
					$('<div />').addClass('col1').append(
						$('<div />').addClass('photo').append(
							$('<div />').addClass('img')
						).append(
							$('<div />').addClass('zoom')
						)
					).append(
						$('<div />').addClass('thumbs').append(
							$('<div />').addClass('mask').append(
								$('<div />').addClass('list')
							)
						).append(
							$('<div />').addClass('button up disabled')
						).append(
							$('<div />').addClass('button down disabled')
						)
					).append(
						$('<div />').addClass('close')
					)
				).append(
					$('<div />').addClass('col2').append(
						$('<div />').addClass('headline').append(
							$('<div />').addClass('right').append(
								$('<span />').addClass('sku')
							).append(
								$('<span />').addClass('productid')
							)
						).append(
							$('<div />').addClass('brand')
						).append(
							$('<div />').addClass('name')
						)
					).append(
						$('<div />').addClass('price').append(
							$('<span />').addClass('original')
						).append(
							$('<span />').addClass('new')
						).append(
							$('<span />').addClass('currency')
						).append(
							$('<span />').addClass('status')
						)
					)/*.append(
						$('<div />').addClass('promo')
					)*/.append(
						$('<div />').addClass('tags')
					).append(
						$('<div />').addClass('care')
					).append(
						$('<div />').addClass('x')
					).append(
						$('<div />').addClass('attrs').append(
							$('<div />').addClass('attrSet').append(
								$('<div />').addClass('title').append(
									$('<span />').addClass('text')
								).append(
									$('<span />').addClass('desc')
								)
							)
						).append(
							$('<div />').addClass('attrSet').append(
								$('<div />').addClass('title').append(
									$('<span />').addClass('text')
								).append(
									$('<span />').addClass('desc')
								)
							)
						)
					).append(
						$('<div />').addClass('buttons').append(
							$('<input />').addClass('qty').attr({name:'bag_qty',id:'bag_qty',maxlength:3}).val(1)
						).append(
							$('<button />').addClass('btn_bag').html('+ Add to Bag')
						).append(
							$('<div />').addClass('stack sm').append(
								$('<button />').addClass('btn_wishlist').html('+ Wish List')
							).append(
								$('<button />').addClass('btn_priceAlert').html('+ Price Alert')
							)
						).append(
							$('<div />').addClass('stack').append(
								$('<button />').addClass('btn_available').html('Store Availability')
							).append(
								$('<button />').addClass('btn_close').html('Back')
							)
						).append(
							$('<div />').addClass('teaser').html('<img src="//img.shopwarrens.com/www/teaser.png" width="231" height="45" />')
						)
					)
				);
				a.product.ui = {
					brand:p.find('.brand'),
					name:p.find('.name'),
					sku:p.find('.sku'),
					id:p.find('.productid'),
					promo:p.find('.promo'),
					price:p.find('.price'),
					priceOrig:p.find('.price .original'),
					priceNew:p.find('.price .new'),
					priceCurrency:p.find('.price .currency'),
					priceStatus:p.find('.price .status'),
					tags:p.find('.tags'),
					attrSet1:$(p.find('.attrs .attrSet')[0]),
					attrSet1Desc:$(p.find('.attrs .attrSet')[0]).find('.title .desc'),
					attrSet2:$(p.find('.attrs .attrSet')[1]),
					attrSet2Desc:$(p.find('.attrs .attrSet')[1]).find('.title .desc'),
					img:p.find('.photo .img'),
					thumbList:p.find('.thumbs .list'),
					loading:p.find('.loadAnimation'),
					col1:p.find('.col1'),
					col2:p.find('.col2'),
					qty:p.find('input.qty'),
					close:p.find('.col1 .close'),
					care:p.find('.col2 .care')
				};
			}
			return a.product.ui;
		},
		populateUI:function(j){
			var ui = a.product.getUI(),
				UL = null;
			
			ui.name.html(j.p.n);
			if (j.p.bi !== '') { ui.brand.html('<img src="//img.shopwarrens.com/brand/'+j.p.bi+'" />'); }
			else { ui.brand.html(j.p.b); }
			ui.sku.html(j.p.s);
			ui.id.html(j.p.i);
			ui.promo.css({display:'none'});
			if (j.p.d === 1) { ui.price.addClass('sale'); }
			else { ui.price.removeClass('sale'); }
			ui.priceNew.html(j.p.p2);
			ui.priceOrig.html(j.p.p1);
			ui.priceCurrency.html('CDN');
			ui.priceStatus.html("Woah - that's "+j.p.pd+"% off!");
			
			// tags or description
			ui.tags.children().remove();
			if (j.p.tx !== '') {
				ui.tags.html('<p>'+j.p.tx+'</p>');
			} else {
				$.each(j.g,function(i,e){
					if (i === 0 || i%3 === 0) {
						UL = $('<ul />').appendTo(ui.tags);	
					}
					UL.append($('<li />').html(e.s+': '+e.n));
				});
			}
			UL = null;
			
			// attr labels
			if (j.p.t === 'denim') {
				ui.attrSet1.find('.title .text').html('Waist');	
				ui.attrSet2.find('.title .text').html('Length');	
			} else {
				ui.attrSet1.find('.title .text').html('Size');	
				ui.attrSet2.find('.title .text').html('Color');	
			}
			ui.attrSet1Desc.html('').css({display:'none'});	
			ui.attrSet2Desc.html('').css({display:'none'});	
				
			// sizes/waist
			ui.attrSet1.children('ul').remove();
			$.each(j.z,function(i,e){
				if (i === 0 || i%4 === 0) {
					UL = $('<ul />').appendTo(ui.attrSet1);	
				}
				UL.append($('<li />').html(e.n).attr({id:'-z'+e.i}).addClass(e._c).data({id:e.i}));
			});
			UL = null;

			// color/length
			ui.attrSet2.children('ul').remove();
			$.each(j.s,function(i,e){
				var li = null;
				
				if (i === 0 || i%4 === 0) {
					UL = $('<ul />').appendTo(ui.attrSet2);	
					if (j.p.t !== 'denim') { UL.addClass('swatches'); }
				}
				if (j.p.t !== 'denim') {
					li = $('<li />').attr({id:'-s'+e.i}).addClass(e._c).data({id:e.i}).append($('<img />').attr({src:'//img.shopwarrens.com/product/swatch/'+e.w,width:32,height:32,title:e.c}));
				} else {
					li = $('<li />').html(e.n).attr({id:'-s'+e.i}).addClass(e._c).data({id:e.i});
				}
				if (e.i === j.p.y && j.p.y !== '') { li.addClass('default'); } // if this color swatch matches the color of the product
				UL.append(li);
			});
			UL = null;
			
			// thumbs
			ui.thumbList.children().remove();
			$.each(j.i,function(i,e){
				var thumb = $('<div />').addClass('thumb -s'+e.s+'_thumb').data({serverFile:e.f,styleid:e.s,ishd:e.hd}).append(
					$('<div />').addClass('bg')
				).append(
					$('<div />').addClass('img').append(
						$('<img />').attr({src:'//img.shopwarrens.com/product/130x173/'+e.f,width:44,height:61})
					)
				);
				if (e.s === j.p.y && j.p.y !== '') { thumb.addClass('default'); } // if this color swatch matches the color of the product
				ui.thumbList.append(thumb);
			});
			
			// care
			ui.care.children().remove();
			$.each(j.c,function(i,e){
				var thumb = $('<img />').attr({width:16,height:16,alt:e.n,title:e.n,src:e.u}).appendTo(ui.care);
			});
			
			// fabric (add to care div)
			$.each(j.f,function(i,e){
				var thumb = $('<div />').addClass('fabric').html(e.v+'% '+e.n).appendTo(ui.care);
			});
			
			// social media
			a.product.socialify(j);
		},
		socialify:function(data){
			var social = $('#social'),
				plusOne = null,
				fbLike = null,
				tweet = null;
			
			// reset the buttons
			social.empty();
			// facebook like
			fbLike = $('<div class="fblike"><fb:like href="'+location.href+'" send="no" layout="button_count" height="22" width="60" show_faces="no" action="like"></fb:like></div>').appendTo(social);
			FB.XFBML.parse();
			// facebook 'share' hack
			$('<div class="fbshare"><div class="mimic-fb"><a href="javascript:void(0);"><img src="//img.shopwarrens.com/www/mimic-fb.jpg" height="12" width="12" /><span class="text">Share</span></a></div></div>').click(function(){
				var title = data.p.n+' ('+data.p.b+') - Warren\'s',
					caption = (data.p.d === 1)?'ON SALE '+data.p.p2+' (reg. '+data.p.p1+')':data.p.p2,
					image = '//img.shopwarrens.com/product/130x173/'+data.p.f;
				
				a.facebook.publish(title,caption,image);
			}).appendTo(social);
			// plusone
			plusOne = $('<div class="gg"><div id="-plusone"></div></div>').appendTo(social);
			gapi.plusone.render('-plusone',{size:'medium',href:location.href,annotation:'none'});
			// twitter
			tweet = $('<div class="tw"><script src="//platform.twitter.com/widgets.js" type="text/javascript"></script><a url="'+location.href+'" href="//twitter.com/share" data-count="none" data-via="shopwarrens" class="twitter-share-button">Tweet</a></div>').appendTo(social);
			social.fadeIn();
		},
		applyUIFunctions:function(){
			var ui = a.product.getUI(),
				defaultStyleLI = ui.attrSet2.find('li.default').first();
			
			// main image interaction
			ui.img.unbind('mousemove').unbind('mouseout').unbind('click');
			ui.img.mousemove(function(ev){ 
				if (a.isTouch) { return false; }
				var img = $($(this).find('img')[0]),
					xM = ev.pageX-$(this).offset().left,
					yM = ev.pageY-$(this).offset().top,
					w1 = 236,
					h1 = 315,
					w2 = 450,
					h2 = 600,
					x2 = -((w2-w1)*(xM/w1)),
					y2 = -((h2-h1)*(yM/h1)),
					ishd = $(this).data('ishd');
				img.css({height:h2+'px',width:w2+'px',left:x2+'px',top:y2+'px'});
				if (ishd === 1) { $(this).siblings('.zoom').css({display:'block'}); }
			}).mouseout(function(ev){ 
				if (a.isTouch) { return false; }
				var img = $(this).find('img'),
					w1 = 236,
					h1 = 315,
					ishd = $(this).data('ishd');
				img.css({height:h1+'px',width:w1+'px',left:'0px',top:'0px'});
				if (ishd === 1) { $(this).siblings('.zoom').css({display:'none'}); }
			}).click(function(ev){
				var imgSrc = $($(this).children()[0]).attr('src');
					ishd = $(this).data('ishd');
					box = $('<div />').addClass('imgBox').append(
								$('<div />').addClass('bg')
							).append(
								$('<div />').addClass('box').append(
									$('<img />').attr({src:imgSrc,width:450,height:600})
								)
							).append(
								$('<div />').addClass('close').click(function(){ $(this).parents('.imgBox').fadeOut(function(){ $(this).remove(); }); })
							).appendTo(document.body).fadeIn();
				
				if (ishd === 1) {
					box.find('.box img').attr({src:imgSrc.replace('450x600','900x1200'),width:450,height:600})
					box.find('.box').mousemove(function(ev){ 
						if (a.isTouch) { return false; }
						var img = $($(this).children()[0]),
							xM = ev.pageX-$(this).offset().left,
							yM = ev.pageY-$(this).offset().top,
							w1 = 450,
							h1 = 600,
							w2 = 900,
							h2 = 1200,
							x2 = -((w2-w1)*(xM/w1)),
							y2 = -((h2-h1)*(yM/h1));
						img.css({height:h2+'px',width:w2+'px',left:x2+'px',top:y2+'px'});
					}).mouseout(function(ev){ 
						if (a.isTouch) { return false; }
						var img = $(this).find('img'),
							w1 = 450,
							h1 = 600;
						img.css({height:h1+'px',width:w1+'px',left:'0px',top:'0px'});
					})
				}
			});
			
			// thumb clicking
			ui.thumbList.children().click(function(ev){
				a.product._onThumbClick($(this),ev);
			});
			
			// thumb scrolling
			ui.thumbList.css({top:'0px'});
			a.product.el.find('.thumbs .button.up, .thumbs .button.down').unbind('mousedown').removeClass('disabled');
			if (ui.thumbList.children().length >= 5) {
				a.product.el.find('.thumbs .button.up').mousedown(function(){ a.product.thumbScroll('up'); });
				a.product.el.find('.thumbs .button.down').mousedown(function(){ a.product.thumbScroll('down'); });
			} else {
				a.product.el.find('.thumbs .button.up').addClass('disabled');
				a.product.el.find('.thumbs .button.down').addClass('disabled');
			}	
			
			// size clicking
			ui.attrSet1.find('li').click(function(){
				if ($(this).hasClass('disabled')) { return; }
				else if ($(this).hasClass('on')) {
					$(this).removeClass('on');
					ui.attrSet2.find('li').removeClass('disabled');
					ui.attrSet1Desc.html('').css({display:'none'});
				} else {
					ui.attrSet1.find('li').removeClass('on');
					$(this).addClass('on');
					ui.attrSet1Desc.html($(this).html()).css({display:'block'});
					ui.attrSet2.find('li').removeClass('disabled').not('.'+$(this).attr('id')).addClass('disabled').removeClass('on');
				}
			}).mouseover(function(){
				ui.attrSet1Desc.html($(this).html()).addClass('hint').css({display:'block'});
			}).mouseout(function(){
				var selectedSize = ui.attrSet1.find('.on');
				if (selectedSize.length > 0) { ui.attrSet1Desc.html(ui.attrSet1.find('.on').html()).removeClass('hint').css({display:'block'}); }
				else { ui.attrSet1Desc.html('').removeClass('hint').css({display:'none'}); }
			});
			
			// lenght/swatch clicking
			ui.attrSet2.find('li').click(function(){
				if ($(this).hasClass('disabled')) { return; }
				else if ($(this).hasClass('on')) {
					$(this).removeClass('on');
					ui.attrSet1.find('li').removeClass('disabled');
					ui.attrSet2Desc.html('').css({display:'none'});
				} else {
					a.product._onThumbClick(ui.thumbList.find('.'+$(this).attr('id')+'_thumb').first(),null,1);
					ui.attrSet2.find('li').removeClass('on');
					$(this).addClass('on');
					if ($(this).find('img').length > 0) {
						ui.attrSet2Desc.html($(this).find('img').attr('title')).css({display:'block'});
					} else {
						ui.attrSet2Desc.html($(this).html()).css({display:'block'});
					}
					ui.attrSet1.find('li').removeClass('disabled').not('.'+$(this).attr('id')).addClass('disabled').removeClass('on');
				}
			}).mouseover(function(){
				if ($(this).find('img').length > 0) {
					ui.attrSet2Desc.html($(this).find('img').attr('title')).addClass('hint').css({display:'block'});
				} else {
					ui.attrSet2Desc.html($(this).html()).addClass('hint').css({display:'block'});
				}
			}).mouseout(function(){
				var selectedStyle = ui.attrSet2.find('.on');
				if (selectedStyle.length > 0) {
					if (selectedStyle.find('img').length > 0) {
						ui.attrSet2Desc.html(selectedStyle.find('img').attr('title')).removeClass('hint').css({display:'block'});
					} else {
						ui.attrSet2Desc.html(selectedStyle.html()).removeClass('hint').css({display:'none'});
					}
				} else {
					ui.attrSet2Desc.html('').removeClass('hint').css({display:'none'});
				}
			});
			
			// auto select the first swatch (almost 100% of the time) OR the first thumbnail image (denim)
			if (defaultStyleLI.length > 0) {
				defaultStyleLI.click();
			}
			
			// catch all - if for some reason a thumb still isn't selected, manually select it (denim in a wishlist)
			if (ui.thumbList.find('.thumb.on').length === 0) {
				ui.thumbList.find('.thumb').first().click();
			} 
			
			// if there is only one size, select it
			if (ui.attrSet1.find('li').not('.on').length === 1) {
				ui.attrSet1.find('li').first().click();
			} 
			
			// if there is only one length and its not already selected, select it
			if (ui.attrSet2.find('li').length === 1 && ui.attrSet2.find('li.on').length === 0 && ui.attrSet2.find('li img').length === 0) {
				ui.attrSet2.find('li').first().click();
			}
			
			// buttons
			if (a.shopOn === 1) {
				a.product.el.find('.btn_bag').unbind('click').click(function(){
					a.bag.add();
				});
			}
			a.product.el.find('.btn_wishlist').unbind('click').click(function(){
				a.weblist.add('wishlist');
			});
			a.product.el.find('.btn_priceAlert').unbind('click').click(function(){
				a.weblist.add('pricealert');
			});
			a.product.el.find('.btn_available').unbind('click').click(function(){
				if (ui.attrSet2.find('li.on').length === 0) {
					alert('Please select a color/length.');
					return;	
				}	
				if (ui.attrSet1.find('li.on').length === 0) {
					alert('Please select a size/waist.');
					return;	
				}
				
				window.location = '#availability?t=product&i='+ui.id.html()+'&s='+ui.attrSet2.find('li.on').data().id+'&z='+ui.attrSet1.find('li.on').data().id;
				///a.availability.open('product');
			});
			a.product.el.find('.btn_close').unbind('click').click(function(){
				a.product.back();
			});
			ui.close.unbind('click').click(function(){
				a.product.back();			
			});
		},
		close:function(params,hash,newHash){
			if (hash !== 'feedback' && hash !== 'login' && hash !== 'forgot' && hash !== 'signup' && hash !== 'products' && hash !== 'herbrands' && hash !== 'hisbrands' && hash !== 'availability') {
				$('.content .body').animate({top:'0px'});
				a.product.el.animate({top:'-496px'});
				$('.pDetail').data({'hash':''});
			} else if (hash === 'products') {
				a.product.el.animate({top:'-496px'});
			}
			$('#social').fadeOut();
		},
		back:function(){
			var pListHash = $('.pList').data().hash; // store the hash value of the product list (if it exists)
			
			// if there is a product list open in the background, go there immeditately
			if (typeof pListHash !== 'undefined') {
				window.location = pListHash;
				
			// otherwise, use the normal back function
			} else {
				a.nav.back();
			}
		},
		thumbScroll:function(dir){
			var ui = a.product.getUI(),
				y = ui.thumbList.position().top,
				y2 = (dir === 'down')?y-53:y+53;
				y2 = Math.min(0,y2);
				y2 = Math.max(y2,-(ui.thumbList.outerHeight()-200));
			ui.thumbList.css({top:y2+'px'});
		},
		appear:function(){
			a.product.ui.loading.animate({opacity:0,'margin-top':'-40px'},function(){ $(this).css({display:'none'}); });
			a.product.ui.col1.css({opacity:0,'margin-left':'-40px',display:'block'}).animate({opacity:1,'margin-left':'0px'});
			a.product.ui.col2.css({opacity:0,'margin-left':'40px',display:'block'}).animate({opacity:1,'margin-left':'0px'});
		},
		disappear:function(){
			a.product.ui.loading.css({opacity:1,'margin-top':'0px'});
			//a.product.ui.loading.css({opacity:0,'margin-top':'-40px',display:'block'}).animate({opacity:1,'margin-top':'0px'});
			a.product.ui.col1.animate({opacity:0,'margin-left':'-40px'},function(){  });
			a.product.ui.col2.animate({opacity:0,'margin-left':'40px'},function(){  });
		},
		_onThumbClick:function(thumb,ev,stopProp){
			if (thumb.hasClass('on') || thumb.length === 0) { return; }
			
			var src = thumb.data().serverFile,
				ui = a.product.getUI(),
				swatch = null;
				
			if (ui.img.children().length === 0) {
				ui.img.append($('<img />'));
			}
			ui.img.children().attr({src:'//img.shopwarrens.com/product/130x173/'+src}); // quickly show the low-res version
			ui.img.children().attr({src:'//img.shopwarrens.com/product/450x600/'+src}); // let the full version load in slowly
			thumb.addClass('on').siblings().removeClass('on');
			
			stopProp = (typeof stopProp === 'undefined')?0:stopProp;
			if (!stopProp) {
				swatch = ui.attrSet2.find('#-s'+thumb.data().styleid);
				// don't click the swatch if its already 'on'
				if (!swatch.hasClass('on')) {
					ui.attrSet2.find('#-s'+thumb.data().styleid).click();
				}
			}
			ui.img.data('ishd',thumb.data().ishd);
		},
		animateImageTo:function(el){
			var ui = a.product.getUI(),
				img = ui.thumbList.find('.on').data().serverFile,
				position1 = ui.img.offset(),
				position2 = el.offset(),
				imgAnim = null;
				
			imgAnim = $('<img />').attr({src:'//img.shopwarrens.com/product/130x173/'+img,width:'230',height:'309',border:'0'}).css({position:'absolute',display:'block',top:position1.top+'px',left:position1.left+'px',zIndex:999999}).appendTo($(document.body));
			imgAnim.animate({top:position2.top+'px',left:position2.left+'px',height:'20px',width:'20px',opacity:0},function(){ $(this).remove(); });
		}
	},
	slides:{
		index:null,
		interval:null,
		intervalTime:7000,
		intervalTime_default:7000,
		isOneCycleComplete:0,
		init:function(){
			if ($('div.slides .slide').length === 0) { return; }
			
			a.slides.index = null;
			if (a.slides.interval !== null) { clearInterval(a.slides.interval); }
			
			$('.body .arrows').css({display:'none'});
			$('.body .arrows .left').click(function(){ a.slides.previous(1); });
			$('.body .arrows .right').click(function(){ a.slides.next(1); });
			
			a.slides.format();
			a.slides.next();
			
			if ($('div.slides .slide').length > 1) {
				setTimeout(function(){ $('.body .arrows').fadeIn(); }, 3000);
			}
		},
		format:function(){
			var startLeft = -($('div.slides .slide').length*980);
			$.each($('div.slides .slide'),function(i,e){
				$(e).css({top:'0px',left:(980*i)+'px'});
			});
			$('div.slides').css({left:startLeft+'px'});
		},
		next:function(pause){
			pause = (typeof pause !== 'undefined')?pause:0;
			if (a.slides.index === null) {
				a.slides.index = 0;
				a.slides.go(3000);
				return;
			} else {
				a.slides.index++;
			}

			if (a.slides.index > $('div.slides .slide').length-1) {
				a.slides.index = 0;
				a.slides.intervalTime = (pause)?20000:a.slides.intervalTime_default;
				a.slides.go(1200);
			} else {
				a.slides.intervalTime = (pause)?20000:a.slides.intervalTime;
				a.slides.go();
			}
		},
		previous:function(pause){
			pause = (typeof pause !== 'undefined')?pause:0;
			a.slides.index--;
			if (a.slides.index < 0) {
				a.slides.index = $('div.slides .slide').length-1;
				a.slides.go(1200);
			} else {
				a.slides.intervalTime = (pause)?20000:a.slides.intervalTime;
				a.slides.go();
			}
		},
		go:function(dur){
			dur = (typeof dur !== 'undefined')?dur:550;
			if ($('div.slides .slide').length > 1) {
				$('div.slides').animate({left:(-980*a.slides.index)+'px'},dur,'easeOutCubic',function(){ a.slides.restartTimeout(); });
			} else {
				$('div.slides').css({left:(-980*a.slides.index)+'px'});
			}
		},
		restartTimeout:function(){
			if (a.slides.interval !== null) { clearInterval(a.slides.interval); }
			a.slides.interval = setInterval(function(){ a.slides.next(); },a.slides.intervalTime);
			if (a.slides.intervalTime === 20000) { a.slides.intervalTime = a.slides.intervalTime_default; } // never continue running the slideshow at this speed
		}
	},
	login:{
		init:function(){
			$('#divalog_login_form_email').keyup(function(ev){
				if (window.event.keyCode === 13) {
					$('#divalog_login_form_password').focus();
				}
			});
			$('#divalog_login_form_password').keyup(function(ev){
				if (window.event.keyCode === 13) {
					a.login.submit();
				}
			});
		},
		open:function(){
			jc.form.unvalidate('#divalog_login_form');
			a.ui.divalog.open('#divalog_login',function(){
				$("#divalog_login input").first().focus();
			});
		},
		submit:function(){
			var params = $('#divalog_login_form').serializeArray();
			$('#divalog_login_process').slideDown();
			$('#divalog_login_formWrap').slideUp();
			$('#divalog_login .dlg-btns').slideUp();
			$.post('/cf/ajax/user.login.cfm',params,a.login._loginResponse,'json');
		},
		_loginResponse:function(j){
			if (j.s === 1) {
				// populate links at top
				$('.sm-links .user .firstname').html(j.u.f);
				$(document.body).addClass('-is-logged-in');
				//$('.sm-links').addClass('loggedin');
				
				// hide divalog
				$('<div />').addClass('welcome').html('Welcome back, <strong>'+j.u.f+'</strong>!').appendTo('#divalog_login .dlg-bdy').slideDown();
				$('#divalog_login_process').slideUp();
				setTimeout(function(){ $('#divalog_login .dlg-x').click(); },2000);
				
				// populate checkout screen
				a.weblist.load('pricealert');
				a.weblist.load('wishlist');
				a.weblist.load('bag');
				
				a.userFirstName = j.u.f;
				
				if ($('#checkout_form').length > 0) { // if we're on the checkout screen
					// update checkout fields
					$('#bill_firstname').val(j.u.BillingFirstName);
					$('#bill_lastname').val(j.u.BillingLastName);
					$('#bill_address').val(j.u.BillingAddress);
					$('#bill_city').val(j.u.BillingCity);
					$('#bill_province').val(j.u.BillingProvince);
					$('#bill_postalcode').val(j.u.BillingPostalCode);
					$('#bill_phone').val(j.u.BillingPhone);
					$('#bill_email').val(j.u.BillingEmail);
					$('#bill_email2').val(j.u.BillingEmail);
					$('#bill_phone').val(j.u.BillingPhone);
					$('#ship_firstname').val(j.u.ShippingFirstName);
					$('#ship_lastname').val(j.u.ShippingLastName);
					$('#ship_address').val(j.u.ShippingAddress);
					$('#ship_city').val(j.u.ShippingCity);
					$('#ship_province').val(j.u.ShippingProvince);
					$('#ship_postalcode').val(j.u.ShippingPostalCode);
					$('#ship_phone').val(j.u.ShippingPhone);
					$('#ship_email').val(j.u.ShippingEmail);
					$('#ship_email2').val(j.u.ShippingEmail);
					$('#ship_phone').val(j.u.ShippingPhone);
					
					// now that we've populated all the fields, lets save those values to the session
					a.checkout.saveFormToSession();
					
					// refresh bag on the left of checkout screen
					a.checkout.loadCart();
				}
				
				/*var html = '<li class="name">Welcome, <a href="#profile">'+json.result.FIRSTNAME+'</a>!</li>';
				html += '<li><a href="#profile">My Profile</a></li>';
				//if (json.result.ISEMPLOYEE === '1') html += '<li><a href="#referrals">Referrals</a></li>';
				html += '<li class="last" onClick="a.logout();">Logout</li>';
				
				$('.account ul.hMenu').html(html);
				
				setTimeout(function(){ $('#divalog_login').fadeOut(); },800);*/
			} else {
				alert('Login failed.  Please try again.');
				$('#divalog_login_process').slideUp();
				$('#divalog_login_formWrap').slideDown();
				$('#divalog_login .dlg-btns').slideDown();
			}
		},
		clear:function(){
			$('#divalog_login_form')[0].reset();
			$('#divalog_login_process').slideUp();
			$('#divalog_login_formWrap').slideDown();
			$('#divalog_login .dlg-btns').slideDown();
			$('#divalog_login .welcome').remove();
		},
		switchToSignUp:function(){
			a.ui.divalog.close($('#divalog_login'));
			a.signup.open({f:'1'});
		},
		switchToForgot:function(){
			$('#divalog_forgot_form_email').val($('#divalog_login_form_email').val());
			a.ui.divalog.close($('#divalog_login'));
			a.forgot.open();
		}
	},
	logout:function(){
		$('#loading-payment .desc').html('LOGGING OUT');
		$('#loading-payment').fadeIn(function(){
			var logoutTimer = setInterval(function(){ $('#loading-payment .desc').append('.'); },1000);
			
			if (confirm(a.userFirstName+' - Are you sure you want to logout?')) {
				//$('.sm-links').removeClass('loggedin');
				$.post('/cf/ajax/user.logout.cfm',function(){ 
					clearInterval(logoutTimer);
					$('#loading-payment').fadeOut();
					
					a.userFirstName = '';
					$(document.body).removeClass('-is-logged-in');
					$('.sm-links .user .firstname').html('');
					a.checkout.loadCart();
					a.weblist.clear('wishlist');
					a.weblist.clear('pricealert');
					a.weblist.clear('bag');
					a.signup.clear();
					a.login.clear();
					
					if ($('#checkout_form').length > 0) { // if we're on the checkout screen
						// update checkout fields
						$('#bill_firstname').val('');
						$('#bill_lastname').val('');
						$('#bill_address').val('');
						$('#bill_city').val('');
						$('#bill_province').val('ON');
						$('#bill_postalcode').val('');
						$('#bill_phone').val('');
						$('#bill_email').val('');
						$('#bill_email2').val('');
						$('#bill_phone').val('');
						$('#ship_firstname').val('');
						$('#ship_lastname').val('');
						$('#ship_address').val('');
						$('#ship_city').val('');
						$('#ship_province').val('ON');
						$('#ship_postalcode').val('');
						$('#ship_phone').val('');
						$('#ship_email').val('');
						$('#ship_email2').val('');
						$('#ship_phone').val('');
						
						// now that we've populated all the fields, lets save those values to the session
						a.checkout.saveFormToSession();
					}
					
					if (a.nav.currentHash === 'profile' || a.nav.currentHash === 'login') { window.location = '/'; }
				});
			} else {
				clearInterval(logoutTimer);
				$('#loading-payment').fadeOut();
			}
		});
	},
	signup:{
		referralInterval:null,
		open:function(params){
			// default options for this function
			params = $.extend({
				n:null, // name
				e:null, // email
				f:0 // forcemembership
			},params);
			
			// reset validation on this form
			jc.form.unvalidate('#divalog_signup_form');
			
			// open dialog
			a.ui.divalog.open('#divalog_signup',function(){
				
				// pre populate the signup form
				$("#divalog_signup_form_firstname").val(params.n);									 
				$("#divalog_signup_form_email").val(params.e);									 
				
				// toggle force membership
				if (params.f === '1') {
					
					// no matter what the user does, make sure that 'ShopWarrens.com Account' checkbox stays selected and that the first password field is auto focused
					$("#divalog_signup_form_isBasic").attr({'checked':true}).unbind('change').click(function(){
						$(this).attr({'checked':true}); 
						$("#divalog_signup_form_password").focus();
					});
					
				// otherwise, make the membership optional
				} else {
					$("#divalog_signup_form_isBasic").attr({'checked':false}).unbind('change').click(function(){ a.signup.onClickShopWarrensAccount(); });
					
				}
				
				// trigger the function that governs the membership checbox behaviour to make sure the form displays correctly
				a.signup.onClickShopWarrensAccount();
				
				// auto focus on password field if name and email are popualted
				if (params.f === '1' && params.e != null && params.n != null) {
					$("#divalog_signup_form_password").focus();
				
				// auto focus on checkbox if name and email are populated
				} else if (params.f === '1' && params.e != null && params.n != null) {
					$("#divalog_signup_form_isPrivacyPolicy").focus();
				
				// otherwise, auto focus on name field (first field)
				} else {
					$("#divalog_signup_form_firstname").focus();
				}
			});
		},
		submit:function(){
			if (jc.form.validate('#divalog_signup')) {
				$('#divalog_signup_process').slideDown();
				$('#divalog_signup_formWrap').slideUp();
				$('#divalog_signup .dlg-btns').slideUp();
				var params = $('#divalog_signup_form').serializeArray();
				$.post('/cf/ajax/user.signup.cfm',params,function(json){
					if (json.status === 'success') {
						// populate links at top
						$('.sm-links .user .firstname').html(json.result.FIRSTNAME);
						$(document.body).addClass('-is-logged-in');
						//$('.sm-links').addClass('loggedin');
						
						// hide divalog
						$('<div />').addClass('welcome').html('Welcome, <strong>'+json.result.FIRSTNAME+'</strong>!').appendTo('#divalog_signup .dlg-bdy').slideDown();
						$('#divalog_signup_process').slideUp();
						setTimeout(function(){ $('#divalog_signup .dlg-x').click(); },2000);
						
						a.weblist.load('pricealert');
						a.weblist.load('wishlist');
						
						a.userFirstName = json.result.FIRSTNAME;
					} else if (json.status === 'emailonly') {
						$('<div />').addClass('welcome').html('Thanks for signing up, <strong>'+json.result.FIRSTNAME+'</strong>!').appendTo('#divalog_signup .dlg-bdy').slideDown();
						$('#divalog_signup_process').slideUp();
						setTimeout(function(){ $('#divalog_signup .dlg-x').click(); },2000);
						
					} else {
						alert('Sign-up failed. '+json.message+' Please try again.');
						$('#divalog_signup_process').slideUp();
						$('#divalog_signup_formWrap').slideDown();
						$('#divalog_signup .dlg-btns').slideDown();
					}
				},'json');
			}
		},
		clear:function(){
			$('#divalog_signup_form')[0].reset();
			$('#divalog_signup_process').slideUp();
			$('#divalog_signup_formWrap').slideDown();
			$('#divalog_signup .dlg-btns').slideDown();
			$('#divalog_signup .welcome').remove();
		},
		onReferralType:function(){
			if (a.signup.referralInterval !== null) { clearInterval(a.signup.referralInterval); }
			a.signup.referralInterval = setInterval(a.signup.checkReferral,800);
		},
		checkReferral:function(){
			var field = $('#divalog_signup_form_referralcode'),
				hint = field.siblings('.hint')[0],
				code = field.val();

			if (a.signup.referralInterval !== null) { clearInterval(a.signup.referralInterval); }
			$.post('/cf/ajax/user.find.cfm',{ReferralCode:code},function(json){
				if (json.status === 'success') { 
					a.form.onFieldSuccess(field);
				} else {
					a.form.onFieldError(field,'Promo # not recognzied.');
				}
			},'json');
		},
		onClickShopWarrensAccount:function(){
			if ($('#divalog_signup_form_isBasic').attr('checked') === true) {
				$('#divalog_signup_password_wrap').css({display:'block'});
				$('#divalog_signup_form_password').addClass('required');
				$('#divalog_signup_form_password2').addClass('required');
			} else {
				$('#divalog_signup_password_wrap').css({display:'none'});
				$('#divalog_signup_form_password').removeClass('required');
				$('#divalog_signup_form_password2').removeClass('required');
			}
		},
		openFromQuickForm:function(){
			var name = $('#Connect-FirstName').val(),
				email = $('#Connect-Email').val();
			
			if (name === 'Your Name') { name = ''; }
			if (email === 'Your Email') { email = ''; }
			
			window.location = '#signup?n='+escape(name)+'&e='+escape(email);
		}
	},
	forgot:{
		open:function(){
			jc.form.unvalidate('#divalog_forgot_form');
			a.ui.divalog.open('#divalog_forgot',function(){
				$("#divalog_forgot input").first().focus();
			},1);	
		},
		submit:function(){
			if (jc.form.validate('#divalog_forgot')) {
				var params = $('#divalog_forgot_form').serializeArray();
				$('#divalog_forgot_process').slideDown();
				$('#divalog_forgot_formWrap').slideUp();
				$('#divalog_forgot .dlg-btns').slideUp();
				$.post('/cf/ajax/user.forgot.cfm',params,function(json){
					if (json.status === 'success') {
						$('<div />').addClass('welcome').html('Email sent successfully!').appendTo('#divalog_forgot .dlg-bdy').slideDown();
						$('#divalog_forgot_process').slideUp();
						setTimeout(function(){
							$('#divalog_forgot').fadeOut(function(){
								a.forgot.clear();
							});
							a.nav.back(); // history.go(-1);
						},2000);
					} else {
						alert('Sorry - \''+$('#divalog_forgot_form_email').val()+'\' doesn\'t exist in our records.');
						$('#divalog_forgot_form_email').val('');
						$('#divalog_forgot_process').slideUp();
						$('#divalog_forgot_formWrap').slideDown();
						$('#divalog_forgot .dlg-btns').slideDown();
					}
				},'json');
			}
		},
		clear:function(){
			$('#divalog_forgot_form')[0].reset();
			$('#divalog_forgot_process').slideUp();
			$('#divalog_forgot_formWrap').slideDown();
			$('#divalog_forgot .dlg-btns').slideDown();
			$('#divalog_forgot .welcome').remove();
		}
	},
	feedback:{
		open:function(){
			jc.form.unvalidate('#divalog_feedback_form');
			a.ui.divalog.open('#divalog_feedback',function(){
				var str_a = [],
					dPrev = new Date();
				
				a.feedback.clear();
				
				$.each(a.nav.history,function(i,e){
					var secondsSince = (dPrev-e.d)/1000;
					str_a.push(e.d.getHours()+':'+e.d.getMinutes()+':'+e.d.getSeconds()+' - '+e.h+' ('+secondsSince+'secs)');
					dPrev = e.d;
				});
				
				$("#divalog_feedback_form_history").val(str_a.join(',\n'));
				$("#divalog_feedback textarea").first().focus();
			});	
		},
		submit:function(){
			if (jc.form.validate('#divalog_feedback')) {
				var params = $('#divalog_feedback_form').serializeArray();
				$('#divalog_feedback_process').slideDown();
				$('#divalog_feedback_formWrap').slideUp();
				$('#divalog_feedback .dlg-btns').slideUp();
				$.post('/cf/ajax/feedback.cfm',params,function(json){
					if (json.status === 'success') {
						$('<div />').addClass('welcome').html("<p align=\"center\">Thanks for helping us make your online experience the best that it can be!</p>").appendTo('#divalog_feedback .dlg-bdy').slideDown();
						$('#divalog_feedback_process').slideUp();
						setTimeout(function(){ $('#divalog_feedback .dlg-x').click(); },2000);
					} else {
						alert('Brutal... you\'re trying to give us feedback but for some reason, we\'re unable to receive it. Please try again later.');
						$('#divalog_feedback_form_email').val('');
						$('#divalog_feedback_process').slideUp();
						$('#divalog_feedback_formWrap').slideDown();
						$('#divalog_feedback .dlg-btns').slideDown();
					}
				},'json');
			}
		},
		clear:function(){
			$('#divalog_feedback_form')[0].reset();
			$('#divalog_feedback_process').slideUp();
			$('#divalog_feedback_formWrap').slideDown();
			$('#divalog_feedback .dlg-btns').slideDown();
			$('#divalog_feedback .welcome').remove();
		}
	},
	connect:{
		emailSignUp:function() {
			// populate signup form
			$('#divalog_signup_form_firstname').val($('#Connect-FirstName').val());
			$('#divalog_signup_form_email').val($('#Connect-Email').val());
			$('#divalog_signup_form_isSlice').attr('checked',1);
			// open signup form
			a.signup.open(1);
		},
		reset:function(){
			$('#FirstName').val($('#FirstName').attr('alt')).addClass('hint');
			$('#LastName').val($('#LastName').attr('alt')).addClass('hint');
			$('#Email').val($('#Email').attr('alt')).addClass('hint');
			a.connect.close(e);
		}
	},
	profile:{
		init:function(){
			jc.form.init('#UserForm',a.form.onFieldError,a.form.onFieldSuccess);
		},
		save:function(){
			if (jc.form.validate('#UserForm')) {
				var params = $('#UserForm').serializeArray();
				$.post('/cf/ajax/user.update.cfm',params,function(json){
					if (json.status === 'success') {
						alert('Your profile was successfully updated.');
						//window.location = '#home';
					} else {
						alert('Failed to update your status. Please try again.');
					}
				},'json');
			}
		},
		togglePasswordChange:function(){
			var a = $('#profile-changepassword_anchor'),
				wrap = $('#profile-changepassword_wrap');
			
			if (wrap.css('display') === 'none') {
				a.html('Cancel');
				wrap.css('display','block');
				wrap.find('input').addClass('required');
			} else {
				a.html('Change Password');
				wrap.css('display','none');
				$('#profile-PasswordOld').val('');
				$('#profile-PasswordNew').val('');
				$('#profile-PasswordNew2').val('');
				wrap.find('input').removeClass('required');
			}
		}
	},
	search:{
		init:function(){
			var srch = $('.srch');
			$('#srch-kw').keyup(function(ev){
				if (ev.keyCode === 13) {
					a.search.submit();
				}
			});
			$('#srch-btn').click(function(){ a.search.submit(); });
		},
		submit:function(){
			//var gender = ($('.srch').hasClass('his') || $('.srch').hasClass('wasHis'))?'his':'her';
			var query = $('#srch-kw').val(),
				gender = a.search.getGenderFromString(query);
			
			if (gender === '') {
				$('#search-choice .term').html('"'+query+'"');
				$('#search-choice').fadeIn();
				return;
			}	
			
			if ($('#srch-kw').val() !== '' && $('#srch-kw').val() !== 'Search') {
				window.location = '#products?q='+$('#srch-kw').val();
			}
		},
		getGenderFromString:function(str){
			var synonymHis = ['men','mens','men\'s','his','him','guy','guys','guy\'s','boy','boys','boy\'s'],
				synonymHer = ['lady','ladies','lady\'s','her','hers','her\'s','girl','girls','girl\'s'];
				returnStr = '';
			
			// is it his?
			$.each(synonymHis,function(i,his){
				if (str.indexOf(his) > -1) {
					returnStr = 'his';
				}
			});
			
			// is it hers?
			$.each(synonymHer,function(i,her){
				if (str.indexOf(her) > -1) {
					returnStr = 'her';
				}
			});
			
			return returnStr;
		},
		onChoice:function(g){
			var query = $('#srch-kw').val();
			$('#srch-kw').val(g+' '+query);
			$('#search-choice').fadeOut();	
			a.search.submit();
		},
		cancelChoice:function(){
			$('#srch-kw').val('Search');
			$('#search-choice').fadeOut();	
		}
	},
	availability:{
		open:function(p){
			a.availability.clear();
			var ui = a.product.getUI();
			
			a.ui.divalog.open('#divalog_availability',function(){
				a.availability.load(p);
			});
		},
		load:function(p){
			var bdy = $('#divalog_availability_chart');
			bdy.children().remove();
			bdy.html('<p align="center"><img src="/images/loading_img.gif" /><br />Checking...</p>');
			$.post('/cf/ajax/availability.get.cfm',p,function(j){
				bdy.children().remove();
				
				t = $('<table />').addClass('avail').append(
						$('<tbody />').append(
							$('<tr />').append(
								$('<th />').addClass('check')
							).append(
								$('<th />').addClass('location')
							).append(
								$('<th />').addClass('qty').html((p.t === 'product')?'QTY':'ITEMS')
							)			  
						)
					);
				
				// loop through the list of locations
				$.each(j.l,function(i,e){
					t.append(
						$('<tr />').append(
							$('<td />').addClass('check').html((e.l.length === j.t)?'<img src="/images/available.gif" width="14" height="14" />':'<img src="/images/unavailable.gif" width="14" height="14" />')
						).append(
							$('<td />').addClass('location').append(
								$('<span />').addClass('name').html(e.n)
							).append(
								$('<span />').addClass('contact').html(e.p) //$('<span />').addClass('contact').html((e.n === 'St Laurent Centre')?'<img src="/images/reno_sm.png" width="141" height"52" style="position:relative; display:block; top:-32px; left:350px;" />':e.p)
							)
						).append(
							$('<td />').addClass('qty').html((p.t === 'product')?e.q:((e.l.length === j.t)?'All':e.l.length+' of '+j.t))
						)
					);
					if (p.t !== 'product' && e.l.length !== j.t) {
						t.append(
							$('<tr />').append(
								$('<td />')
							).append(
								$('<td />').attr({colspan:2}).addClass('location pics')
							)
						);
						k = [];
						$.each(e.l,function(j,e2){ k.push(e2.n); });
						
						t.find('.pics').last().append(
							$('<span />').html(k.join(', ')).css({'text-transform':'capitalize','font-size':'9px','color':'#999'})
						);
					}
				});
				
				bdy.append(t);
				bdy.append(
					$('<p />').addClass('sm').html('Stock last updated '+j.d)
				);
			},'json');
		},
		clear:function(){
			$('#divalog_signup_form')[0].reset();
			$('#divalog_signup_process').slideUp();
			$('#divalog_signup_formWrap').slideDown();
			$('#divalog_signup .dlg-btns').slideDown();
			$('#divalog_signup .welcome').remove();
		}
	},
	brand: {
		init:function(){
			$('.logos img').click(function(ev){
				var el = $(this);
				
				if (el.hasClass('his') && !el.hasClass('her')) {
					$('#srch-kw').val('his '+$(this).attr('alt'));
				} else if (!el.hasClass('his') && el.hasClass('her')) {
					$('#srch-kw').val('her '+$(this).attr('alt'));
				} else {
					$('#srch-kw').val($(this).attr('alt'));
				}

				a.search.submit();
				if ($(el).parents('.divalog').length > 0) {
					a.ui.divalog.close(el);
				}
			});
			$('#brand-tip *').mouseover(function(ev){ $('#brand-tip').css({display:'block'}); });
			$('#divalog_brands img').click(function(ev){
				var el = $(this);
					
				if (el.hasClass('his')) {
					$('#srch').removeClass('his her').addClass('wasHis');
					$('#srch-kw').val('his '+$(this).attr('alt'));
				} else if (el.hasClass('her')) {
					$('#srch').removeClass('his her').addClass('wasHer');
					$('#srch-kw').val('her '+$(this).attr('alt'));
				}
				a.search.submit();
				if ($(el).parents('.dlg').length > 0) {
					a.ui.divalog.close(el);
				}
			});
		},
		showOption:function(el){
			var tip = $('#brand-tip'),
				l = $(el).offset().left,
				t = $(el).offset().top,
				l1 = $(tip).outerWidth(),
				l2 = $(el).outerWidth(),
				l3 = (l2-l1)/2;
				
			tip.css({left:(l+l3)+'px',top:(t-30)+'px',display:'block'});
			tip.unbind('mouseout').mouseout(function(){ $(this).css({display:'none'}); });
			
			tip.find("a:contains('HIS')").unbind('click').click(function(){
				$('.srch').removeClass('his her').addClass('his');
				$('#srch-kw').val($(el).attr('alt'));
				a.search.submit();											 
				if ($(el).parents('.divalog').length > 0) {
					a.ui.divalog.close(el);
				}
				tip.css({display:'none'});
			});
			
			tip.find("a:contains('HER')").unbind('click').click(function(){
				$('.srch').removeClass('his her').addClass('her');
				$('#srch-kw').val($(el).attr('alt'));
				a.search.submit();	
				if ($(el).parents('.divalog').length > 0) {
					a.ui.divalog.close(el);
				}
				tip.css({display:'none'});
			});
		},
		show:function(g){
			$('#divalog_brands .head').html('Shop by '+g+' brands'); 
			$('#divalog_brands p.'+g).css({display:'block'}).siblings().css({display:'none'});
			a.ui.divalog.open('#divalog_brands',function(){});	
		}
	},
	weblist:{
		wl:{
			thumbs:null	
		},
		init:function(){
			$('.weblist .close').click(function(){ a.weblist.hide($(this)); });
			if (a.isTouch) { $('.weblist').addClass('touch'); }
			a.weblist.load('wishlist');
			a.weblist.load('pricealert');
			
			// clicking outside any of the weblist previews makes the weblist close
			$(document).click(function(ev){ if ($(ev.target).parents('.weblist, .wl, .pa, .bag, .pDetail .buttons').length === 0 && $(ev.target).closest('.weblist, .wl, .pa, .bag, .pDetail .buttons').length === 0) { a.weblist.hideAll(); } });
		},
		add:function(type){
			if (type === 'pricealert' && !$(document.body).hasClass('-is-logged-in')) {
				window.location = '/#login';
				return;
			}
			
			var ui = a.product.getUI(),
				zOn = ui.attrSet1.find('li.on'),
				sOn = ui.attrSet2.find('li.on'),
				img = null,
				params = {},
				newThumb = null,
				thumbList = null,
				errs = [],
				errStr = '';
			
			if (sOn.length > 0 && zOn.length > 0) {
				params = {
					z:zOn.data().id,	
					s:sOn.data().id,
					i:ui.id.html(),
					q:1,
					t:type
				};
				img = ui.thumbList.find('.on').data().serverFile;
				thumbList = $('#'+type+' .thumbs');
			} else {
				if (sOn.length === 0) {
					errs.push(ui.attrSet2.find('.title .text').html().toLowerCase());	
				}
				if (zOn.length === 0) {
					errs.push(ui.attrSet1.find('.title .text').html().toLowerCase());	
				}
				
				errStr += 'Make sure you\'ve selected a valid ';
				$.each(errs,function(i,w){
					if (errs.length > 1 && i === errs.length-1) { errStr += ' and '; }
					else if (errs.length > 1 && i > 0) { errStr += ', '; }
					errStr += w;
				});
				errStr += '.';

				alert(errStr);
				return;
			}
			
			// does it exist already?
			if (thumbList.find('.-i'+params.i+'.-s'+params.s+'.-z'+params.z).length > 0) {
				alert('You\'ve already got that item in your list!');
				return;	
			}
			
			if (type === 'wishlist') { a.product.animateImageTo($('.opt .wl .count')); } 
			else if (type === 'pricealert') { a.product.animateImageTo($('.opt .pa .count')); } 
			
			// temp thumb
			newThumb = $('<div />').addClass('thumb -i'+params.i+' -s'+params.s+' -z'+params.z).css({width:'0px'}).append(
					$('<div />').addClass('bg')
				).append(
					$('<div />').addClass('img temp')
				);

			// save to database
			$.post('/cf/ajax/weblist.add.cfm',params,function(j){
				newThumb.find('.img').append(
					$('<img />').attr({src:'//img.shopwarrens.com/product/130x173/'+img,width:'44',height:'58'})
				);
				newThumb.append(
					$('<div />').addClass('remove')
				);
				newThumb.data({ProductID:j.p,StyleID:j.s,SizeID:j.z});
				a.weblist.applyThumbFns(newThumb);
				a.weblist.updateCount(type);
				setTimeout(function(){ a.weblist.hide(newThumb); },1500);
			},'json');
			
			// show wishlist 
			//a.weblist.show(type);
			thumbList.append(newThumb);
			newThumb.animate({width:'50px'});
		},
		load:function(type){
			$.post('/cf/ajax/weblist.get.cfm',{t:type},function(j){
				a.weblist.update(j);
				a.weblist.updateCount(type);
			},'json');
		},
		update:function(j){
			$('#'+j.t+' .thumb').remove(); // clear existing
			$.each(j.l,function(i,e){
				var t = $('<div />').addClass('thumb -i'+e.p+' -s'+e.s+' -z'+e.z).data({ProductID:e.p,StyleID:e.s,SizeID:e.z,Quantity:e.q,LinkUrl:e.u}).append(
						$('<div />').addClass('bg')
					).append(
						$('<div />').addClass('img temp').append(
							$('<img />').attr({src:'//img.shopwarrens.com/product/130x173/'+e.f,width:'44',height:'58'})
						)
					).append(
						$('<div />').addClass('remove')
					).append(
						$('<div />').addClass('qty').append(
							$('<div />').addClass('count').html(e.q)
						)
					);
				if (e.q <= 1) { t.find('.qty').css({display:'none'}); } // hide quantity if its one
				a.weblist.applyThumbFns(t);
				$('#'+j.t+' .thumbs').append(t);
			});
			if (j.t === 'bag') {
				$('#bag h1 .amountPreview').html(': '+j.v);
			}
		},
		updateCount:function(t){
			var label = null,
				count = 0;
				
			if (t === 'wishlist') {
				label = $('.opt .wl .count');	
			} else if (t === 'pricealert') {
				label = $('.opt .pa .count');	
			} else if (t === 'bag') {
				label = $('.opt .bag .count');	
			}
			
			$('#'+t+' .thumb').each(function(i,e){
				var qty = $(e).data().Quantity;
				count += (!isNaN(parseInt(qty)))?parseInt(qty):1;
			});
			
			label.children().html(count);
			if (count > 0) {
				label.css({display:'inline'});
			} else {
				label.css({display:'none'});
			}
		},
		applyThumbFns:function(t){
			var d = $(t).data();
			//console.log(d);
			$(t).find('.remove').click(function(e){ a.weblist.remove(t); });
			$(t).mouseover(function(ev){ $(this).addClass('ovr'); });
			$(t).mouseout(function(ev){ $(this).removeClass('ovr'); });
			$(t).find('.img').click(function(ev){ /*console.log(d); return;*/ window.location = d.LinkUrl; });
		},
		clear:function(type){
			$('#'+type+' .thumbs').children().remove();
			a.weblist.updateCount(type);
		},
		show:function(type){
			var pos = {};
			
			if (type === 'wishlist') { pos = $('.opt .wl').offset(); }
			else if (type === 'pricealert') { pos = $('.opt .pa').offset(); }
			else if (type === 'bag') { pos = $('.opt .bag').offset(); }
			
			$('.weblist').not('#'+type).animate({'margin-top':'-20px','opacity':0},function(){ $(this).css({display:'none'}); });
			
			$('#'+type).css({'margin-top':'-20px','opacity':0,display:'block',top:(pos.top+30)+'px',left:(pos.left-200)+'px'}).animate({'margin-top':'0px','opacity':1},200);
		},
		hide:function(el){
			$(el).parents('.weblist').animate({'margin-top':'-20px','opacity':0},function(){ $(this).css({display:'none'}); });
		},
		hideAll:function(){
			$('.weblist').each(function(i,e){
				if ($(e).css('display') === 'block') {
					$(e).animate({'margin-top':'-20px','opacity':0},function(){ $(this).css({display:'none'}); });
				}
			});
		},
		remove:function(t){
			var params = {
				t:$(t).parents('.weblist').attr('id'),
				i:t.data().ProductID,
				s:t.data().StyleID,
				z:t.data().SizeID
			}; 
			$(t).animate({width:'0px'},function(){
				$(this).remove();
				a.weblist.updateCount(params.t);
			}); 
			if (params.t === 'bag') { $('#bag h1 .amountPreview').html(''); }
			$.post('/cf/ajax/weblist.remove.cfm',params,function(j){
				if (j.t === 'bag') {
					$('#bag h1 .amountPreview').html(': '+j.ta);
					if ($('#checkout_form').length > 0) { // if we're on the checkout screen
						a.checkout.loadCart(); // reload cart
					}
				}
			},'json');
		}	
	},
	bag:{
		init:function(){
			if (a.shopOn === 1) {
				a.weblist.load('bag');
			} else {
				$('.opt .bag').remove();
				$('.pDetail .buttons').append($('<div />').css({position:'absolute',top:'0px',left:'0px','background-color':'red'}).html('asdf'));
			}
		},
		show:function(){
			a.weblist.show('bag'); // borrow functions from weblist class
		},
		reload:function(){
			// clear contents of the bag preview
			//$('#bag .thumbs').remove();
			
			
			// reload bag preview
			a.weblist.load('bag');
		},
		add:function(){
			var ui = a.product.getUI(), 
				zOn = ui.attrSet1.find('li.on'),
				sOn = ui.attrSet2.find('li.on'),
				img = null,
				params = {},
				newThumb = null,
				thumbList = null,
				qty = (!isNaN(parseInt(ui.qty.val())))?parseInt(ui.qty.val()):0,
				errs = [],
				errStr = '',
				existingThumb = null;
			
			if (sOn.length > 0 && zOn.length > 0 && qty > 0) {
				params = {
					z:zOn.data().id,	
					s:sOn.data().id,
					i:ui.id.html(),
					q:qty,
					t:'bag'
				};
				img = ui.thumbList.find('.on').data().serverFile;
				thumbList = $('#bag .thumbs');
				existingThumb = thumbList.find('.thumb.-s'+params.s+'.-z'+params.z+'.-i'+params.i);
			} else {
				if (sOn.length === 0) {
					errs.push(ui.attrSet2.find('.title .text').html().toLowerCase());	
				}
				if (zOn.length === 0) {
					errs.push(ui.attrSet1.find('.title .text').html().toLowerCase());	
				}
				if (qty === 0) {
					errs.push('quantity');	
				}
				
				errStr += 'Make sure you\'ve selected a valid ';
				$.each(errs,function(i,w){
					if (errs.length > 1 && i === errs.length-1) { errStr += ' and '; }
					else if (errs.length > 1 && i > 0) { errStr += ', '; }
					errStr += w;
				});
				errStr += '.';

				alert(errStr);
				return;
			}
			
			a.product.animateImageTo($('.opt .bag'));
			
			// create a new thumb
			if (existingThumb.length === 0) {
				newThumb = $('<div />').addClass('thumb -i'+params.i+' -s'+params.s+' -z'+params.z).css({width:'0px'}).append(
					$('<div />').addClass('bg')
				).append(
					$('<div />').addClass('img temp')
				);
				thumbList.append(newThumb);
				newThumb.animate({width:'50px'});
			}

			// save to database
			$.post('/cf/ajax/weblist.add.cfm',params,function(j){
				if (j._s !== 'success') { alert(j._s); }											  
															  
				// update existing thumb
				if (existingThumb.length > 0) {
					existingThumb.find('.qty .count').html(j.q);
					if (j.q <= 1) { existingThumb.find('.qty').css({display:'none'}); } // hide quantity if its one
					else { existingThumb.find('.qty').css({display:'block'}); }
					existingThumb.data('Quantity',j.q);
					
				// update new thumb
				} else {
					newThumb.find('.img').append(
						$('<img />').attr({src:'//img.shopwarrens.com/product/130x173/'+img,width:'44',height:'58'})
					);
					newThumb.append(
						$('<div />').addClass('remove')
					).append(
						$('<div />').addClass('qty').append(
							$('<div />').addClass('count').html(j.q)
						)
					);
					if (j.q <= 1) { newThumb.find('.qty').css({display:'none'}); } // hide quantity if its one
					newThumb.data({ProductID:j.p,StyleID:j.s,SizeID:j.z,Quantity:j.q,LinkUrl:j.u});
				}
				$('#bag h1 .amountPreview').html(': '+j.ta);
				a.weblist.applyThumbFns(newThumb);
				a.weblist.updateCount('bag');
			},'json');
		}
	},
	checkout:{
		isComplete:false,
		init:function(){
			// load the items in cart
			a.checkout.loadCart();
			// apply save function to all input fields
			$('#checkout_form input[type=text]').blur(function(){ a.checkout.saveFormToSession(); });
			$('#checkout_form input[type=checkbox]').click(function(){ a.checkout.saveFormToSession(); });
			$('#checkout_form select').not('select[name=ship_province]').change(function(){ a.checkout.loadCart(); });
			$('#checkout_form select[name=ship_province]').change(function(){ a.checkout.saveFormToSession({onComplete:function(){ a.checkout.loadCart(); }}); }); // update cart so we can see accurate taxes
			// enter key for promocodes
			$('#cart_promocode').keyup(function(ev){
				if (ev.keyCode === 13) { a.checkout.applyPromo(); }
			});
			// form validation
			jc.form.init($('#checkout_form'),a.form.onFieldError,a.form.onFieldSuccess);
		},
		// save the form data to the session so its not lost
		saveFormToSession:function(opts){
			var o = $.extend({
					onComplete:function(){}
				},opts);
			
			$.post('/cf/ajax/checkout.save.cfm',$('#checkout_form').serializeArray(),function(){
				if (typeof o.onComplete === 'function') { o.onComplete(); }
			});
		},
		// 
		loadCart:function(action,promo,product){
			var v = (typeof action !== 'undefined')?action:'',
				params = {
					s:$('#cart_shippingOpt').val(),
					p:'',
					a:action
				};
			
			// find the promo code
			if (action === 'removePromo' && typeof promo !== 'undefined') {
				params.p = promo.toUpperCase();
			} else if ($('#cart_promocode').length > 0) {
				params.p = $('#cart_promocode').val().toUpperCase();
			}
			
			// populate product details if present
			if (typeof product != 'undefined') {
				params['pi'] = product.ProductID;
				params['ps'] = product.StyleID;
				params['pz'] = product.SizeID;
				params['pq'] = product.Quantity;
			}
			
			// update totals
			$('.cartScroll').css({opacity:0.5});
			$('#cart-subtotal, #cart-shippingamont, #cart-taxamount, #cart-grandtotal').html('-');
			
			// get the latest data
			$.post('/cf/ajax/checkout.load.cfm',params,function(j){
				var shipping = $('#cart_shippingOpt'),
					itemList = $('#cart_itemlist');
				
				// show promo status
				if (j._s.s === 'fail') {
					alert(j._s.m);
				}
				
				// update bag preview
				a.bag.reload();
				
				// clear current items
				itemList.children().remove();

				// add any cart-wide promos to the top of the list
				/*if (j._c.c !== '') {
					itemList.append(
						$('<tr />').addClass('cart-promo promo').data({'promocode':j._c.c}).append(
							$('<td />').attr({'colspan':3}).html(j._c.n).append(
								$('<div />').addClass('promocode').html(j._c.c).append(
									$('<img />').attr({'src':'/images/promo-remove.gif',width:'9',height:'9',border:'0'}).addClass('remove').click(function(){
										var code = $(this).parents('tr').first().data('promocode');								 
										a.checkout.removePromo(code);
									})
								)
							)
						).append(
							$('<td />').addClass('rgt discountamount').html(j._c.df)
						)
					);
					
					// actions
					itemList.find('img.remove').click(function(){
						var code = $(this).parents('tr').first().data('promocode');								 
						a.checkout.removePromo(code);
					});
				}*/
				
				// update cart list
				$.each(j.b,function(i,e){
					var promoDesc = (e.pr !== '') ? j.p[e.pr].n : '',
						el_r1 = $('<tr />').addClass('cart_item').data({json:e}).append(
								$('<td />').addClass('thumbCol').attr({width:50,rowspan:2}).append(
									$('<div />').addClass('thumb_wrap').append(
										$('<a />').attr({href:e.u}).append(
											$('<img />').attr({src:'//img.shopwarrens.com/product/130x173/'+e.f}).addClass('thumb')
										)
									).append(
										$('<img />').attr({src:'/images/wishlist.remove.png',width:'22',height:'22',border:'0',alt:'Remove item from your cart.'}).addClass('remove')
									)
								)
							).append(
								$('<td />').addClass('noborder').attr({width:125}).append(
									$('<div />').addClass('name').html(e.n+' ('+((e.id === 1)?e.zn:e.sn)+')')
								).append(
									$('<div />').addClass('size').html((e.id === 1)?'Length: '+e.sn:'Size: '+e.zn)
								)
							).append(
								$('<td />').addClass('noborder').attr({width:40}).addClass('ctr').append(
									$('<input />').attr({'type':'text'}).addClass('qty').val(e.q)
								)
							).append(
								$('<td />').addClass('noborder item-price').attr({width:55}).addClass('rgt')
							).append(
								$('<td />').addClass('noborder').attr({width:75}).addClass('rgt').html(e.taf)
							),
						el_r2 = $('<tr />').append(
								$('<td />').addClass('desc').attr({colspan:4}).append(
									$('<div />').addClass('promocode').html(e.pr+'<img src="/images/promo-remove.gif" width="9" height="9" border="0" class="remove" />')
								).append(
									$('<span />').addClass('promodesc').html(promoDesc)
								)
							);						
											
					// set item price & promo status (an item could have a promo code but no promo price as its may be part of a buy 2 get 1 at a discount)
					if (e.pr !== '') {
						el_r1.addClass('promo').data({'promocode':e.pr}).find('.item-price');
						el_r2.addClass('promo').data({'promocode':e.pr}).find('.item-price');
						// promo price
						if (e.pf !== e.paf) {
							el_r1.find('.item-price').append(
								$('<span />').addClass('old-price').html(e.pf)
							).append(
								$('<span />').addClass('new-price').html(e.paf)
							);
						} else {
							el_r1.find('.item-price').append($('<span />').addClass('price').html(e.paf));
						}
					} else {
						el_r1.find('.item-price').append(
							$('<span />').addClass('price').html(e.paf)
						);
					}
					
					// actions
					el_r2.find('.promocode img.remove').click(function(){
						a.checkout.removePromo(e.pr);
					});
					
					el_r1.find('.thumbCol img.remove').click(function(){
						a.checkout.updateQuantity({ProductID:e.i, StyleID:e.s, SizeID:e.z, Quantity:0});
					});
					
					el_r1.find('input.qty').change(function(){
						a.checkout.updateQuantity({ProductID:e.i, StyleID:e.s, SizeID:e.z, Quantity:$(this).val()});
					});
					
					itemList.append(el_r1).append(el_r2);
					
				});
				$('.cartScroll').css({opacity:1});
				
				/*
				<tr>
					<td width="175">
						<a href="##product?i=#ProductID#&s=#StyleID#&z=#SizeID#"><img src="//img.shopwarrens.com/product/130x173/#FirstPhotoServerFile#" class="thumb" /></a>
						<div class="name">#Name#</div>
						<cfif IsDenim>
							<div class="size">Waist: #SizeName#</div>
							<div class="color">Length: #StyleName#</div>
						<cfelse>
							<div class="size">Size: #SizeName#</div>
							<div class="color">Color: #StyleName#</div>
						</cfif>
					</td>
					<td width="40" class="ctr">#Quantity#</td>
					<td width="55" class="rgt">#DollarFormat(Price)#</td>
					<td width="75" class="rgt">#DollarFormat(TotalAmount)#</td>
				</tr>
				*/
				
				// update totals
				$('#cart-subtotal').html(j.t.tf).data({'amount':j.t.t});
				$('#cart-shippingamont').html(j.t.shf).data({'amount':j.t.sh});
				$('#cart-taxamount').html(j.t.txf).data({'amount':j.t.tx});
				$('#cart-grandtotal').html(j.t.taf).data({'amount':j.t.ta});
				
				// update shipping
				shipping.empty();
				$.each(j.s,function(i,e){
					var opt = $('<option />').attr({value:e.i}).html(e.n+' ('+e.taf+')');
					if (e._s === 1) { opt.attr({'selected':'selected'}); }
					shipping.append(opt);
				});
				
			},'json');
		},
		applyPromo:function(){
			a.checkout.loadCart('applyPromo');
			$('#cart_promocode').val('');
		},
		removePromo:function(code){
			a.checkout.loadCart('removePromo',code);
		},
		updateQuantity:function(params){
			a.checkout.loadCart('updateProduct',null,params);
		},
		copyBillToShip:function(){
			$('#ship_firstname').val($('#bill_firstname').val());	
			$('#ship_lastname').val($('#bill_lastname').val());	
			$('#ship_address').val($('#bill_address').val());	
			$('#ship_city').val($('#bill_city').val());	
			$('#ship_province')[0].selectedIndex = $('#bill_province')[0].selectedIndex;
			$('#ship_postalcode').val($('#bill_postalcode').val());	
			$('#ship_phone').val($('#bill_phone').val());	
			$('#ship_email').val($('#bill_email').val());
			$('#ship_email2').val($('#bill_email2').val());
			a.checkout.saveFormToSession();
			a.checkout.loadCart();
		},
		payment:function(opts){
			// fn defaults
			var o = $.extend({
					skipGuestCheck:false
				},opts),
				checkoutLoadTimer = null,
				formData = $('#checkout_form').serializeArray();
			
			// validate form
			if (!jc.form.validate('#checkout_form')) {
				return false;
			}
			
			// signup?
			if (!o.skipGuestCheck && !$(document.body).hasClass('-is-logged-in')) {
				a.checkout.guestDialogShow();
				return;
			}
			
			$('#loading-payment').fadeIn();
			$('#loading-payment .desc').html('CHECKING OUT');
			$('#hostedPaymentPage .iFrameWrap').css({display:'none'});
			checkoutLoadTimer = setInterval(function(){ $('#loading-payment .desc').append('.'); },1000);
			
			// load the final cart data for preview and payments
			$.post('/txn/pre.cfm',formData,function(j){
				
				clearInterval(checkoutLoadTimer);
				$('#loading-payment').stop().fadeOut();
				
				if (j.statusmessage != '') { alert(j.statusmessage); }
				
				// data to submit to the hosted pay page
				var data = {
						// required
						ps_store_id:$('#PS_STORE_ID').val(),
						hpp_key:$('#HPP_KEY').val(),
						charge_total:jc.util.number.dollarFormat(j.amounttocharge),
						// identifiers
						cust_id:j.customerid, 
						order_id:j.orderid
					};
				
				// loop through the custom variables (shipping/billing/weblistid) so we can wrap up the order after the fact
				$.each(j.rnav,function(i,e){ data['rvar_'+i] = e; });
				
				// open dialog
				a.ui.divalog.open('#hostedPaymentPage',null,1);
				
				// show cart preview
				$('#invoice_preview').html(j.carthtml);
				
				if (j.amounttocharge > 0) {
					$('#hostedPaymentPage .iFrameWrap').css({display:'block'});
	
					// a.util.form creates the form and appends it to the DOM, submit() fires the data up to the payment gateway into the iframe, then remove() removes the form from the DOM
					a.util.form({action:$('#PP_URL').val(),method:'post',target:'paypageiframe'},data).submit().remove();
				}
			},'json');
		},
		cancelPayment:function(){
			a.ui.divalog.close('#hostedPaymentPage',null,1);
		},
		iframeFormatting:function(el){
			//console.log(el.scrollHeight);
			// setTimeout(function(){ console.log(el.contentDocument.body.offsetHeight); },4000);
			
			//$(el).css({height:el.scrollHeight});
			//console.log(el);
			//console.log($(el.contentDocument.body).find('table'));
			//$(el.contentDocument).find('.table').css({background:'#f00'});
		},
		onSuccess:function(){
			a.checkout.isComplete = true;
			a.weblist.updateCount('bag');
			// update checkout fields
			/*$('#bill_firstname').val('');
			$('#bill_lastname').val('');
			$('#bill_address').val('');
			$('#bill_city').val('');
			$('#bill_province').val('');
			$('#bill_postalcode').val('');
			$('#bill_phone').val('');
			$('#bill_email').val('');
			$('#bill_email2').val('');
			$('#bill_phone').val('');
			$('#ship_firstname').val('');
			$('#ship_lastname').val('');
			$('#ship_address').val('');
			$('#ship_city').val('');
			$('#ship_province').val('');
			$('#ship_postalcode').val('');
			$('#ship_phone').val('');
			$('#ship_email').val('');
			$('#ship_email2').val('');
			$('#ship_phone').val('');
			
			// now that we've populated all the fields, lets save those values to the session
			a.checkout.saveFormToSession();*/
			
			// refresh bag on the left of checkout screen
			a.checkout.loadCart();
		},
		guestDialogShow:function(){
			a.ui.divalog.open('#divalog_checkout_signup',null,1);
			$('#divalog_checkout_signup_status').css({display:'none'});
			$('#divalog_checkout_signup_form').css({display:'block'});
		},
		guestDialogFinish:function(){
			if (jc.form.validate('#divalog_checkout_signup_form')) {
				$('#divalog_checkout_signup_status').css({display:'block'}).html('Processing...');
				$('#divalog_checkout_signup_form').css({display:'none'});
				
				var params = {
						email:$('#bill_email').val(),
						firstname:$('#bill_firstname').val(),
						lastname:$('#bill_lastname').val(),
						isBasic:($('#divalog_checkout_signup_form_isBasic').attr('checked'))?1:0,
						password:$('#divalog_checkout_signup_form_password').val(),
						isSlice:($('#divalog_checkout_signup_form_isSlice').attr('checked'))?1:0
					};
				
				// if signup required
				if (params.isBasic === 1 || params.isSlice === 1) {
					
					$.post('/cf/ajax/user.signup.cfm',params,function(json){
						if (json.status === 'success') {
							// populate links at top
							$('.sm-links .user .firstname').html(json.result.FIRSTNAME);
							$(document.body).addClass('-is-logged-in');
							a.userFirstName = json.result.FIRSTNAME;
							
							a.checkout.guestDialogClose();
							
						} else if (json.status === 'emailonly') {
							a.checkout.guestDialogClose();
							
						} else {
							a.checkout.guestDialogClose();
						}
					},'json');
				} else {
					a.checkout.guestDialogClose();
				}
			}
		},
		guestDialogClose:function(){
			a.ui.divalog.close('#divalog_checkout_signup');
			a.checkout.payment({skipGuestCheck:true});
		},
		onCreateAccountChange:function(){
			if ($('#divalog_checkout_signup_form_isBasic').attr('checked')) {
				$('#divalog_checkout_signup_form_password_wrap').css({display:'block'})
				$('#divalog_checkout_signup_form_password_wrap input').addClass('required');
			} else {
				$('#divalog_checkout_signup_form_password_wrap').css({display:'none'});	
				$('#divalog_checkout_signup_form_password_wrap input').removeClass('required');
			}
		},
		onGCFocus:function(el,nullStr){
			if ($(el).val() === nullStr) {
				$(el).removeClass('empty');
				$(el).val('');
			}
		},
		onGCBlur:function(el,nullStr){
			if ($.trim($(el).val()) === '') {
				$(el).val(nullStr)
			}
			
			if ($(el).val() === nullStr) {
				$(el).addClass('empty');
			} else {
				$(el).removeClass('empty');
			}
		},
		removeGC:function(sequence){
			var formData = {
					cardNumber: '', // pass a blank card number to clear the card
					cardSequence: sequence
				}; 
					
			$('#invoice_preview').html('Processing.');
			checkoutLoadTimer = setInterval(function(){ $('#invoice_preview').append('.'); },1000);
			$('#hostedPaymentPage .iFrameWrap').css({display:'none'});
			
			// load the final cart data for preview and payments
			$.post('/txn/pre.cfm',formData,function(j){
				
				clearInterval(checkoutLoadTimer);
				
				if (j.statusmessage != '') { alert(j.statusmessage); }
				
				// data to submit to the hosted pay page
				var data = {
						// required
						ps_store_id:$('#PS_STORE_ID').val(),
						hpp_key:$('#HPP_KEY').val(),
						charge_total:jc.util.number.dollarFormat(j.amounttocharge),
						// identifiers
						cust_id:j.customerid, 
						order_id:j.orderid
					};
				
				// loop through the custom variables (shipping/billing/weblistid) so we can wrap up the order after the fact
				$.each(j.rnav,function(i,e){ data['rvar_'+i] = e; });
				
				// show cart preview
				$('#invoice_preview').html(j.carthtml);
				
				if (j.amounttocharge > 0) {
					$('#hostedPaymentPage .iFrameWrap').css({display:'block'});
	
					// a.util.form creates the form and appends it to the DOM, submit() fires the data up to the payment gateway into the iframe, then remove() removes the form from the DOM
					a.util.form({action:$('#PP_URL').val(),method:'post',target:'paypageiframe'},data).submit().remove();
				}
			},'json');
		},
		applyGC:function(sequence){
			var formData = {
					cardNumber: $('#cash_card-gc_cardnumber_0'+sequence).val(),
					cardSequence: sequence
				}; 
			
			if (formData.cardNumber.length < 18) { alert('Invalid cash card number.'); return; }
			
			$('#invoice_preview').html('Processing.');
			checkoutLoadTimer = setInterval(function(){ $('#invoice_preview').append('.'); },1000);
			$('#hostedPaymentPage .iFrameWrap').css({display:'none'});
			
			// load the final cart data for preview and payments
			$.post('/txn/pre.cfm',formData,function(j){
				
				clearInterval(checkoutLoadTimer);
				
				if (j.statusmessage != '') { alert(j.statusmessage); }
				
				// data to submit to the hosted pay page
				var data = {
						// required
						ps_store_id:$('#PS_STORE_ID').val(),
						hpp_key:$('#HPP_KEY').val(),
						charge_total:jc.util.number.dollarFormat(j.amounttocharge),
						// identifiers
						cust_id:j.customerid, 
						order_id:j.orderid
					};
				
				// loop through the custom variables (shipping/billing/weblistid) so we can wrap up the order after the fact
				$.each(j.rnav,function(i,e){ data['rvar_'+i] = e; });
				
				// show cart preview
				$('#invoice_preview').html(j.carthtml);
				
				if (j.amounttocharge > 0) {
					$('#hostedPaymentPage .iFrameWrap').css({display:'block'});
	
					// a.util.form creates the form and appends it to the DOM, submit() fires the data up to the payment gateway into the iframe, then remove() removes the form from the DOM
					a.util.form({action:$('#PP_URL').val(),method:'post',target:'paypageiframe'},data).submit().remove();
				}
			},'json');
		},
		payWithGC:function(){
			$('#invoice_preview').html('Processing Cash Cards.');
			checkoutLoadTimer = setInterval(function(){ $('#invoice_preview').append('.'); },1000);
			$('#hostedPaymentPage .iFrameWrap').css({display:'none'});
			
			// load the final cart data for preview and payments
			$.post('/txn/cashCardOnly.cfm',function(j){
				
				clearInterval(checkoutLoadTimer);
				a.checkout.onSuccess();
				
				// show results
				$('#invoice_preview').html(j.statusHtml);
			},'json');
		}
	},
	util:{
		form:function(attr,params){
			var f = $('<form />').attr(attr).css({display:'none'});
			$.each(params,function(i,e){ $(f).append($('<input />').attr({type:'hidden',name:i,value:e})); });
			$(document.body).append(f);
			return $(f);
		},
		getIframe:function(s){
			return window.frames[s]; 	
		}
	},
	contact:{
		init:function(){
			a.contact.onFollowUpChange();
			jc.form.init($('#contactus-form'),a.form.onFieldError,a.form.onFieldSuccess);
		},
		onFollowUpChange:function(){
			if ($('#contactus-form-followup').val() === 'phone') {
				$('#contactus-form-phone-wrap').css({display:'block'});
				$('#contactus-form-phone').addClass('required');
			} else {
				$('#contactus-form-phone-wrap').css({display:'none'});	
				$('#contactus-form-phone').removeClass('required').val('');
			}	
		},
		submit:function(){
			// if the form validates
			if (jc.form.validate('#contactus-form')) {
				var params = $('#contactus-form').serializeArray();
				$('#contactus-form').css({display:'none'});
				$('#contactus-status').html('Sending...').css({display:'block'});
				$.post('/cf/ajax/contact.cfm',params,function(json){
					if (json.status === 'success') {
						$('#contactus-status').html('Success! Check your email for confirmation.').css({display:'block'});
					} else {
						$('#contactus-status').html('Blast! We didn\t get that message. <a href="javascript:void(0);" onclick="a.contact.tryAgain();">Try again</a>').css({display:'block'});
					}
				},'json');
			}
		},
		tryAgain:function(){
			$('#contactus-form').css({display:'block'});
			$('#contactus-status').css({display:'none'});
		}
	},
	track:{
		ask:function(){
			$('#ordernumber-question').fadeIn(); // fade in ui
		},
		askCancel:function(){
			$('#ordernumber-question-number').val(''); // set the order number field blank
			$('#ordernumber-question').fadeOut(); // fade out ui
		},
		askSubmit:function(){
			var num = $('#ordernumber-question-number').val(); // get the tracking number
			window.open('/track?o='+num); //location = '#track?i='+num; // go to the tracking URL
			a.track.askCancel(); // close the UI
		}
	},
	cashcard:{
		checkBalanceReload:function(){
			$('#cashcard_balancecheck_iframe_wrap').empty().append(
				$('<iframe />').attr({
					 'name':'checkbalance_iframe',
					 'width':'222',
					 'height':'140',
					 'marginheight':'0',
					 'marginwidth':'0',
					 'frameborder':'0',
					 'scrolling':'no',
					 'allowtransparency':'yes',
					 'src':'https://wwws.givex.com/public/balance/balancecheck.py?5519'
				})
			);
		},
		chooseType:function(amount){
			$('#divalog_cashcard_choice_amount').val(amount);
			$('#divalog_cashcard_choice .dlg-hdr').html('$'+amount+' Cash Card');
			a.ui.divalog.open('#divalog_cashcard_choice',function(){},1);
		},
		addToBag:function(){
			var data = {
					'25':{productid_card:17981,productid_online:17982,styleid:2206,sizeid:506,img:'P17981_BA33523.jpg'},
					'50':{productid_card:17985,productid_online:17986,styleid:2208,sizeid:506,img:'P17985_35A9405.jpg'},
					'100':{productid_card:17979,productid_online:17980,styleid:2205,sizeid:506,img:'P17979_3677BD6.jpg'},
					'250':{productid_card:17983,productid_online:17984,styleid:2207,sizeid:506,img:'P17983_7FADBF2.jpg'}
				}[$('#divalog_cashcard_choice_amount').val()+''],
				isecard = ($('#divalog_cashcard_choice input[name=isecard]:checked').val() === '1'),
				params = {
					z:data.sizeid,	
					s:data.styleid,
					i:(isecard)?data.productid_online:data.productid_card,
					q:$('#divalog_cashcard_choice_quantity').val(),
					t:'bag'	
				},
				img = data.img,
				thumbList = $('#bag .thumbs'),
				newThumb = null,
				existingThumb = thumbList.find('.thumb.-s'+params.s+'.-z'+params.z+'.-i'+params.i);
			
			// quick add so you see it in the bag asap
			// create a new thumb
			if (existingThumb.length === 0) {
				newThumb = $('<div />').addClass('thumb -i'+params.i+' -s'+params.s+' -z'+params.z).css({width:'0px'}).append(
					$('<div />').addClass('bg')
				).append(
					$('<div />').addClass('img temp')
				);
				thumbList.append(newThumb);
				newThumb.animate({width:'50px'});
			}
			
			// save to database
			$.post('/cf/ajax/weblist.add.cfm',params,function(j){
				// update existing thumb
				if (existingThumb.length > 0) {
					existingThumb.find('.qty .count').html(j.q);
					if (j.q <= 1) { existingThumb.find('.qty').css({display:'none'}); } // hide quantity if its one
					else { existingThumb.find('.qty').css({display:'block'}); }
					existingThumb.data('Quantity',j.q);
					
				// update new thumb
				} else {
					newThumb.find('.img').append(
						$('<img />').attr({src:'//img.shopwarrens.com/product/130x173/'+data.img,width:'44',height:'58'})
					);
					newThumb.append(
						$('<div />').addClass('remove')
					).append(
						$('<div />').addClass('qty').append(
							$('<div />').addClass('count').html(j.q)
						)
					);
					if (j.q <= 1) { newThumb.find('.qty').css({display:'none'}); } // hide quantity if its one
					newThumb.data({ProductID:j.p,StyleID:j.s,SizeID:j.z,Quantity:j.q,LinkUrl:j.u});
				}
				$('#bag h1 .amountPreview').html(': '+j.ta);
				a.weblist.applyThumbFns(newThumb);
				a.weblist.updateCount('bag');
			},'json');
			
			a.ui.divalog.close('#divalog_cashcard_choice');
		}
	}
};

a.nav.manageSSL();

$(document).ready(function(){ a.init(); });
