var TOUCH_DEVICE = !!('ontouchstart' in window);

$(document).ready(function() {
	
	//var PROFILE_START = (new Date()).getTime();//PROFILING INIT TIME
	var header = new PiiqHeader(), f, families = {};
	
	if($('body').hasClass('team_detail')){ setupTeamListDetail(); } //marking the current page in the detail team member list
	
	if($('.heroCarousel').length){
		var phc = new PiiqHeroCarousel('.heroCarousel');
		$('.module.variable').each(function(){ new VariableModule(this, phc); });
	}
	
	$('.piiqModule').each(function(){ new PiiqModule(this); });//piiq modules with corner notches, icons, and rollover states 
		
	$('.cw_module').each(function(){ new ColorwayModule(this); }); //colorway modules
	
	$('.module.piiq_pairs').each(function(){ new PiiqPairs(this); }); //filter roller for the piiq pairs modules
	
	$('#partners').children('li').each(function(){ new PartnersModule(this); }); //piiq partners list
	
	$('#site_nav .dd').each(function(){ new PiiqDropDown(this); }); //dropdown
	
	$('#site_nav #site_nav_prod .dd').each(function(){ new ProductDD(this); }); //product dropdown
	
	$('#site_nav #site_nav_team .dd').each(function(){ new TeamDD(this); }); //team dropdown
	
	$('.basicSlider').each(function(){ new SliderModule(this); });
	
	$(".sportNav li a").each(function() {
		$(this).append($("span", this).clone().addClass("highlight"));
		$(this).hasClass("selected") && $(this).addClass("hover");
	});
	
	if(!TOUCH_DEVICE) {
		$(".sportNav li a").hover(
			function() {
				$(".sportNav li a.hover").removeClass("hover");
				$(this).addClass("hover");
			},
			function() {
				$(this).removeClass("hover");
				$(".sportNav li a.selected").addClass("hover");
			}
		);
	}
	
	if ($('.newsArchiveList').length) {
		new PiiqNewsControl('.newsArchiveList', '.newsDetailContent', '.newsDetail');
	}
	
	if($('.productLandBox').length) {
		$('.productLandBox').each(function() {
			var famName = $(this).data("family");
			if(!!families[famName]) {
				families[famName].push(this);
			} else {
				families[famName] = [this];
			}
		});
		
		for(f in families) {
			(new PiiqProductLandingFamily(families[f]));
		}
	}
	
	if ($('.productCarousel').length) {
		new PiiqProductDetail('.productCarousel');
	}
	
	//PROFILING INIT TIME
	//var PROFILE_END = (new Date()).getTime();
	//console.log('Init Time: ' + (PROFILE_END - PROFILE_START) + 'ms');
});



var GreyScaler = function($el, filter){
	var t = this;
	t.$el = $el;
	t.filter = filter || "none";
	t.img = new Image();
	t.img.onload = function() { t.render(); };
	t.img.src = $el.attr("src");
}
GreyScaler.prototype.render = function(){
	var t = this;
	t.w = t.$el.width();
	t.h = t.$el.height();
	
	if(document.createElement("canvas").getContext && t.canvas == null){
		var c, px, y, xm, i, avg;
		t.canvas = $('<canvas/>').attr({'class' : 'gs', 'width':t.w, 'height':t.h}).insertAfter(t.$el);
		c = t.canvas.get(0).getContext('2d');
		c.clearRect(0, 0, this.w, this.h);
		c.drawImage(this.img, 0, 0, this.w, this.h);
		px = c.getImageData(0, 0, this.w,this.h);

		for(y = 0; y < px.height; y++){
			for(x = 0; x < px.width; x++){
				i = (y * 4) * px.width + x * 4;
				avg = (
				(0.2989 *px.data[i]) + 
				(0.5870 * px.data[i + 1]) + 
				(0.1140 * px.data[i + 2])
				);
				
				switch(t.filter) {
					case "quad": avg = (function(v) {v /= 127.5; return (v < 1) ? (127.5*v*v) : (-127.5 * ((v-1)*(v-3) - 1));})(avg); break;
					case "circ": avg = (function(v) { v /= 127.5; return (v < 1) ? (-127.5 * (Math.sqrt(1 - v*v) - 1)) : (127.5 * (Math.sqrt(1 - (v-2)*(v-2)) + 1));})(avg); break;
					case "sine": avg = (function(v) { return -255/2 * (Math.cos(Math.PI*v/255) - 1); })(avg); break;
				}

				px.data[i] = avg; 
				px.data[i + 1] = avg; 
				px.data[i + 2] = avg;
			}
		}

		c.putImageData(px, 0, 0, 0, 0, px.width, px.height);
	} else {
		t.canvas = t.$el.clone();
		t.canvas.addClass('gs ie').insertAfter(t.$el).css('background', '#fff');
		t.canvas.get(0).style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)';
	}
		
	t.$el.css('visibility', 'hidden');
}

var SliderModule = function(el){
	var t = this;
	$.extend(t, {
		$el : $(el),
		lBtn : $('<div/>', {'class' : 'btn left'}),
		rBtn : $('<div/>', {'class' : 'btn right'}),
		curInd : 0,
		dur : 300,
		animating : false,
		hasThumbs : false,
		easingMethod : 'easeOutExpo',
		thumbMods : []
	});
	
	t.ul = t.$el.children('ul').eq(0);
	t.lis = t.ul.children('li');
	t.lw = t.lis.eq(0).width();
	t.btns = t.lBtn.add(t.rBtn);
	
	//setup
	if(t.lis.length > 1){
		t.ul.width(t.lw * t.lis.length);
		t.lBtn.appendTo(t.$el).bind('click', function(e){e.preventDefault(); t.onBtnClick('left')});
		t.rBtn.appendTo(t.$el).bind('click', function(e){e.preventDefault(); t.onBtnClick('right')});
		
		if(!TOUCH_DEVICE) {
			t.btns.hide();
			if($.support.opacity){
				t.btns.bind({
					mouseenter : function(e){$(e.target).fadeTo(100, 1)},
					mouseleave : function(e){$(e.target).fadeTo(100, .7)}
				});
			}
			t.$el.hoverIntent({
				over:function(){t.onOver()},
				out:function(){t.onOut()},
				interval:0,
				timeout:200
			});
		} else {
			t.btns.show();
		}
		
		if(t.ul.find('.thumbnail').length){
			var ul = $('<ul/>', {'class':'thumbList'});
			t.ul.find('.thumbnail').each(function(i){
				var li = $('<li/>');
				var a = $('<a class="piiqModule" data-linkStroke="#404142" data-notch="0" href="#'+ i +'"/>');
				a.bind('click', function(e){
					e.preventDefault();
					e.stopPropagation();
					t.slideTo(i)
				}).append($(this))
				li.append(a).appendTo(ul);
			});
			
			t.$el.append(ul);
			ul.find('li a').each(function(){t.thumbMods.push(new PiiqModule(this))});
			t.hasThumbs = true;
			t.thumbMods[0].showStroke();
			t.thumbMods[0].$el.addClass("selected");
		}
		
	}
	
	t.checkForVideo(false);
}
SliderModule.prototype.onBtnClick = function(dir){
	var t = this, goTo;
	
	goTo = dir === "left" ? t.curInd-1 : t.curInd+1;
	
	if(goTo !== t.currInd && !t.animating){
		t.slideTo(goTo, dir);
	}
}
SliderModule.prototype.onOver = function(){
	$.support.opacity ? this.btns.fadeTo(100, .7) : this.btns.show();
}
SliderModule.prototype.onOut = function(){
	$.support.opacity ? this.btns.fadeTo(100, 0) : this.btns.hide();
}
SliderModule.prototype.slideTo = function(num, dir){
	var t = this, clones = false, liLen = t.lis.length, diff = (num - t.curInd)%liLen, allWd = liLen * t.lw, i, th;
	
	dir = dir === "left" || dir === "right" ? dir : diff < 0 ? "left" : "right";
	if(!t.animating) {
		t.animating = true;
		
		t.clearVideo();
	
		if(dir === "left" && num < 0) {
			clones = t.lis.clone();
			t.ul.append(clones).css("marginLeft", allWd*-1).width(allWd*2);
		}
		if(dir === "right" && num >= liLen) {
			clones = t.lis.clone();
			t.ul.prepend(clones).css("marginLeft", (allWd*-1)+t.lw).width(allWd*2);
		}
	
		t.ul.animate({'marginLeft': '-='+(diff*t.lw)}, {duration:t.dur, easing:t.easingMethod});
		$.when(t.ul).always(function() {
			var mLeft;
		
			t.curInd = (num+liLen)%liLen;
			if(!!(clones)) {
				clones.remove();
				dir === "right" && t.ul.css("marginLeft", '+='+allWd);
				t.ul.width(allWd);
			}
		
			t.checkForVideo(true);
			
			t.animating = false;
		});
	
		if(t.hasThumbs){
			for(i=0;i< t.thumbMods.length;i++){
				th = t.thumbMods[i];
				if(i === (num+liLen)%liLen){
					th.showStroke();
					th.$el.addClass('selected');
				}else if(th.$el.hasClass('selected')){
					th.hideStroke();
					th.$el.removeClass('selected');
				}
			}
		}
	}
	

}
SliderModule.prototype.checkForVideo = function(autoPlay) {
	var t = this, currentListItem = $(t.lis[t.curInd]), imgs = currentListItem.find('img');
	
	if (!(swfobject.hasFlashPlayerVersion('10.0.0'))) { return false };
	
	imgs.each(function(index, element) {
		var el = $(element);
        if (typeof(el.data('video')) != 'undefined') {
			t.showVideo(el.data('video'), autoPlay, $(element).attr('src'));
		}
    });
	
}
SliderModule.prototype.showVideo = function(videoUrl, autoPlay, posterUrl) {
	var t = this, currentListItem = $(t.lis[t.curInd]), videoContainer = $('<div />').attr('class', 'videoContainer'), replacedDiv = $('<div />').attr('id', 'piiqVideo');
	
	currentListItem.append(videoContainer);
	videoContainer.append(replacedDiv);
	
	new PiiqVideoPlayer('piiqVideo', videoUrl, autoPlay, posterUrl);
	
}
SliderModule.prototype.clearVideo = function() {
	var t = this, currentListItem = $(t.lis[t.curInd]);
	
	currentListItem.find('.videoContainer').each(function(index, element) {
		$(element).detach();
	});
}

var PiiqHeroCarousel = function(el){
	var t = this;
	
	$.extend(t, {
		$el : $(el),
		stages : [],
		lBtn : $('<span />').attr('class', 'btn left'),
		rBtn : $('<span />').attr('class', 'btn right'),
		curInd : 0,
		dur : 300,
		easeType : 'easeOutQuad',
		category : null,
		navItems : []
	});
	
	t.lis = t.$el.children('ul').children('li');
	t.stageImgs = t.$el.find('.stageImage');
	t.btns = $(t.lBtn).add(t.rBtn);
	
	t.stageImgs.each(function(i){
		var _t = $(this), stg = $('<div/>').attr('class', 'stage');
		stg.css('background-image', 'url('+_t.attr('src')+')').appendTo(t.$el);
		
		t.stages.push(stg);
		if(i != 0){
			stg.hide();
		}
	}).detach();
	
	t.$el.append($('<div/>').attr('class', 'overlay'));
	
	
	if(t.stageImgs.length > 1){
		t.$el.append(this.lBtn, this.rBtn);
		t.lBtn.bind('click', function(e){e.preventDefault(); t.onButtonClick('left')});
		t.rBtn.bind('click', function(e){e.preventDefault(); t.onButtonClick('right')});
		if(!TOUCH_DEVICE) {	
			t.$el.bind({
				mouseenter : function(){t.onOver();},
				mouseleave : function(){t.onOut();}
			});
			t.btns.hide().bind({
				mouseenter : function(){ $(this).fadeTo(100, 1);},
				mouseleave : function(){ $(this).fadeTo(100, .7);}
			});
		}
		t.createCarouselNav();
		
		t.slideTo(0, 'right');
	}

}
PiiqHeroCarousel.prototype.createCarouselNav = function(){
	
	var t = this;
	
	var container = $('<div />', {"class": 'carouselNavContainer'});
	t.$el.append(container);
	
	var navList = $('<ul />', {"class": 'carouselNav'});
	container.append(navList);
	
	t.lis.each(function(index, element) {
		
		var li = $('<li />');
		li.appendTo(navList);
		
		var a = $('<a/>', {"href":"#"}).appendTo(li);
		
		var img = $('<span />', {"class": $(element).data('icon')}).appendTo(a);
		
		a.bind('click', function(e){
			e.preventDefault();
			e.stopPropagation();
			t.navItemClick(index);
		});
		
		t.navItems.push(new PiiqModule(a, 0));
		
	});
	
}
PiiqHeroCarousel.prototype.navItemClick = function(index){
	var t = this, prevInd = t.curInd;
	
	t.curInd = index;
	
	(prevInd !== t.curInd) && t.slideTo(t.curInd, t.curInd < prevInd ? 'left' : 'right');
}
PiiqHeroCarousel.prototype.onButtonClick = function(dir) {
	var t = this, prevInd = t.curInd;
	dir = dir || "right";
	switch(dir){
		case 'left':
			t.curInd = t.curInd > 0 ? t.curInd-1 : t.lis.length-1;
		break;
		case 'right':
			t.curInd = t.curInd < t.lis.length -1 ? t.curInd+1 : t.curInd = 0;
		break;
	}
	
	(prevInd !== t.curInd) && this.slideTo(t.curInd, dir);
}
PiiqHeroCarousel.prototype.onOver = function(){
	$(this.rBtn).add(this.lBtn).fadeTo(100, .7);
}
PiiqHeroCarousel.prototype.onOut = function(){
	$(this.rBtn).add(this.lBtn).fadeTo(100, 0);
}
PiiqHeroCarousel.prototype.slideTo = function(ind, dir){
	var t = this, i, thumb;
	dir = dir || "right";
	
	for(i=0; i< t.stages.length;i++){
		thumb = t.navItems[i];
		if(i==ind){
			t._in(i, dir);
			thumb.$el.addClass('selected');
			thumb.overColor = '#989898';
			thumb.showStroke();
		}else{
			t._out(i, dir);
			thumb.$el.removeClass('selected');
			thumb.overColor = '#00bcd4';
			thumb.hideStroke();
		}
	}
	t.category = t.lis.eq(ind).data('category');
	t.$el.trigger('carouselchanged');
}
PiiqHeroCarousel.prototype._out = function(i, dir){
	var t = this, theMargin = dir === 'left' ? '120px' : '-120px';
	t.stages[i].animate({
		'margin-left' : theMargin
	}, {queue:false, easing:t.easeType}).fadeOut(t.dur);
	t.lis.eq(i).fadeOut(t.dur);
}
PiiqHeroCarousel.prototype._in = function(i, dir){
	var t = this, theMargin = dir === 'left' ? '-120px' : '120px';
	t.stages[i].css({
		'marginLeft' : theMargin
	}).animate({
		'margin-left':0
	}, {queue:false, easing:t.easeType}).fadeIn(t.dur);
	t.lis.eq(i).fadeIn(t.dur);
}

var VariableModule = function(el, master){
	var t = this;
	$.extend(t, {
		$el : $(el),
		master : master,
		dur : 450,
		conts : $(el).find(".content")
	});
	
	t.master.$el.bind('carouselchanged', function(e){
		t.change(t.master.category);
	});
}
VariableModule.prototype.change = function(term){
	var t = this
	var tw = t.$el.width();
	var th = t.$el.height();
	var dw = Math.ceil(tw * Math.sqrt(2));
	var dh = Math.ceil(th * Math.sqrt(2));
	var washHold = $('<div/>').attr('class', 'washHold');
	washHold.width(tw).height(th).appendTo(t.$el);
	var r = Raphael(washHold.get(0), tw, tw);
	var s = r.image('assets/img/transition_diag_pattern_trans.png', 0, 0, tw, th).attr({
		'stroke' : 0,
		'rotation' : '45',
		'translation' : tw+' '+(th*-1),
		'scale' : 1.4
	}).animate({
		'translation' : (tw*-2)+' '+(th*2)
	}, t.dur, function(){
		washHold.remove();
	});
	t.conts.each(function(){
		var _t = $(this);
		setTimeout((_t.data('category') === term) ? function(){_t.show()} : function(){_t.hide()}, t.dur/2);
	});
}

var PiiqModule = function(el, argNotch, argNotchStroke, argIcon){
	var t = this, fCo, fOpac = 1, sCo, sOpac = 1, r;
	
	$.extend(t, {
		$el : $(el),
		ew : $(el).width(),
		eh : $(el).height(),
		dur : 100
	});
	
	t.$el.data("piiqModuleRef", t);
	
	typeof argNotch !== "undefined" && t.$el.data('notch', argNotch);
	typeof argNotchStroke !== "undefined" && t.$el.data('notchStroke', argNotchStroke);
	typeof argIcon !== "undefined" && t.$el.data('icon', argIcon);
	
	t.hasNotch = !(t.$el.data('notch') == null);
	t.hasNotchStroke = !(t.$el.data('notchStroke') === false);
	t.hasIcon = t.$el.data('icon');
	t.isLink = t.$el.is('a');
	
	// set-up notch
	if(t.hasNotch){ 
		t.rHold = $('<div>', {'class': 'rHold'}).appendTo(t.$el);
		
		t.rh = t.rHold.height();
		t.rw = t.rHold.width();
		
		if(t.rw >= t.ew) {
			t.isMini = true;
			t.rHold.addClass("mini");
		}
		
		t.triColor = t.$el.data('notch');
		if(t.triColor === 0) {
			fCo = "#f9f9f9";
			fOpac = 0;
		} else {
			fCo = t.triColor;
		}
		
		t.tStrokeColor = !(t.$el.data("notchstroke") == null) ? t.$el.data("notchstroke") : 0;
		if(t.tStrokeColor === 0) {
			sCo = "#f9f9f9";
			sOpac = 0;
		} else {
			sCo = t.tStrokeColor;
		}
		
		var ts = t.isMini ? '13' : '60';
		
		r = Raphael(this.rHold.get(0));
		t.triangle = r.path('M0 0L'+ts+' 0L'+ts+' '+ts+'L0 0').attr({
			"fill" : fCo,
			"fill-opacity" : fOpac,
			'stroke' : 0
		});
		
		t.tStroke = r.path('M0 0L'+ts+' '+ts).attr({
			'stroke' : sCo,
			'stroke-opacity' : sOpac
		});
	}
	
	//set up link
	if(t.isLink){
		
		t.overColor = t.$el.data('linkStroke') == null ? '#00bcd4' : t.$el.data('linkStroke');
		t.sHold = $('<div>', {'class': 'sHold'});
		if(!t.$el.children('.sHold').length){
			t.$el.append(t.sHold);
		}	
		r = Raphael(t.sHold.get(0), t.ew, t.eh);
		
		if(!TOUCH_DEVICE) {
			t.$el.bind({
				mouseenter : function(){t.onOver()},
				mouseleave : function(){t.onOut()}
			});
		}

		var sWidth;
		if(t.ew < 100){
			t.sWidth = 8;
		}else if(t.ew < 200){
			t.sWidth = 12;
		}else{
			t.sWidth = 16;
		}
		
		t.stroke = r.path('M0 0L'+t.ew+' 0L'+t.ew+' '+t.eh+'L0 '+t.eh+'L0 0').attr({
			'stroke':t.overColor,
			'stroke-width':0,
			'stroke-opacity':0
		});
	}
	
	// set up icon
	if(t.hasIcon){
		t.iHold = $('<div>', {'class': 'iHold'}).appendTo(t.$el);
		$("<span/>", {"class" : !!t.$el.data('icon') ? t.$el.data('icon') : "" }).appendTo(t.iHold);
	}
	
	if(t.$el.hasClass('selected')){
		t.showStroke();
	}
	
	return this;
}
PiiqModule.prototype.onOver = function(){
	!this.$el.hasClass('selected') && this.showStroke();
}
PiiqModule.prototype.onOut = function(){
	!this.$el.hasClass('selected') && this.hideStroke();
}
PiiqModule.prototype.showStroke = function(){
	var t = this;
	t.stroke.stop();
	t.stroke.attr('stroke-opacity', 1);
	t.stroke.animate({
		'stroke':t.overColor,
		'stroke-width':t.sWidth
	}, t.dur);
	
	t.hasNotch && t.changeNotchColor(t.overColor);
}
PiiqModule.prototype.hideStroke = function(){
	var t = this;
	t.stroke.stop();
	t.stroke.animate(
		{
			'stroke':t.overColor,
			'stroke-width':0
		},
		t.dur,
		function() {
			t.stroke.attr({'stroke-opacity':0});
		}
	);
	
	t.hasNotch && t.changeNotchColor(t.triColor, t.tStrokeColor);
}
PiiqModule.prototype.changeNotchColor = function(fillColor, strokeColor){
	var t = this, fillOpacity = 1, strokeOpacity = 1, curFillColor, curFillOpacity, curStrokeColor, curStrokeOpacity;
	
	switch(arguments.length) {
		case 1:
			strokeColor = fillColor;
			break;
		case 0:
			fillColor = t.triColor;
			strokeColor = t.tStrokeColor;
			break;
	}
	
	curFillColor = t.triangle.attr("fill");
	curFillOpacity = t.triangle.attr("fill-opacity");
	curStrokeColor = t.tStroke.attr("stroke");
	curStrokeOpacity = t.tStroke.attr("stroke-opacity");
	
	if(fillColor === 0) {
		fillOpacity = 0;
		fillColor = curFillColor;
	} else if(curFillOpacity === 0) {
		t.triangle.attr("fill", fillColor);
	}
	if(strokeColor === 0) {
		strokeOpacity = 0;
		strokeColor = curStrokeColor;
	} else if(curStrokeOpacity === 0) {
		t.tStroke.attr("stroke", strokeColor);
	}
	
	t.triangle.stop();
	t.tStroke.stop();
	
	t.triangle.animate({
		"fill" : fillColor,
		"fill-opacity" : fillOpacity
	}, t.dur);
	
	t.tStroke.animateWith(t.triangle, {
		"stroke" : strokeColor,
		"stroke-opacity" : strokeOpacity
	}, t.dur);
	
}

var ColorwayButton = function(el){
	var t = this, $el = $(el), r;
	
	$.extend(
		t,
		{
			$el : $el,
			ew : $el.width(),
			eh : $el.height(),
			color1 : '#'+$el.data('colorway').split(',')[0],
			color2 : '#'+$el.data('colorway').split(',')[1],
			downOffset : 12,
			dur : 200,
			ease : "<",
			selected : false
		},
		{
			//some shape path strings
			bhString : "M0 10L17 0L35 10L35 30L17 40L0 30L0 10",
			flString : "M2 11L17 2L17 38L2 29L2 11",
			tlString : "M2 11L17 2L17 19L2 11",
			frString : "M17 19L35 11L35 30L17 40",

			// the over-state paths
			bhStringOver : "M0 12L17 2L35 12L35 30L17 40L0 30L0 10",
			flStringOver : "M2 13L17 4L17 38L2 29L2 13",
			tlStringOver : "M2 14L17 4L17 21L2 13",
			frStringOver : "M17 21L35 13L35 30L17 40",
	
			// the down-state paths
			bhStringDown : "M0 22L17 12L35 22L35 30L17 40L0 30L0 10",
			flStringDown : "M2 24L17 14L17 38L2 29L2 24",
			tlStringDown : "M2 24L17 14L17 31L2 23",
			frStringDown : "M17 32L35 23L35 30L17 40"
		}
	);

	r = Raphael(el, t.ew, t.eh);


	
	// create the actual path objects
	t.baseHex = r.path(t.bhString).attr({
		"fill" : t.color2,
		"stroke" : 0
	});
	t.frontLeft = r.path(t.flString).attr({
		"fill" : t.color1,
		"stroke" : 0
	});
	t.topLeft = r.path(t.tlString).attr({
		"fill" : "#000",
		"stroke" : 0,
		"opacity" : .1
	});
	t.frontRight = r.path(t.frString).attr({
		"fill" : "#000",
		"stroke" : 0,
		"opacity" : .15
	});
	
	if(!TOUCH_DEVICE) {		
		t.$el.hover(
			function(){ t.selected === false && t.goOver(); },
			function(){ t.selected === false && t.comeUp();	}
		);
	}
}
ColorwayButton.prototype.goOver = function(){
	var t = this;
	
	t.frontLeft.animate({"path" : t.flStringOver}, t.dur/4);
	t.baseHex.animate({"path" : t.bhStringOver}, t.dur/4);
	t.frontRight.animate({"path" : t.frStringOver}, t.dur/4);
	t.topLeft.animate({"path" : t.tlStringOver}, t.dur/4);
	
	t.$el.addClass('over');
}
ColorwayButton.prototype.goDown = function(){
	var t = this;
	
	t.frontLeft.animate({"path" : t.flStringDown}, t.dur);
	t.baseHex.animate({"path" : t.bhStringDown}, t.dur);
	t.frontRight.animate({"path" : t.frStringDown}, t.dur);
	t.topLeft.animate({"path" : t.tlStringDown}, t.dur);
	
	t.selected = true;
	t.$el.addClass('selected').removeClass('over');
}
ColorwayButton.prototype.comeUp = function(){
	var t = this;
	var topOff = t.$el.hasClass('over') ? 3 : t.downOffset;
	
	t.frontLeft.animate({"path" : t.flString}, t.dur);
	t.baseHex.animate({"path" : t.bhString}, t.dur);
	t.frontRight.animate({"path" : t.frString}, t.dur);
	t.topLeft.animate({"path" : t.tlString}, t.dur);
	
	t.selected = false;
	t.$el.removeClass('selected').removeClass('over');
}

var ColorwayModule = function(el){
	var t = this;
	
	$.extend(t, {	
		$el : $(el),
		images : $(el).find('ul.images li'),
		cwButtons : [],
		dur : 200,
		easeOnScreen : "easeOutExpo",
		easeOffScreen : "easeInExpo",
		currentImage : 0,
		animating : false
	});
	
	t.$el.find('.cw_buttons a').each(function(i){
		t.cwButtons.push(new ColorwayButton(this));
		$(this).bind('click', function(e){
			e.preventDefault();
			e.stopPropagation();
			if(!$(this).hasClass('selected')){
				t.buttonClicked(i);
			}
		});
	});
	
	t.buttonClicked(0);
}
ColorwayModule.prototype.buttonClicked = function(ind){
	var t = this, i, btn;
	
	if(!t.animating) {
		t.animating = true;
		for(i=0; i < t.cwButtons.length;i++){//put the button down and switch the image
			btn = t.cwButtons[i];
			if(i === ind){
				btn.goDown();
				t.switchImages(ind);
				$('p.colorway span').text(btn.$el.attr('href').substring(1));			
			}else if(btn.selected === true){//bring the currently selected button up
				btn.comeUp();
			}
		}
	}
}
ColorwayModule.prototype.switchImages = function(ind){
	var t = this;
	
	t.images.eq(t.currentImage).animate({top:440}, t.dur, t.easeOffScreen);
	
	$.when(t.images.eq(t.currentImage)).always(function() {
		t.images.eq(ind).animate({top:48}, t.dur, t.easeOnScreen);
		$.when(t.images.eq(ind)).always(function() { t.animating = false; });
		t.currentImage = ind;
	});
}

var PiiqPairs = function(el) {
	var th = this, itemCount = 0, $cats;
	
	$.extend(
		th,
		{
			$els : { module : $(el), buttons : {} },
			curCatIndex : 0,
			curItemIndex : 0,
			isAnimating : false,
			transitionDur : 400,
			categories : [],
			categoryPages : [],
			itemPages : []
		}
	);
	
	th.$els.catWindow = $("<div/>", {"class":"catWindow"}).appendTo(th.$els.module);
	th.$els.catTray = $("<ul/>", {"class":"catTray"}).appendTo(th.$els.catWindow);
	
	th.$els.itemWindow = $("<div/>", {"class":"itemWindow"}).appendTo(th.$els.module);
	th.$els.itemTray = $("<ul/>", {"class":"itemTray"}).appendTo(th.$els.itemWindow);
	
	// Pull products out
	var $cats = th.$els.module.find(".pairs").children("li");
	$cats.each(function() {
		var products = $(this).find(".products").children("li");
		th.categories.push(new PiiqPairsCategory($(this), itemCount));
		itemCount += products.length;
		products.find("*:not(img)").remove();
		products.appendTo(th.$els.itemTray);
	}).remove();
	$cats.find("*:not(img)").remove();
	$cats.appendTo(th.$els.catTray);
	
	th.catHt = th.$els.catTray.find("li").eq(0).outerHeight(true);
	th.itemHt = th.$els.itemTray.find("li").eq(0).outerHeight(true);
	
	th.$els.buttons.randomizeFake = $("<span/>", {"class":"randomButtonFake"}).appendTo(th.$els.module);
	(Raphael(th.$els.buttons.randomizeFake.get(0), 108, 108)).circle(54, 54, 53).attr({fill:"#edb122", stroke:0});
	th.$els.buttons.randomizeFake.append($("<span/>"));
	
	th.$els.buttons.randomize = $("<span/>", {
		"class" : "randomButton",
		"click" : function() { th.randomize(); }
	}).appendTo(th.$els.module);
	(Raphael(th.$els.buttons.randomize.get(0), 108, 108)).circle(54, 54, 54).attr({fill:"#00c7df", stroke:0});
	th.$els.buttons.randomize.append($("<span/>"));
	if(!TOUCH_DEVICE) {
		th.$els.buttons.randomize.children().hide();
		th.$els.buttons.randomize.bind({
			"mouseenter" : function() { $(this).children().show(); },
			"mouseleave" : function() { $(this).children().hide(); }
		});
	}
	
	th.$els.buttons.categoryUp = $("<span/>", {
		"class" : "button up",
		"click" : function() { !$(this).hasClass("disabled") && th.turnTo(th.curCatIndex-1, 0); }
	}).appendTo(th.$els.catWindow);
	th.$els.buttons.categoryDown = $("<span/>", {
		"class" : "button down",
		"click" : function() { !$(this).hasClass("disabled") && th.turnTo(th.curCatIndex+1, 0); }
	}).appendTo(th.$els.catWindow);
	
	th.$els.buttons.itemUp = $("<span/>", {
		"class" : "button up",
		"click" : function() { !$(this).hasClass("disabled") && th.turnTo(th.curCatIndex, th.curItemIndex-1); }
	}).appendTo(th.$els.itemWindow);
	th.$els.buttons.itemDown = $("<span/>", {
		"class" : "button down",
		"click" : function() { !$(this).hasClass("disabled") && th.turnTo(th.curCatIndex, th.curItemIndex+1); }
	}).appendTo(th.$els.itemWindow);
	
	th.$els.categoryPages = $("<div/>", {"class" : "pagination"}).appendTo(th.$els.catWindow);
	th.$els.itemPages = $("<div/>", {"class" : "pagination"}).appendTo(th.$els.itemWindow);
	
	th.$els.categoryTitle = $("<h4/>").appendTo(th.$els.catWindow);
	th.$els.itemTitle = $("<h4/>").appendTo(th.$els.itemWindow);
	th.$els.itemLink = $("<a/>", {"class":"productLink", "href":"#", "text":"View Product Online", "target": "_blank"}).appendTo(th.$els.itemWindow);
	th.$els.itemLogo = $("<img/>", {"class":"productLogo", "src":""}).appendTo(th.$els.itemWindow);
	
	
	th.updateUI();
};
PiiqPairs.prototype.turnTo = function(catIndex, itemIndex) {
	var th = this, catTop, itemTop;
	
	catIndex = (catIndex+th.categories.length)%th.categories.length;
	itemIndex = (itemIndex+th.categories[catIndex].items.length)%th.categories[catIndex].items.length;
	if(!th.isAnimating && (catIndex !== th.curCatIndex || itemIndex !== th.curItemIndex)) {
			
			th.isAnimating = true;
			
			// Set current
			th.curCatIndex = catIndex;
			th.curItemIndex = itemIndex;
			
			// Determine new margin values
			catTop = th.catHt * catIndex * -1;
			itemTop = th.itemHt * (th.categories[catIndex].itemOffset + itemIndex) * -1;
			
			// Animate
			th.$els.catTray.animate({top : catTop}, th.transitionDur, 'easeInOutBack');
			th.$els.itemTray.animate({top : itemTop}, th.transitionDur, 'easeInOutBack');
			
			$.when(th.$els.catTray, th.$els.itemTray).always(function() {
				th.isAnimating = false;
			});
			
			th.updateUI();
	}
	
};
PiiqPairs.prototype.updateUI = function() {
	var th = this, c, i, cT, iT, iL, tD2 = th.transitionDur/2, cIx = th.curCatIndex, iIx = th.curItemIndex, cats = th.categories;
	
	// Check up/down buttons
	if(cats.length <= 1) {
		th.$els.buttons.categoryUp.addClass("disabled").stop(true).fadeTo(300, 0);
		th.$els.buttons.categoryDown.addClass("disabled").stop(true).fadeTo(300, 0);
	} else {
		th.$els.buttons.categoryUp.removeClass("disabled").stop(true).fadeTo(300, 1);
		th.$els.buttons.categoryDown.removeClass("disabled").stop(true).fadeTo(300, 1);
	}
	
	if(cats[cIx].items.length <= 1) {
		th.$els.buttons.itemUp.addClass("disabled").stop(true).fadeTo(300, 0);
		th.$els.buttons.itemDown.addClass("disabled").stop(true).fadeTo(300, 0);
	} else {
		th.$els.buttons.itemUp.removeClass("disabled").stop(true).fadeTo(300, 1);
		th.$els.buttons.itemDown.removeClass("disabled").stop(true).fadeTo(300, 1);
	}
	
	// Re-draw category squares
	if(cats.length <= 1) {
		th.$els.categoryPages.empty();
		th.categoryPages = [];
	} else if(th.categoryPages.length !== cats.length) {
		th.$els.categoryPages.empty();
		th.categoryPages = [];
		for(c=0; c<cats.length; c++) {
			th.categoryPages.push(
				(Raphael($("<div/>", {
					"class" : "page",
					"click" : function(){ th.turnTo(th.$els.categoryPages.find(".page").index(this), 0); }
				}).appendTo(th.$els.categoryPages).get(0), 6, 10)).rect(0, 0, 6, 6).attr({
					fill : c === cIx ? "#00c7df" : "#d9d9d3",
					stroke : 0
				})
			);
		}
	} else {	
		for(c=0; c<th.categoryPages.length; c++) {
			th.categoryPages[c].attr("fill", c === cIx ? "#00c7df" : "#d9d9d3");
		}
	}
	
	// Re-draw item squares
	if(cats[cIx].items.length <= 1) {
		th.$els.itemPages.empty();
		th.itemPages = [];
	} else if(th.itemPages.length !== cats[cIx].items.length) {
		th.$els.itemPages.empty();
		th.itemPages = [];
		for(i=0; i < cats[cIx].items.length; i++) {
			th.itemPages.push(
				(Raphael($("<div/>", {
					"class" : "page",
					"click" : function(){ th.turnTo(th.curCatIndex, th.$els.itemPages.find(".page").index(this)); }
				}).appendTo(th.$els.itemPages).get(0), 6, 10)).rect(0, 0, 6, 6).attr({
					fill : i === iIx ? "#00c7df" : "#d9d9d3",
					stroke : 0
				})
			);
		}
	} else {	
		for(i=0; i<th.itemPages.length; i++) {
			th.itemPages[i].attr("fill", i === iIx ? "#00c7df" : "#d9d9d3");
		}
	}
	
	// Update category title
	cT = th.$els.categoryTitle.fadeOut(tD2);
	iT = th.$els.itemTitle.fadeOut(tD2);
	iL = th.$els.itemLogo.fadeOut(tD2);
	
	$.when(cT, iT, iL).always(function() {
		cT.html(cats[cIx].title);
		iT.html(cats[cIx].items[iIx].title);
		iL.attr("src", cats[cIx].items[iIx].logo).css({"visibility" : cats[cIx].items[iIx].logo ? true : false});
		th.$els.itemLink.attr("href", cats[cIx].items[iIx].url).css({"visibility" : cats[cIx].items[iIx].url ? true : false});
		
		$(cT).add(iT).add(iL).fadeIn(tD2);
	});
};
PiiqPairs.prototype.randomize = function() {
	var th = this, rCat=th.categories.length-1, rItem, range = th.$els.itemTray.find("li").length, cur = (th.categories[th.curCatIndex].itemOffset + th.curItemIndex);
	var deg = 0, randBtn = th.$els.buttons.randomize.get(0);
	
	!!((rItem = (Math.floor(Math.random()*(range-1))))+1) && rItem >= cur && (rItem++);
	
	function WHEEEEE() {
		deg = deg >= 360 ? 0 : deg+12;
		randBtn.style.MozTransform = randBtn.style.WebkitTransform = randBtn.style.OTransform = "rotate("+deg+"deg)";
		if(deg > 0) {
			setTimeout(WHEEEEE, 5);
		}
	}
	
	for(c=0; c<th.categories.length; c++) {
		if(th.categories[c].itemOffset > rItem) {
			rCat = c-1;
			break;
		}
	}
	rItem -= th.categories[rCat].itemOffset;
	
	if(!TOUCH_DEVICE) { WHEEEEE(); }
	th.turnTo(rCat, rItem);
};

var PiiqPairsCategory = function($el, offset) {
	var th = this;
	
	$.extend(th, {
		$el : $el,
		title : $el.children("h4").eq(0).html(),
		items : [],
		itemOffset : offset
	});
	
	th.$el.find(".products li").each(function() {
		th.items.push({
			logo : !!$(this).data("logo") ? $(this).data("logo") : false,
			title : $(this).find("h4 a").eq(0).html(),
			url : $(this).find("a").length ? $(this).find("a").eq(0).attr("href") : false
		});
	});
}

var PiiqHeader = function() {
	var th = this;
	
	$.extend(th, {
		$els : {
			header : $("#hd"),
			headerBar : $("#hd_bar"),
			overlay : $("<div/>", {"id":"blackOverlay"}).fadeTo(0, 0).hide().appendTo("body"),
			shaderStrip : $("<div/>", {"class":"shaderStrip checkedOverlay"}).appendTo("#hd"),
			shadow : $("<div/>", {"class":"shadow"}).appendTo("#hd_nav")
		}
	});
	
	$("#hd").find(".dd").each(function() { $("<div/>", {"class":"shadow"}).appendTo(this) });
}

var PiiqDropDown = function(el){
	var t = this, $el = $(el);
	
	$.extend(t, {
		$el : $el,
		wrapper : $el.children('.sub_nav_wrapper').eq(0),
		master : $el.parent(),
		ol : $("#blackOverlay")
	});
	
	t.$el.show();
	t.upMarg = (t.wrapper.children('ul').eq(0).height() * t.wrapper.children('ul').length * -1) - 6;
	
	t.wrapper.css('margin-top', t.upMarg);
	
	if(!TOUCH_DEVICE) {
		t.master.hoverIntent({
			over:function(){t.onOver()},
			out:function(){t.onOut()},
			interval:200,
			timeout:200
		})
	}
}
PiiqDropDown.prototype.onOver = function(){
	var t = this, b = $('body');
	t.wrapper.animate({'margin-top' : 0}, {duration:250, easing:'easeOutCirc'});
	t.ol.stop(true).show().fadeTo(200, 0.3);
	t.master.addClass('down');
}
PiiqDropDown.prototype.onOut = function(){
	var t = this;
	t.wrapper.animate({'margin-top' : t.upMarg}, {duration:250, easing:'easeOutCirc'});
	t.ol.stop(true).fadeTo(200, 0, function() { $(this).hide(); });
	t.master.removeClass('down');
}

var ProductDD = function(el){
	var t = this;
	t.$el = $(el);
	t.lis = t.$el.children('.sub_nav_wrapper').children('ul').children('li:not(.empty)');
	t.pdcs = [];

	t.lis.each(function(){
		t.pdcs.push(new ProductDDComponent(this));
	});
}

var ProductDDComponent = function(el){
	var t = this, ox=3, oy=3;
	
	$.extend(t, {
		$el : $(el),
		curInd : 0,
		cwList : $(el).find('.colorWays'),
		easingType : 'easeOutQuad',
		timer : null,
		dWrap : $('<div/>', {'class': 'dWrap'}),
		dots : [],
		linkText : $('<span/>', {'class': 'linkTxt', 'text' : 'Products'})
	});
	
	t.cws = t.cwList.children('li');
	t.iw = t.cws.eq(0).width();
	
	t.cwList.width(t.iw * t.cws.length);
	t.gs = new GreyScaler(t.cws.eq(0).find('img'), "quad");
	
	t.$el.children("a").eq(0).append(t.dWrap).append(t.linkText);
	if(!TOUCH_DEVICE) {
		t.$el.hoverIntent({
			over:function(){t.onOver()},
			out:function(){t.onOut()},
			interval:0,
			timeout:50
		});
	}
	
	t.r = Raphael(t.dWrap.get(0));
	
	t.cws.each(function(i){
		var c = t.r.circle(ox, oy, 2.5).attr({
			'stroke':0,
			'fill':'#adafb0'
		});
		$(c.node).bind('click', function(e){
			e.preventDefault();
			e.stopPropagation();
			t.curInd = i-1;
			t.moveCws(true);
		});
		t.dots.push(c);
		ox += 7;
	});
}
ProductDDComponent.prototype.onOver = function(){
	var t = this;
	
	t.gs.$el.css('visibility', 'visible');
	
	$.support.opacity ? t.gs.canvas.stop(true).fadeTo(200, 0) : t.gs.canvas.css('visibility', 'hidden');
	
	t.timer = setTimeout(function() { t.moveCws(); }, 1500);
	
	t.dots[t.curInd].attr({
		'fill':'#00d8df'
	});
}
ProductDDComponent.prototype.onOut = function(){
	var t = this, i;
	
	clearTimeout(t.timer);
	
	t.curInd = -1;
	t.moveCws(true);
	
	if($.support.opacity){
		t.gs.canvas.stop(true).fadeTo(200, 1, function() {
			t.gs.$el.css('visibility', 'hidden');
		});
	} else {
		t.gs.$el.css('visibility', 'hidden');
		t.gs.canvas.css('visibility', 'visible');
	}
	
	for(i=0; i < t.dots.length; i++){
		t.dots[i].attr({
			'fill':'#adafb0'
		});
	}
}
ProductDDComponent.prototype.moveCws = function(stopLooping){
	var t = this, a = t.$el.find('a'), clones, ml, i;
	
	clearTimeout(t.timer);
	
	a.attr("href", a.attr("href").split("#")[0]+"#"+t.cws.eq((t.curInd+1)%t.cws.length).data("colorway"));
	
	if(t.cws.length > 1) {
		t.curInd++;
	
		if(t.curInd >= t.cws.length) {
			clones = t.cwList.find("li").clone().appendTo(t.cwList);
			t.cwList.width(t.iw * t.cws.length * 2);
			ml = t.curInd * t.iw * -1;
			t.curInd = 0;
		} else {
			ml = t.curInd * this.iw * -1;
		}
	
		t.cwList.animate({marginLeft : ml}, {
			duration : 200,
			easing : this.easingType,
			complete : !clones ? $.noop : function() {
				var wd = (t.iw*t.cws.length);
				clones.remove();
				t.cwList.css({
					marginLeft : "+="+wd,
					width : wd
				});
			}
		});
	} else {
		t.curInd = 0;
	}
	
	for(i=0; i<t.dots.length; i++){
		t.dots[i].attr({fill : i===t.curInd ? '#00d8df' : '#adafb0'});
	}
	
	!!stopLooping || (t.timer = setTimeout(function() { t.moveCws(); }, 1500));
}

var TeamDD = function(el){
	var t = this;
	t.$el = $(el);
	t.lis = t.$el.children('.sub_nav_wrapper').children('ul').children('li:not(.empty)');
	t.tdcs = [];

	t.lis.each(function(){
		t.tdcs.push(new TeamDDComponent(this));
	});
}
var TeamDDComponent = function(el){
	var t = this, icn;
	
	t.$el = $(el);
	t.$np = t.$el.find(".nameplate").eq(0);
	t.easingType = 'easeOutExpo';
	
	t.gs = new GreyScaler(t.$el.find('img'), "none");
	
	t.rHold = $('<div>', {'class': 'rHold'}).appendTo(t.$np);
	t.iHold = $('<div>', {'class': 'iHold'}).appendTo(t.$np);
	
	t.rh = t.rHold.height();
	t.rw = t.rHold.width();
	t.r1 = Raphael(t.rHold.get(0));
	t.triangle = t.r1.path('M0 0L60 60').attr({'stroke':"#f9f9f9"});
	$("<span/>", {"class" : !!t.$np.data('icon') ? t.$np.data('icon') : "team" }).appendTo(t.iHold);
	
	if(!TOUCH_DEVICE) {
		t.$el.hoverIntent({
			over:function(){t.onOver()},
			out:function(){t.onOut()},
			interval:0,
			timeout:50
		});	
	}

}
TeamDDComponent.prototype.onOver = function(){
	var t = this;
	
	t.gs.$el.css("visibility", "visible");
	
	$.support.opacity ? t.gs.canvas.stop(true).fadeTo(200, 0) : t.gs.canvas.css("visibility", "hidden");
}
TeamDDComponent.prototype.onOut = function(){
	var t = this;
	
	if($.support.opacity){
	   	t.gs.canvas.stop(true).fadeTo(200, 1, function() {
			t.gs.$el.css("visibility", "hidden");
		});
	} else {
	   	t.gs.$el.css("visibility", "hidden");
		t.gs.canvas.css("visibility", "visible");
	}
}

var setupTeamListDetail = function(){
	var cl = $('body').attr('class').split(/\s+/);
	var tl = $('.sportsMembersList li');
	var memName;
	$.each(cl, function(ind, it){
	    if(it.lastIndexOf('member_', 0) === 0) {
	       memName = it.substring(it.lastIndexOf('_') + 1);
	    }
	});
	
	var curMem = tl.filter('.' + memName);
	var img = curMem.find('img').eq(0);
	curMem.addClass('currentPage');
	curMem.children('a').data({'notch': '#989898', 'linkStroke' : '#989898'}).addClass('selected');
	var cOver = $('<div/>', {'class' : 'checkedOverlay'});
	cOver.width(img.width()).height(img.height()).css({'top':0, 'left':0, 'z-index' : 0}).insertAfter(img);
}

var PiiqTooltip = function($parentEl, html) {
	var t = this;
	
	$parentEl = !!$parentEl ? $parentEl : $("body");
	
	t._$parent = $parentEl;
	t._view = $('<div />', {'class':'tooltip'}).appendTo($parentEl);
	
	!!html && t.setHTML(html);
	
	$(window).bind("resize", function() {
		t.calcSizes();
	});
	
	t.calcSizes();
}

PiiqTooltip.prototype.calcSizes = function() {
	var t = this;
	
	t._view.detach();
	t._parLeft = t._$parent.offset().left;
	t._parTop = t._$parent.offset().top;
	t._parWd = t._$parent.outerWidth(false);
	t._parHt = t._$parent.outerHeight(false);
	t._view.appendTo(t._$parent);
	
	t.resize();
}

PiiqTooltip.prototype.resize = function() {
	var t = this, disp = t._view.css("display"), mT = t._view.css("marginTop"), mL = t._view.css("marginLeft");
	t._view.appendTo("body").css({"display":"block", "marginTop":0, "marginLeft":0, "visibility":"hidden"});

	t._view.css({
		"width" : "auto",
		"height" : "auto"
	});

	t._view.css({
		"width" : t._view.width()+1,
		"height" : t._view.height()
	});

	t._view.appendTo(t._$parent).css({"display":!!disp ? disp : "none", "marginTop":mT, "marginLeft":mL,  "visibility":"visible"});
	return this;
}

PiiqTooltip.prototype.setHTML = function(html) {
	var t = this;
	
	t._view.html(html);
	
	t.resize();
	
	return this;
}
PiiqTooltip.prototype.show = function(html) {
	var t = this;
	
	!!html && t.setHTML(html);
	
	t._$parent.bind('mousemove', function(e) {
		t.update(e);
	});
	
	t._view.show();
	if($.support.opacity) {
		t._view.fadeTo(0,0).fadeTo(100,1);
	}
}
PiiqTooltip.prototype.hide = function() {
	var t = this;
	t._view.hide();
	t._$parent.unbind('mousemove');
}
PiiqTooltip.prototype.update = function(e) {
	var t = this;
	var mouseX = !!e ? e.pageX : t._parLeft;
	var mouseY = !!e ? e.pageY : t._parTop;
	var ttHeight = t._view.outerHeight();
	var ttWidth = t._view.outerWidth();
	var vSpace = 12;
	var left = mouseX - t._parLeft;
	var top = mouseY - t._parTop;
	var docWd;
	
	t._view.detach();
	docWd = $("body").width();
	t._view.appendTo(t._$parent);
	
	if(left < 0 || left >= t._parWd || top < 0 || top >= t._parHt) {
		t.hide();
	} else {
		t._view.css({
			"marginLeft" : (mouseX+ttWidth > docWd) ? left-((mouseX+ttWidth)-docWd) : left,
			"marginTop" : top - (ttHeight + vSpace)
		});
	}
}



/* VIDEO PLAYER
* -------------------------- */

var PiiqVideoPlayer = function(container, videoUrl, autoPlay, posterUrl) {
	
	var t = this;
	var playerUrl = PIIQ_ASSET_PATH + 'swf/PiiqVideoPlayer.swf';
	var ap = autoPlay === true ? '1' : '0';
	var pu = posterUrl || null;
	
	var flashvars = {
		videoUrl: escape(videoUrl),
		posterUrl: escape(pu),
		autoPlay: ap
	};
	
	var params = {
		allowfullscreen: true,
		wmode: 'opaque'
	};
	
	var attributes = {
		id: 'piiqVideoPlayer',
		name: 'piiqVideoPlayer'
	};
	
	swfobject.embedSWF(playerUrl, container, "100%", "100%", "10.0.0", null, flashvars, params, attributes);
	
}


/* NEWS
* -------------------------- */

var PiiqNewsControl = function(newsList, detailContent, detailContainer) {
	
	var t = this;
	t._isOpen = true;
	t._isFirst = true;
	t._currentIndex = -1;
	t._newsList = $(newsList);
	t._detailContent = $(detailContent);
	t._detailContainer = $(detailContainer);
	t._listItems = this._newsList.children('li');
	t._tooltip = new PiiqTooltip();
	t._thumbs = [];
	
	
	// construct carousel background -----
	
	var bgSrc = $(t._detailContainer.find('img.bg'));
	bgSrc.detach();
	
	var newBg = $('<div />').attr('class', 'productCarouselBg').css('background-image', 'url(' + bgSrc.attr('src') + ')');
	newBg.prependTo(t._detailContainer);
	
	
	
	// set up thumbnail behaviors -----
	
	var thumbnailLinks = t._listItems.find('.thumb a');
	
	thumbnailLinks.each(function() {
		var checkedDiv = $('<div />', {'class': 'checkedOverlay'});
		var overDiv = $('<div />', {'class': 'over'});
		var $t = $(this);
		
		checkedDiv.appendTo(this);
		
		overDiv.appendTo(this);
		
		$t.data("tooltip", new PiiqTooltip($t, $t.parent().parent().find('.detail h3').html()));
		t._thumbs.push(new PiiqModule(this));
	}).bind({
		click : function(e) {
			e.preventDefault();
			e.stopPropagation();
			$(this).data("tooltip").hide();
			t.listItemClick(this);
		},
		mouseenter : function(e) {
			$(this).data("tooltip").update(e);
			$(this).data("tooltip").show();
		},
		mouseleave : function(e) {
			$(this).data("tooltip").hide();
		}
	});
	
	// show default item -----
	
	t.selectNewsItem(0);
	t._isFirst = false;
	
}

PiiqNewsControl.prototype.selectNewsItem = function(index) {
	
	var t = this;
	
	if (t._currentIndex === index) {
		return;
	}

	// clear last selected thumb
	if (t._currentIndex !== -1) {
		
		var thumb = $(t._listItems[t._currentIndex]).find('.thumb a');
		thumb.removeClass('selected');
		
		var mod = t._thumbs[t._currentIndex];
		mod.hideStroke();
		mod.overColor = '#00bcd4';
		
	}

	
	// show it
	t._currentIndex = index;
	
	// get source item detail and copy it
	var sourceItem = $(t._listItems[index]);
	var sourceDetail = sourceItem.find('.detail');
	var itemCopy = sourceDetail.clone();
	
	// replace detail container content
	t._detailContent.empty();
	t._detailContent.append(itemCopy);
	
	
	// see if this is a video item
	var img = itemCopy.find('img');
	
	if (typeof(img.data('video')) != 'undefined') {
		
		if (swfobject.hasFlashPlayerVersion('10.0.0')) {
			
			// replace media content with video player
			var containerId = 'videoContainer';
			var media = itemCopy.find('.media');
			media.empty();
			
			var videoContainer = $('<div />').attr('id', containerId);
			media.append(videoContainer);
			
			var autoPlay = t._isFirst ? false : true;
			new PiiqVideoPlayer(containerId, img.data('video'), autoPlay, img.attr('src'));
			
		}
		
	}
	
	var thumb = $(t._listItems[t._currentIndex]).find('.thumb a');
	thumb.addClass('selected');
	
	var mod = t._thumbs[t._currentIndex];
	mod.overColor = '#989898';
	mod.showStroke();
	mod.changeNotchColor(0);
	
	t._detailContent.hide();
	t._detailContent.fadeIn(300);
}

PiiqNewsControl.prototype.closeDetail = function() {
	var t = this;
	t._isOpen = false;
	t._currentIndex = -1;
	t._detailContainer.slideUp();
}

PiiqNewsControl.prototype.openDetail = function() {
	var t = this;
	t._isOpen = true;
	t._detailContainer.slideDown();
}

PiiqNewsControl.prototype.listItemClick = function(thumbLink) {
	var t = this;
	var listItem = $(thumbLink).parent().parent();
	var index = t._listItems.index(listItem);
	t.selectNewsItem(index);
}


/* PRODUCT LANDING
* -------------------------- */

function PiiqProductLandingFamily(els) {
	var th = this;
	
	$.extend(this, {
		enterTimer : null,
		enterWait : 150,
		leaveTimer : null,
		leaveWait : 150,
		$els : $(els),
		boxes : []
	});
	
	th.$els.each(function() {
		var thEl = this;
		th.boxes.push(new PiiqProductLandingBox(this, th));
		if(!TOUCH_DEVICE) {
			$(this).hover(
				function(e) {
					clearTimeout(th.leaveTimer);
					th.enterTimer = setTimeout(function() {
						th.highlightAll(thEl);
					}, th.enterWait);
				},
				function() {
					clearTimeout(th.enterTimer);
					th.leaveTimer = setTimeout(function() {
						th.unhighlightAll();
					}, th.leaveWait);
				}
			);
		}
	});
}
PiiqProductLandingFamily.prototype.highlightAll = function(except) {
	var th = this, b, bLen;
	for(b=0, bLen = th.boxes.length; b < bLen; b++) {
		if(!th.boxes[b].$el.is(except)) {
			th.boxes[b].highlightAsRelated();
		}
	}
	
	return this;
}
PiiqProductLandingFamily.prototype.unhighlightAll = function() {
	var th = this, b, bLen;
	
	for(b=0, bLen = th.boxes.length; b < bLen; b++) {
		th.boxes[b].unhighlightAsRelated();
	}
	
	return this;
};

function PiiqProductLandingBox(el, family) {
	var th = this;
	
	$.extend(this, {
		family : family,
		$el : $(el),
		piiqModule : $(el).data("piiqModuleRef"),
		tooltip : new PiiqTooltip($(el), $(el).find('h6').html())
	});
	
	if(!TOUCH_DEVICE) {
		th.$el.hover(
			function(e) {
				th.tooltip.update(e);
				th.tooltip.show();
				th.$el.removeClass("related");
			},
			function() { th.tooltip.hide(); }
		);
	}

}
PiiqProductLandingBox.prototype.highlightAsRelated = function() {
	var th = this;
	th.$el.addClass("related");
};
PiiqProductLandingBox.prototype.unhighlightAsRelated = function() {
	var th = this;	
	th.$el.removeClass("related");
};


/* PRODUCT DETAIL
* -------------------------- */

var PiiqProductDetail = function(carouselContainer) {
	
	var t = this;
	t._carouselContainer = $(carouselContainer);
	t._currentColor = null;
	t._currentView = null;
	t._currentColorContainer = null;
	t._currentColorCta = null;
	t._validColors = [];
	t._validViews = [];
	t._colorButtons = [];
	t._currentImage = null;
	t._previousImage = null;
	t._prevBtn = null;
	t._nextBtn = null;
	t._hotspotsContainer = null;
	t._tooltip = new PiiqTooltip();
	t._retailersOpen = false;
	t._thumbs = [];
	
	// construct carousel background -----
	
	var bgSrc = $(t._carouselContainer.find('img.bg'));
	bgSrc.detach();
	
	var newBg = $('<div />').attr('class', 'productCarouselBg').css('background-image', 'url(' + bgSrc.attr('src') + ')');
	newBg.prependTo(t._carouselContainer);
	
	
	// construct available views and colors from dom -----
	
	var modelColors = $('.modelColors > li');
	modelColors.each(function(index, element) {
        t._validColors.push($(element).data('name'));
    });
	
	var colorViews = $(modelColors.get(0)).find('.colorThumbs a');
	colorViews.each(function(index, element) {
        t._validViews.push($(element).data('view'));
    });
	
	// we will start with first view
	t._currentView = t._validViews[0];
	
	
	// hook up color switching buttons ----
	
	t._carouselContainer.find('.cw_buttons a').each(function(index, element) {
		
		t._colorButtons.push(new ColorwayButton(this));
		
		$(this).bind('click', function(e) {
			e.preventDefault();
			e.stopPropagation();
			t.selectColorway(t._validColors[index]);
		});
		
	});
	
	// hook up view switching buttons ----
	
	t._carouselContainer.find('.colorThumbs a').each(function(index, element) {
		
		t._thumbs.push(new PiiqModule(this, 0));
		
		$(this).bind('click', function(e) {
			e.preventDefault();
			e.stopPropagation();
			t.selectView($(this).data('view'), false);
		});
		
	});
	
	// hook up buy now buttons ----
	// this is for dynamic link switching based on color, taking out for now so client can hard-code buy now link in markup
	/*
	t._carouselContainer.find('a.cta').each(function(index, element) {
		
		$(this).bind('click', function(e) {
			e.preventDefault();
			window.open(t._currentColorCta);
		});
		
	});
	*/
	// hook up retailers button ----
	
	t._carouselContainer.find('a.retailers').each(function(index, element) {
		
		$(this).bind('click', function(e) {
			e.preventDefault();
			e.stopPropagation();
			t.toggleRetailersMenu();
		});
		
	});
	
	// set up view direction buttons, hotspots container -----
	
	t._hotspotsContainer = $('<div />').attr('class', 'hotspotsContainer');
	t._prevBtn = $('<span />').attr('class', 'btn left');
	t._nextBtn = $('<span />').attr('class', 'btn right');
	
	var content = t._carouselContainer.find('.content');
	content.append(t._hotspotsContainer, t._prevBtn, t._nextBtn);
	
	t._prevBtn.bind('click', function(e) {
		e.preventDefault();
		t.prevView();
	});
	
	t._nextBtn.bind('click', function(e) {
		e.preventDefault();
		t.nextView();
	});
	
	if (t._validViews.length < 2) {
		t._prevBtn.hide();
		t._nextBtn.hide();
	}
	
	
	// check location hash for specific color -----
	
	$(window).bind("hashchange", function() {
		var hash;
		if(!!(hash = t.hashCheck())) {
			t.selectColorway(hash);
		}
	})
	
	if(!!(hash = t.hashCheck())) {
		t.selectColorway(hash);
		return;
	}
	
	// else show default color ---
	
	t.selectColorway(t._validColors[0]);
	
}

PiiqProductDetail.prototype.hashCheck = function() {
	var hash = location.hash.substr(1);
	return (hash && this.getIndexForColor(hash) !== -1) ? hash : false;
}

PiiqProductDetail.prototype.toggleRetailersMenu = function() {
	var t = this;
	if (t._retailersOpen) {
		t.hideRetailersMenu();
	} else {
		t.showRetailersMenu();
	}
}

PiiqProductDetail.prototype.showRetailersMenu = function() {
	
	var t = this;
	t._retailersOpen = true;
	
	t._carouselContainer.find('a.retailers').each(function(index, element) {
		$(element).addClass('open');
	});
	
	t._carouselContainer.find('div.retailersMenu').each(function(index, element) {
		$(element).fadeIn(100);
	});
	
	$('body').bind('mousedown', function(e) {
		var menuContainer = t._carouselContainer.find('div.retailersContainer');
		if (menuContainer.find(e.target).length) return;
		t.hideRetailersMenu();
	});
}

PiiqProductDetail.prototype.hideRetailersMenu = function() {
	
	var t = this;
	t._retailersOpen = false;
	
	t._carouselContainer.find('a.retailers').each(function(index, element) {
		$(element).removeClass('open');
	});
	
	t._carouselContainer.find('div.retailersMenu').each(function(index, element) {
		$(element).hide();
	});
	
	$('body').unbind('mousedown');
}

PiiqProductDetail.prototype.prevView = function() {
	var t = this;
	var currentIndex = t.getIndexForView(t._currentView);
	var newIndex = currentIndex - 1;
	if (newIndex < 0) newIndex = t._validViews.length - 1;
	t.selectView(t._validViews[newIndex], false);
}

PiiqProductDetail.prototype.nextView = function() {
	var t = this;
	var currentIndex = t.getIndexForView(t._currentView);
	var newIndex = currentIndex + 1;
	if (newIndex >= t._validViews.length) newIndex = 0;
	t.selectView(t._validViews[newIndex], false);
}

PiiqProductDetail.prototype.selectColorway = function(color) {
	
	var t = this;
	
	if (color === t._currentColor) return;
	if (t.getIndexForColor(color) === -1) return;
	
	
	// update new stuff ---------------
	
	t._currentColor = color;
	
	// update location hash
	location.hash = t._currentColor;
	
	// update color buttons -----
	
	var colorIndex = t.getIndexForColor(t._currentColor);
	
	for (var i = 0; i < t._colorButtons.length; i++) {
		
		var btn = t._colorButtons[i];
		
		if (i === colorIndex) {
			btn.goDown();
			$('p.colorway span').text(btn.$el.attr('href').substring(1));
		} else if (btn.selected === true) {
			btn.comeUp();
		}
		
	}
	
	// update model display -----
	
	var modelDisplay = t._carouselContainer.find('.productModel');
	modelDisplay.each(function(index, element) {
		var e = $(element);
		if (e.hasClass(t._currentColor)) {
			e.show();
		} else {
			e.hide();
		}
	});
	
	var colorDisplay = t._carouselContainer.find('.colorLabel');
	colorDisplay.each(function(index, element) {
		var e = $(element);
		if (e.hasClass(t._currentColor)) {
			e.show();
		} else {
			e.hide();
		}
	});
	
	
	// update product color image for current view ------
	
	// save ref to current container, hide/show view thumbs
	
	var modelColors = $('.modelColors > li');
	
	modelColors.each(function(index, element) {
		
		var e = $(element);
		var viewNav = e.find('ul.colorThumbs');
		
        if (e.data('name') === t._currentColor) {
			t._currentColorContainer = e;
			t._currentColorCta = e.data('cta');
			viewNav.show();
		} else {
			viewNav.hide();
		}
		
    });
	
	// show image for current view
	t.selectView(t._currentView, true);
	
}

PiiqProductDetail.prototype.selectView = function(view, isNewColor) {
	
	var t = this;
	var newViewIndex = t.getIndexForView(view);
	
	if (newViewIndex === -1) return;
	if (view === t._currentView && !isNewColor) return;
	
	t._hotspotsContainer.empty();
	
	
	// animate old image off ----
	
	var props;
	var dur = 200;
	var delay = 0;
	var easeOffScreen = 'easeInExpo';
	var easeOnScreen = 'easeOutExpo';
	var oldViewIndex = t.getIndexForView(t._currentView);
	var difIndex = newViewIndex - oldViewIndex;
	var motionDir = difIndex === -1 || difIndex === t._validViews.length - 1 ? 'left' : 'right';
	
	if (t._currentImage !== null) {
		
		t._previousImage = t._currentImage;
		delay = 300;
		
		// set up props for proper direction
		if (isNewColor) {
			props = {
				top: 625
			};
			if ($.support.opacity) {
				props.opacity = 0;
			}
		} else {
			props = {};
			if ($.support.opacity) {
				props.left = motionDir === 'left' ? 250 : -250
				props.opacity = 0;
			} else {
				props.top = 625
			}
		}
		
		// animate off
		t._previousImage.animate(
			props,
			{
				duration: dur,
				easing: easeOffScreen,
				queue: true,
				complete: function() {
					t.hidePreviousImageComplete();
				}
			}
		);
		
	}
	
	// animate new image on ------
	
	t._currentView = view;
	
	t._currentImage = t._currentColorContainer.find('.colorViews li.' + t._currentView );
	
	// reset css
	t._currentImage.css('top', 0).css('left', 0);
	if ($.support.opacity) t._currentImage.css('opacity', 1);
	t._currentImage.show();
	
	// set up animation props for proper direction
	if (isNewColor) {
		props = {
			top: 0
		};
		if ($.support.opacity) props.opacity = 1;
		t._currentImage.css('top', '625px');
		if ($.support.opacity) t._currentImage.css('opacity', '0');
	} else {
		props = {};
		if ($.support.opacity) {
			props.left = 0
			props.opacity = 1;
			var left = motionDir === 'left' ? '-500px' : '500px'
			t._currentImage.css('left', left);
			t._currentImage.css('opacity', '0');
		} else {
			props.top = 0;
			t._currentImage.css('top', '625px');
		}
	}
	
	// animate on
	t._currentImage.delay(delay).animate(
		props,
		{
			duration: dur,
			easing: easeOnScreen,
			queue: true,
			complete: function() {
				t.showCurrentImageComplete();
			}
		}
	);
	
	
	// update view thumbs state ------
	
	for (var i = 0; i < t._thumbs.length; i++) {
		
		var thumb = t._thumbs[i];
		
		if (thumb.$el.data('view') === t._currentView) {
			
			thumb.overColor = '#989898';
			thumb.showStroke();
			thumb.$el.addClass('selected');
			
		} else if (thumb.$el.hasClass('selected')) {
			
			thumb.overColor = '#00bcd4';
			thumb.hideStroke();
			thumb.$el.removeClass('selected');
			
		}
		
	}
	
}

PiiqProductDetail.prototype.showCurrentImageComplete = function() {
	var t = this;
	t.updateHotspots();
}

PiiqProductDetail.prototype.hidePreviousImageComplete = function() {
	var t = this;
	t._previousImage.hide();
}

PiiqProductDetail.prototype.updateHotspots = function() {
	var t = this, viewHotspots = t._carouselContainer.find('ul.viewsHotspots li.' + t._currentView + ' li'), delay = 0;
	
	// attach hotspots for each list item
	viewHotspots.each(function(index, element) {
		var e = $(element), html = e.html(), btn;
		btn = $('<span />').attr('class', 'hotspot').attr('data-label', html).css('top', e.data('y')).css('left', e.data('x'));
		delay += 80;
		
		btn.hover(
			function(e) {
				t._tooltip.update(e);
				t._tooltip.show($(this).data('label'));
			},
			function(e) {
				t._tooltip.hide();
			}
		);
		
		t._hotspotsContainer.append(btn);
		
		if (jQuery.support.opacity) {
			btn.hide().delay(delay).fadeIn(300);
		} else {
			btn.show();
		}
	});
	
}

PiiqProductDetail.prototype.getIndexForColor = function(color) {
	var t = this, i = t._validColors.length;
	
	while (i--) {
		if (t._validColors[i] === color) {
			return i;
		}
	}
	
	return -1;
}

PiiqProductDetail.prototype.getIndexForView = function(view) {
	var t = this, i = t._validViews.length;
	
	while (i--) {
		if (t._validViews[i] === view) {
			return i;
		}
	}
	
	return -1;
}
