/* Video Panel function */
var videoList = {
	  'jamboxoverview' : {
			  'flv' : "http://www.youtube.com/watch?v=XgC3zjNH1oU",
			  'embed_link' : '<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/XgC3zjNH1oU?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/XgC3zjNH1oU?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>',
			  'dl_link' : "http://www.youtube.com/watch?v=XgC3zjNH1oU",
			  'share_link': 'http://www.youtube.com/watch?v=XgC3zjNH1oU',
			  'trackingId' : "JAMBOX Overview - YouTube"
	  },
	  //'jamboxoverview' : {
	  //		'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/JAMBOX_Overview.mp4",
	  //		'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/JAMBOX_Overview.mp4",
	  //		'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/JAMBOX_Overview_65.mp4.zip",
	  //		'trackingId' : "JAMBOX Overview"
	  //},

			
		'eraOverviewNew' : {
		  'flv' : "http://www.youtube.com/watch?v=0GPYwxvqW7s",
		  'embed_link' : '<iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/0GPYwxvqW7s" frameborder="0" allowfullscreen></iframe>',
		  'dl_link' : "http://www.youtube.com/watch?v=0GPYwxvqW7s",
		  'share_link': '',
		  'trackingId' : "ERA Overview"
		},
		
		/*
		'eraOverviewNew' : {
		  'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/ERA_Overview.mp4",
		  'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/ERA_Overview.mp4",
		  'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/ERA_Overview.mp4",
		  'share_link': '',
		  'trackingId' : "ERA Overview"
		},
		*/
		'iconoverviewNew' : {
		  'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/ICON_Overview.mp4",
		  'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/ICON_Overview.mp4",
		  'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/ICON_Overview.mp4",
		  'share_link': '',
		  'trackingId' : "ICON Overview"
		},
		'mytalkoveview' : {
		  'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/MYTALK_Overview.mp4",
		  'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/MYTALK_Overview.mp4",
		  'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/MYTALK_Overview.mp4",
		  'share_link': '',
		  'trackingId' : "MyTalk Overview"
		},
			
		'maniacs' : {
		  'flv' : "http://www.youtube.com/watch?v=n7f1VrukB8s",
		  'embed_link' : '<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/n7f1VrukB8s?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/n7f1VrukB8s?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>',
		  'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Our_Little_Maniacs_640x360_650kbps.zip",
		  'share_link': 'http://www.youtube.com/watch?v=n7f1VrukB8s',
		  'trackingId' : "Little Maniacs - YouTube"
		},
	//'maniacs' : {
	//		'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Our_Little_Maniacs_640x360_650kbps.mp4",
	//		'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Our_Little_Maniacs_640x360_650kbps.mp4",
	//		'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Our_Little_Maniacs_640x360_650kbps.zip",
	//		'trackingId' : "Little Maniacs"
	//	  },

			
		'construction' : {
		  'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/construction5.flv",
		  'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/construction5.flv",
		  'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Jawbone_Construction.mov.zip",
		  'share_link': '',
		  'trackingId' : "Construction"
		},
		'derby' : {
		  'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/derby2.flv",
		  'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/derby2.flv",
		  'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Jawbone_Derby.mov.zip",
		  'share_link': '',
		  'trackingId' : "Derby" 
		},
		'iconoverview' : {
		  'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/ICON_overview.flv",
		  'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/ICON_overview.flv",
		  'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/ICON_overview.zip",
		  'share_link': '',
		  'trackingId' : "ICON Overview"
		},
		'iconphoneconnect' : {
		  'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/How_to_Connect_with_your_phone.flv",
		  'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/How_to_Connect_with_your_phone.flv",
		  'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/How_to_Connect_with_your_phone.zip",
		  'share_link': '',
		  'trackingId' : "How To Pair"
		},
		'iconearbuds' : {
		  'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Choosing_and_putting_on_an_Earbud.flv",
		  'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Choosing_and_putting_on_an_Earbud.flv",
		  'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Choosing_and_putting_on_an_Earbud.zip",
		  'share_link': '',
		  'trackingId' : "Choosing An Earbud"
		},
		'iconwearing' : {
		  'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Wearing_Your_ICON.flv",
		  'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Wearing_Your_ICON.flv",
		  'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Wearing_Your_ICON.zip",
		  'share_link': '',
		  'trackingId' : "Wearing Your ICON"
		},
		'iconconnect' : {
		  'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Connecting_Your_ICON.flv",
		  'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Connecting_Your_ICON.flv",
		  'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Connecting_Your_ICON.zip",
		  'share_link': '',
		  'trackingId' : "Connecting ICON"
		},
		'iconcall' : {
		  'flv' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/AcceptingandRejecting_a_Call.flv",
		  'embed_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/AcceptingandRejecting_a_Call.flv",
		  'dl_link' : "http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/AcceptingandRejecting_a_Call.zip",
		  'share_link': '',
		  'trackingId' : "Accept-Reject A Call"
		},
		'curve' : {
		  'flv' : 'http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Ahead_of_the_Curve1.flv',
		  'embed_link' : 'http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Ahead_of_the_Curve1.flv',
		  'dl_link' : 'http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/Ahead_of_the_Curve1.flv.zip',
		  'share_link': '',
		  'trackingId' : "Ahead of the Curve"
		},
		'americathismorning' : {
		  'flv' : 'http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/America_This_Morning.flv',
		  'embed_link' : 'http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/America_This_Morning.flv',
		  'dl_link' : 'http://aliphcom.httpsvc.vitalstreamcdn.com/aliphcom_vitalstream_com/videos/America_This_Morning.flv.zip',
		  'share_link': '',
		  'trackingId' : "America This Morning"
		},
			
		'thoughtsOverview' : {
		  'flv' : 'http://www.youtube.com/watch?v=rKlB0lRZBAg',
		  'embed_link' : '<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/rKlB0lRZBAg?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/rKlB0lRZBAg?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>',
		  'dl_link' : 'http://www.youtube.com/watch?v=rKlB0lRZBAg',
		  'share_link': 'http://www.youtube.com/watch?v=rKlB0lRZBAg',
		  'trackingId' : "Thoughts Overview"
		}

};

function deleteVideo(theWrapper, thePlaceholder, thePlayerId) { 
  swfobject.removeSWF(thePlayerId);
  var tmp = $("#" + theWrapper);
  if (tmp) { 
	tmp.html("<div id='" + thePlaceholder + "'></div>");
  }
}

function cleanVideoPath(p) {
	if(p.indexOf("../") !== 0) return p;
	return cleanVideoPath(p.substring(3));
}
  // Tell the flv player to play this video
function playVideo(placeHolder, playerId, vidId, w, h){
  try {  
	var eventTrackingObj = {
		category: "Video",
		action: videoList[vidId].trackingId,
		label: window.location.pathname
	};
	jawbone.google.eventTracking.trackSingle(eventTrackingObj);
	
	var link = (videoList[vidId].share_link != "") ? videoList[vidId].share_link : videoList[vidId].embed_link;
	
	jwplayer(placeHolder).setup({
		flashplayer: "/jwplayer/player.swf",
		file: videoList[vidId].flv,
		controlbar: 'bottom',
		autostart: 'true',
		height: h,
		wmode: 'transparent',
		width: w,
		dock: true,
		plugins:
			'/flash/plugins/sharingdl/sharingdl.swf',
			'sharingdl.link': link,
			'sharingdl.code': videoList[vidId].embed_link,
			'sharingdl.download': videoList[vidId].dl_link,
			'sharingdl.title': '',
		skin: '/flash/jawbonePlayerSkin/jawbonePlayerSkin.xml',
		events: {
		  onComplete: function() {
				//var s = 'jwplayer(' + placeHolder + ').remove()';
				//setTimeout( "jwplayer('videoDisplay1').remove()", 1000);
			}
		}
	});
  } catch(e) {}
}

function initVideo(placeHolder, vidId, w, h, i){
  try {
	//	alert("initVideo " + placeHolder);
	var link = (videoList[vidId].share_link != "") ? videoList[vidId].share_link : videoList[vidId].embed_link;
	
	var params = {
		flashplayer: "/jwplayer/player.swf",
		file: videoList[vidId].flv,
		controlbar: 'bottom',
	  autostart: 'false',
	  height: h,
	  wmode: 'transparent',
		width: w,
	  dock: true,
	  plugins: '/flash/plugins/sharingdl/sharingdl.swf',
	  'sharingdl.link': link,
	  'sharingdl.code': videoList[vidId].embed_link,
	  'sharingdl.download': videoList[vidId].dl_link,
	  'sharingdl.title': '',
	  skin: '/flash/jawbonePlayerSkin/jawbonePlayerSkin.xml',
	  events: {
		  onComplete: function() {
			//var s = 'jwplayer(' + placeHolder + ').remove()';
			//setTimeout( "jwplayer('videoDisplay1').remove()", 1000);
		  }
	  }
	};
	if(i) params["image"] = i;
	jwplayer(placeHolder).setup(params);
	} catch(e) {}
}

function startVideo(placeHolder, videoPlayerWrapper, videoThumbWrapper) {
	$("#" + videoPlayerWrapper).css("height", $("#" + videoThumbWrapper).css("height"));
	$("#" + videoPlayerWrapper).css("width", $("#" + videoThumbWrapper).css("width"));
	$("#" + videoPlayerWrapper).css("top", "0px");
	$("#" + videoPlayerWrapper).css("left", "0px");
	$("#" + videoThumbWrapper).css("height", "0px");
	$("#" + videoThumbWrapper).css("width", "0px");
	$("#" + videoThumbWrapper).css("overflow", "hidden");
	document.getElementById(placeHolder).sendEvent("PLAY", "true");
}

// Infinite Carousel
$.fn.infiniteCarousel = function () {

	function repeat(str, num) {
		return new Array( num + 1 ).join( str );
	}
  
	return this.each(function () {
		var $wrapper = $('> div', this).css('overflow', 'hidden'),
			$slider = $wrapper.find('> ul'),
			$items = $slider.find('> li'),
			$single = $items.filter(':first'),
			
			singleWidth = $single.outerWidth(), 
			visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesnt include padding or border
			currentPage = 1,
			pages = Math.ceil($items.length / visible);			   


		// 1. Pad so that 'visible' number will always be seen, otherwise create empty items
		if (($items.length % visible) != 0) {
			$slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
			$items = $slider.find('> li');
		}

		// 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
		$items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
		$items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
		$items = $slider.find('> li'); // reselect
		
		// 3. Set the left position to the first 'real' item
		$wrapper.scrollLeft(singleWidth * visible);
		
		// 4. paging function
		function gotoPage(page) {
			var dir = page < currentPage ? -1 : 1,
				n = Math.abs(currentPage - page),
				left = singleWidth * dir * visible * n;
			
			$wrapper.filter(':not(:animated)').animate({
				scrollLeft : '+=' + left
			}, 2000, function () {
				if (page == 0) {
					$wrapper.scrollLeft(singleWidth * visible * pages);
					page = pages;
				} else if (page > pages) {
					$wrapper.scrollLeft(singleWidth * visible);
					// reset back to start position
					page = 1;
				} 

				currentPage = page;
			});				   
			
			return false;
		}
		
		$wrapper.after('<a class="arrow back"></a><a class="arrow forward"></a>');
		
		// 5. Bind to the forward and back buttons
		$('a.back', this).click(function () {
			return gotoPage(currentPage - 1);				 
		});
		
		$('a.forward', this).click(function () {
			return gotoPage(currentPage + 1);
		});
		
		// create a public interface to move to a specific page
		$(this).bind('goto', function (event, page) {
			gotoPage(page);
		});
	});	 
};
function scrollTowardIndex(ind) {
	var carousel = $('#galleryCarousel').data('jcarousel');
	// alert("SCROLL TOWARD " + ind + " FROM {" + carousel.first + ":" + carousel.last + "}");
	// need to scroll carousel?
	if(ind > carousel.last) {
		carousel.next();
		setTimeout(function(){scrollTowardIndex(ind);}, 2100);
	} else if(ind < carousel.first) {
		carousel.prev();
		setTimeout(function(){scrollTowardIndex(ind);}, 2100);
	}
}
function getImageIndex(imgsrc) {
	var container = document.getElementById("galleryCarousel");
	var imagelis = container.childNodes;
	// alert("LIS: " + imagelis.length);
	var liindex = 1;
	for(var i = 0; i < imagelis.length; i++) {
		if(imagelis[i].nodeName == "#text") continue;
		// alert(imagelis[i].nodeName + "//" + imagelis[i].childNodes.length);
		if(imagelis[i].firstChild.getAttribute("rel") == imgsrc) return liindex;
		liindex++;
	}
	return -1;
}
function getFirstSrc() {
	var fs = $("#galleryCarousel").children(":first-child").children(":first-child").attr("rel");
	alert(fs);
	return fs;
}

//////////////////////////////////////////////////////
//		new stuff from here down; winning!
//////////////////////////////////////////////////////

jawbone = {
	init: function() {
		this.util.init();
		this.google.init();
		this.facebook.init();
		this.productShelf.init();
		this.homepageSlider.init();
		this.emailOptIn.init();
		this.compareHeadSets.init();
	},
	runtimeInit: function() {
		this.util.setBrowserClass();
	},
	util:  {
		isBadIE: false,
		init: function() {
			this.setNav();
			this.setSuckerFish();
		},
		runtimeInit: function() {
			this.setBrowserClass();
		},
		setBrowserClass: function() {
			if (navigator.userAgent.indexOf('MSIE 7.0') != -1) {
				$('html').addClass('ie7');
				this.isBadIE = true;
			}
		},
		setNav: function() {
			var nav = $('#main-nav');
			switch(window.location.pathname.split("/")[1]) {
				case "headsets":
					nav.find(".headsets").addClass("active");
				break;
				case "speakers":
					nav.find(".speakers").addClass("active");
				break;
				case "thoughts":
					nav.find(".thoughts").addClass("active");
				break;
				case "support":
					nav.find(".support").addClass("active");
				break;
			}
		},
		setSuckerFish: function() {
			if (!this.isBadIE) { return false; }
			var mainTarget = $('#main-nav').find('.sf');
			var subMenu = mainTarget.find('.headset-sub');
			mainTarget.mouseenter(function(){
				$(this).addClass('hover');
				subMenu.attr('style','');
			});
			mainTarget.mouseleave(function(){
				$(this).removeClass('hover');
				subMenu.css('left','-999em');
			});
			subMenu.mouseenter(function(){
				subMenu.attr('style','');
			});
			subMenu.mouseleave(function(){
				mainTarget.removeClass('hover');
				subMenu.css('left','-999em');
			});
		},
		isValidEmail: function(email) {
			var reg = /^([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.\+])+\.([A-Za-z]{2,4})$/;
			return reg.test(email);
		}
	},
	productShelf:  {
		sliders: [],
		rightButtons: [],
		timeouts: {},
		leftLocations: {
			era: {
				over: "10px",
				out: "40px"
			},
			icon: {
				over: "240px",
				out: "270px"
			},
			earwear: {
				over: "470px",
				out: "500px"
			},
			jambox: {
				over: "700px",
				out: "730px"
			}
		},
		init: function() {
			if ($('#productSliderShell').length == 0) { return false;}
			this.storeSliders();
			this.setEventListeners();
		},
		storeSliders: function() {
			// slider elements
			this.sliders.push($('#productSliderEraDiv')[0]);
			this.sliders.push($('#productSliderIconDiv')[0]);
			this.sliders.push($('#productSliderEarwearDiv')[0]);
			this.sliders.push($('#productSliderJamboxDiv')[0]);
			// right buttons
			this.rightButtons.push($("#productSliderRightEra")[0]);
			this.rightButtons.push($("#productSliderRightIcon")[0]);
			this.rightButtons.push($("#productSliderRightEarwear")[0]);
			this.rightButtons.push($("#productSliderRightJambox")[0]);
		},
		setEventListeners: function() {
			var $this = this;
			$('#productSliderInitDiv').find('.main-shelf-item').each(function() {
				$(this).click(function(e) {
					$this.initClickHander(this);
				});
				$(this).mouseover(function(e) {
					$this.initMouseOverHandler(this);
				});
				$(this).mouseout(function(e) {
					$this.initMouseOutHandler(this);
				});
			});
			$(this.rightButtons).click(function(e) {
				var targetButton = e.currentTarget.id.replace("productSliderRight","").toLowerCase() + "Img"; 
				$('#' + targetButton).click();
			});
			var mainTargets = $('#productSliderShell').find('.action-position');
			var topTargets = $('#productSliderShell').find('.topActionDiv');
			topTargets.mouseenter(function(){
				$this.subMouseOverHandler($(this).parent());
			});
			mainTargets.mouseleave(function(){
				$this.subMouseOutHandler($(this));
			});
		},
		initClickHander: function(el) {
			var $this = this;
			var targetSlider = $('#productSlider' + $(el).attr("rel") +'Div');
			var targetButton= $('#productSliderRight' + $(el).attr("rel"));
			var tempArray = [];
			$(this.sliders).each(function(index) {
				if (this != targetSlider[0]) {
					tempArray.push(this);
				}
				$this.sliders = tempArray;
			});
			$(targetSlider).css("width", "0px");
			$(targetSlider).show();
			$(targetSlider).css("zIndex", "1500");
			$(targetSlider).css("overflow", "hidden");
			$(targetSlider).animate({
				width : "924px"
				}, 800,
				function() {
					$($this.sliders).each(function() {
						$(this).hide();
					});
					$(targetSlider).css("overflow", "visible");
					$(targetSlider).css("zIndex", "1200");
					$(targetSlider).find(".action-position").css("opacity", "0.0");
					$this.sliders.push(targetSlider[0]);
				}
			);
			$($this.rightButtons).each(function(index) {
				$(this).removeClass("selectedShelf");
			});
			$(targetButton).addClass("selectedShelf");
		},
		initMouseOverHandler: function(el) {
			var $this = this;
			$(el).animate({
					width : "173px",
					height : "60px",
					top : "20px",
					left : $this.leftLocations[el.id.split("Img")[0]].over
				}, 450
			);
		},
		initMouseOutHandler: function(el) {
			var $this = this;
			$(el).animate({
					width : "115px",
					height : "40px",
					top : "30px",
					left : $this.leftLocations[el.id.split("Img")[0]].out
				}, 450
			);
		},
		subMouseOverHandler: function(el) {
			var $this = this;
			if ($this.timeouts[el.attr("id")]) {
				clearTimeout($this.timeouts[el.attr("id")]);
				delete $this.timeouts[el.attr("id")];
			} else {
				el.prev().animate({
						width : "165px",
						height : "58px",
						top : "21px",
						left : "15px"
					}, 300
				);
				el.animate({opacity : "1.0", alpha : "100"}, 400);
			}
		},
		subMouseOutHandler: function(el) {
			var $this = this;
			$this.timeouts[el.attr("id")] = setTimeout(function(){
				el.animate({opacity : "0.0", alpha : "0"}, 400);
				el.prev().animate({
					width : "115px",
					height : "40px",
					top : "30px",
					left : "40px"
				}, 300);
				delete $this.timeouts[el.attr("id")];
			}, 100);
		}
	},
	homepageSlider:  {
		autoplay: true,
		interval: 8000,
		fadeSpeed: 1000,
		timer: {},
		slides: {},
		buttons: {},
		currentSlide: {},
		init: function() {
			if ($('#home-slide-container').length == 0) { return false; }
			this.setStorage();
			this.setListeners();
			this.runAutoPlay();
		},
		setStorage: function() {
			this.slides = $('#home-slide-container').find('.slide');
			this.buttons = $('#home-slide-container').find('.button');
		},
		setListeners: function() {
			var $this = this;
			this.buttons.click(function(e){
				e.preventDefault();
				$this.manualSlide(this);
			});
			$('#home-slide-container').find('.arrow').click(function(e){
				e.preventDefault();
				$this.arrowHandler(this);
			});
		},
		runAutoPlay: function(index) {
			if (!this.autoplay) { return false; }
			var $this = this;
			if (!index) { index = 0; }
			delete this.timer;
			this.timer = setTimeout(function() {
				$this.autoSlide($this.buttons[index]);
			}, $this.interval);
			return true;
		},
		arrowHandler: function(el) {
			clearTimeout(this.timer);
			delete this.timer;
			this.autoplay = false;
			var currentTarget = $('#home-slide-container').find('.button.active');
			var currentIndex = this.buttons.index(currentTarget);
			if ($(el).hasClass("next")) {
				currentIndex += 1;
			} else if ($(el).hasClass("previous")) {
				currentIndex -= 1;
			}
 			if (currentIndex > this.buttons.length -1) {
				currentIndex = 0;
			} else if (currentIndex < 0) {
				currentIndex = this.buttons.length - 1;
			}
			this.manualSlide(this.buttons[currentIndex]);
		},
		autoSlide: function(el) {
			var $this = this;
			var $slides = this.slides;
			var currentIndex = this.buttons.index(el);
			var nextIndex = 0;
			if (currentIndex != this.buttons.length - 1) {
				nextIndex = currentIndex + 1;
			} else {
				nextIndex = 0;
			}
			// animation logic
			if (nextIndex != 0) {
				$($slides[currentIndex]).addClass("active");
				$($slides[nextIndex]).show();
				$($slides[currentIndex]).fadeOut($this.fadeSpeed,function(){
					$(this).removeClass("active");
				});
			} else {
				$($slides[currentIndex]).removeClass("active");
				$($slides[nextIndex]).addClass("active");
				$($slides[nextIndex]).fadeIn($this.fadeSpeed,function(){
					$($slides[currentIndex]).hide();
				});
			}
			if (this.autoplay) {
				this.setButton(nextIndex);
				this.runAutoPlay(nextIndex);
			}
		},
		manualSlide: function(el) {
			var $this = this;
			clearTimeout(this.timer);
			delete this.timer;
			this.autoplay = false;
			var currentActive = this.buttons.index($('#home-slide-container').find('.button.active')[0]);
			var nextActive = this.buttons.index(el);
			var currentTarget = this.slides[currentActive];
			var nextTarget = this.slides[nextActive];
			this.slides.each(function() {
				if (this == currentTarget) {
					$(currentTarget).removeClass('active');
				} else if (this == nextTarget) {
					$(nextTarget).hide();
					$(nextTarget).addClass('active');
				} else {
					$(this).hide();
				}
			});
			$(nextTarget).fadeIn($this.fadeSpeed);
			this.setButton($.inArray(el,this.buttons));
		},
		setButton: function(index) {
			this.buttons.removeClass("active");
			$(this.buttons[index]).addClass("active");
		}
	},
	emailOptIn: {
		form: {},
		input: {},
		label: {},
		lightbox: null,
		overlay: null,
		init: function() {
			this.setStorage();
			this.setListeners();
		},
		setStorage: function() {
			this.form = $('#opt-in-form');
			this.input = this.form.find('input');
			this.label = this.form.find('label');
		},
		setListeners: function() {
			var $this = this;
			this.form.submit(function(e){
				e.preventDefault();
				$this.launchForm();
			});
			this.input.val("");
			this.input.focus(function() {
				if (!this.value) {
					$this.label.hide();
				}
			});
			this.input.blur(function() {
				if (!this.value) {
					$this.label.show();
				}
			});
		},
		launchForm: function() {
			var $this = this;
			if ($this.lightbox) {
				$this.showLightbox();
				return false;
			}
			$.ajax({
				url: '/ajax/email-opt-in-form',
				data: {
					"email":  $this.input.val()
				},
				type: 'POST',
				dataType: 'html',
				success: function(data) {
					$this.buildLightbox(data);
				}
			});
			$(window).resize(function(){
				$this.setLightboxPos();
			});
		},
		buildLightbox: function(data) {
			var $this = this;
			this.lightbox = new $.element('div',{
				className: "lightbox",
				id: "opt-in-lightbox"
			},data);
			this.overlay = new $.element('div',{
				className: "lightbox-overlay",
				id: "opt-in-lightbox-overlay"
			});
			this.setLightboxPos();
			this.hideLightbox();
			$('body').append(this.lightbox);
			$('body').append(this.overlay);
			$('#optinForm').submit(function(e) {
				e.preventDefault();
				$this.validateOptinForm(this);
			});
			$('#lightbox-close').click(function(e){
				e.preventDefault();
				$this.hideLightbox();
			});
			$('#opt-in-done').click(function(e){
				e.preventDefault();
				$this.hideLightbox();
			});
			this.showLightbox();
			$("#optin-email-confirm")[0].focus();
		},
		setLightboxPos: function() {
			var leftPos = ($(window).width() / 2) - (500/2);
			var topPos = ($(window).height() / 2) - (400/2);
			$(this.lightbox).css("left", leftPos);
			$(this.lightbox).css("top", topPos);
			$(this.overlay).css("width", $(window).width());
			$(this.overlay).css("height", $(document).height());
		},
		showLightbox: function() {
			$('#optin-email').val($('#opt-in-email').val());
			$(this.overlay).show();
			$(this.lightbox).show();
		},
		hideLightbox: function() {
			$(this.lightbox).find('.error').hide();
			$(this.lightbox).hide();
			$(this.overlay).hide();
		},
		validateOptinForm: function(el) {
			var failPoints = 0;
			if (!$('#optin-email').val() || !jawbone.util.isValidEmail($('#optin-email').val())) {
				failPoints++;
				$('#optin-email-error1').show();
			}
			if ($('#optin-email').val() && $('#optin-email').val() != $('#optin-email-confirm').val()) {
				failPoints++;
				$('#optin-email-error2').show();
			}
			if (failPoints == 0) {
				$(this.lightbox).find('.error').hide();
				this.postEmailOptin(el);
			}
		},
		postEmailOptin: function(el) {
			var $this = this;
			$(el).hide();
			$('#opt-in-loader').show();
			$.ajax({
				url : $(el).attr("action"),
				data : {
					"email" : $("#optin-email").val(),
					"first" : $("#optin-first").val(),
					"last" : $("#optin-last").val(),
					"zip" : $("#optin-zip").val()
				},
				type : "POST",
				dataType : "html",
				success : function(data) {
					$("#opt-in-loader").html(data);
					var error = $("#opt-in-loader").find("optinResultError").text();
					var subid = $("#opt-in-loader").find("optinResultSubid").text();
					var email = $("#opt-in-loader").find("optinResultEmail").text();
					if (!error) {
						$('#opt-in-success').find('.email').html(email);
						$("#opt-in-loader").hide();
						$("#opt-in-success").show();
						$this.doEventTracking(email);
					}
				},
				error : function(xhr, textStatus, errorThrown) {
					alert('There was an unexpected error saving your preferences.');
				},
				timeout : 30000
			});
		},
		doEventTracking: function(email) {
			var eventTrackingObj = {
				category: "Email Opt-In",
				action: "Opt in Conversion",
				label: email
			};
			jawbone.google.eventTracking.trackSingle(eventTrackingObj);
		}
	},
	compareHeadSets: {
		overlay: null,
		init: function() {
			this.setListeners();
		},
		setListeners: function() {
			var $this = this;
			$('.showCompare').click(function(e){
				e.preventDefault();
				$this.showCompare();
			});
		},
		showCompare: function() {
			var $this = this;
			if (!$this.overlay) {
				$this.overlay = new $.element('div',{
					className: "lightbox-overlay",
					id: "opt-in-lightbox-overlay"
				});
				$this.resizeOverlay();
				$(window).resize(function(){
					$this.resizeOverlay();
				});
				$('body').append($this.overlay);
			} else {
				$($this.overlay).show();
			}
			setTimeout(function() {
				$(".w_close").click(function() {
					$this.hideOverlay();
				});
			}, 1000);
		},
		resizeOverlay: function() {
			$(this.overlay).css("width", $(window).width());
			$(this.overlay).css("height", $(document).height());
		},
		hideOverlay: function() {
			$(this.overlay).hide();
		}
	},
	facebook: {
		init: function() {
			this.setLikeButton();
		},
		setLikeButton: function(arg) {
			if ($('#social-media').length == 0) { return false; }
			var $this = this;
			window.fbAsyncInit = function() {
				FB.init({
					appId: '189126087764607',
					status: true,
					cookie: true,
					xfbml: true
				});
				$this.setFrameListener();
			};
			var fbScript = new $.element('script',{
				type: "text/javascript",
				src: document.location.protocol + '//connect.facebook.net/en_US/all.js',
				async: true
			});
			$('#fb-root').append(fbScript);
		},
		setFrameListener: function() {
			var target = $('#socialMediaFB').find('iframe');
			if (target.length == 0) {
				var $this = this;
				var lag = window.setTimeout(function() {
					$this.setFrameListener();
				}, 100);
				return;
			}
			target.load(function(e){
				$('#social-media').fadeIn();
			});
		}
		

	},
	google: {
		init: function() {
			this.setEventListeners();
		},
		setEventListeners: function() {
			this.setMainNavListeners();
			this.setShelfListeners();
			this.setMainSocialListeners();
			this.setHomePageSliderListeners();
			this.setEmailOptInListeners();
		},
		setMainNavListeners: function() {
			var $this = this;
			$('#main-nav').find('a').click(function(e) {
				e.preventDefault();
				var eventTrackingObj = {
					category: "Main Nav",
					action: $(this).attr('rel'),
					label: "Click",
					el: this
				};
				$this.eventTracking.trackSingle(eventTrackingObj);
			});
		},
		setShelfListeners: function() {
			var $this = this;
			var eventTrackingObj = {};

			// right side nav elements
			$('#productSliderRightDock').find('.productSliderRightItem').click(function(e) {
				eventTrackingObj = {
					category: 'Product Shelf',
					action: 'Right Side Nav',
					label: e.currentTarget.id.split("productSliderRight")[1]
				};
				$this.eventTracking.trackSingle(eventTrackingObj);
			});

			// main image elements
			$('#productSliderInitDivPositioner').find('.main-shelf-item').click(function(e) {
				eventTrackingObj = {
					category: 'Product Shelf',
					action: 'Main Shelf Item: ' + e.currentTarget.id.split('Img')[0].toUpperCase(),
					label: 'Click'
				};
				$this.eventTracking.trackSingle(eventTrackingObj);
			});

			// main links
			$('#productSliderShell').find('.main-link').click(function(e) {
				e.preventDefault();
				eventTrackingObj = {
					category: 'Product Shelf',
					action: e.currentTarget.rel.split(":")[0],
					label: $.trim(e.currentTarget.rel.split(":")[1]),
					el: this
				};
				$this.eventTracking.trackSingle(eventTrackingObj);
			});;

			// All DETAILS and ADDTOCART tabs
			$('#productSliderShell').find('.actionItemLink').click(function(e) {
				e.preventDefault();
				eventTrackingObj = {
					category: 'Product Shelf',
					action: e.currentTarget.rel.split(":")[0],
					label: $.trim(e.currentTarget.rel.split(":")[1]),
					el: this
				};
				$this.eventTracking.trackSingle(eventTrackingObj);
			});
		},
		setMainSocialListeners: function() {
			var $this = this;
			$('#main-social-links').find('a').click(function(e) {
				e.preventDefault();
				var eventTrackingObj = {
					category: "Social Media",
					action: "Main Nav Links",
					label: $(e.currentTarget).attr('rel'),
					el: e.currentTarget
				};
				$this.eventTracking.trackSingle(eventTrackingObj);
			});
		},
		setHomePageSliderListeners: function() {
			var $this = this;
			$('#slideDiv').find('a').click(function(e) {
				e.preventDefault();
				var eventTrackingObj = {
					category: "Homepage Carousel",
					action: $(this).attr("rel").split(": ")[0],
					label: $(this).attr("rel").split(": ")[1],
					el: this
				};
				$this.eventTracking.trackSingle(eventTrackingObj);
			});
		},
		setEmailOptInListeners: function() {
			var $this = this;
			$('#opt-in-form').submit(function(e){
				e.preventDefault();
				var eventTrackingObj = {
					category: "Email Opt-In",
					action: "Show Form",
					label: ""
				};
				$this.eventTracking.trackSingle(eventTrackingObj);
			});
			$('body').delegate(
				"#optinForm",
				"submit", {
					category: "Email Opt-In",
					action: "Sumbit Form",
					label: ""
				},
				$this.eventTracking.trackSingle
			);
		},
		eventTracking: {
			trackSingle: function (obj) {
				var data = null;
				if (obj.data) {
					data = obj.data;
				} else {
					data = obj;
				}
				if (pageTracker) {
					obj.value = obj.value || 0;
					pageTracker._trackEvent(obj.category,obj.action,obj.label,obj.value);
					if (obj.el) {
						var linkLagger = window.setTimeout(function() {
							window.location.href = obj.el.href;
						}, 100);
					}
				}
			},
			trackMulti: function (objArray) {
				var $this = this;
				$(objArray).each(function(index) {
					this.trackSingle(objArray[index]);
				});
			}
		}
	}
};

// jquery extensions

$.extend({
	element: function(tag,att,text) {
		var newTag = document.createElement(tag);
		for (var i in att) {
			$(newTag).attr(i.split("Name")[0],att[i]);
		}
		if (text) {
			$(newTag).html(text);
		}
		return newTag;
	},
	lightbox: function(options) {

		// storage
		this.dialog = {};
		this.dialogContent = {};
		this.dialogs = {};
		this.overlay = null;
		this.contentTarget = {};
		this.closeButton = {};

		// private
		this._init = function() {
			if (!options) {
				options = {};
			}
			this._checkDialogs();
			this._checkOverlay();
			this._setDialog();
			this._setEventListeners();
		};
		this._setEventListeners = function() {
			var $this = this;
			// window resize
			$(window).bind('resize.lightbox_resizer',function(){
				$this._resizeHandler();
			});
			$(window).bind('resize.lightbox_positioner',function(){
				$this._dialogPositioner();
			});

			// blur close
			$(this.dialogs).click(function(e){
				$this._blurClose(e);
			});

			// esc key close
			$(document).keyup(function(e){
				if (e.keyCode === 27) {
					$this.close();
				}
			});

			// close callback additions
			if (options.closeCallback) {
				this.addCloseCallback(options.closeCallback);
			}
		};
		this._checkDialogs = function() {
			var testDialogs = $('#lightbox-dialogs');
			if (testDialogs.length === 0) {
				this.dialogs = new $.element('div',{
					id: 'lightbox-dialogs'
				});
				$(this.dialogs).hide();
				$('body').append(this.dialogs);
			} else {
				this.dialogs = testDialogs;
			}
		};
		this._checkOverlay = function() {
			var testOverlay, $this, timer;
			testOverlay = $('#lightbox-overlay');
			$this = this;
			if (testOverlay.length !== 0) {
				this.overlay = testOverlay[0];
			} else {
				this.overlay = new $.element('div', {
					id: "lightbox-overlay"
				});
				$(this.overlay).hide();
				$('body').append(this.overlay);
			}
			timer = window.setTimeout(function() {
				$this._resizeHandler();
			}, 0);
		};
		this._setDialog = function() {
			var $this, header, test;
			$this = this;
			this.dialog = new $.element('div',{
				className: "lightbox"
			});
			if (options.width) {
				$(this.dialog).css('width',options.width);
			}
			if (options.height) {
				$(this.dialog).css('height',options.height + "px");
			}
			header = new $.element('h2',{},
				new $.element('span',{
					className: "title"
				}, options.title || null
			));
			$(this.dialog).append(header);
			this.closeButton = new $.element('a',{
				href: "#",
				className: "lightbox-close"
			}, options.closeText || 'close');
			$(this.closeButton).click(function(e){
				e.preventDefault();
				$this.close();
			});
			$(header).append(this.closeButton);
			this.dialogContent = new $.element('div',{
				id: "lightbox-content-" + Math.floor(Math.random()*10000000),
				className: "lightbox-content loading"
			});
			if (options.content) {
				this.update(options.content);
			}
			if (options.className) {
				$(this.dialog).addClass(options.className);
			}
			$(this.dialog).append(this.dialogContent);
			$(this.dialog).hide();
			$(this.dialogs).append(this.dialog);
			this._resizeHandler();
			this._dialogPositioner();
			test = $this._dialogPositioner;
			$(this.dialog).draggable({
				handle: 'h2',
				containment: 'window',
				start: function() {
					$(window).unbind('resize.lightbox_positioner');
				}
			});
			this.open();
		};
		this._resizeHandler = function() {
			if (options.resizeCallback) {
				options.resizeCallback();
			}
			$(this.overlay).css("width",$(window).width());
			$(this.overlay).css("height",$(document).height());
			$(this.dialogs).css("width",$(window).width());
			$(this.dialogs).css("height",$(document).height());
		};
		this._dialogPositioner = function() {
			$(this.dialog).css("left", ($(window).width() / 2) - ($(this.dialog).width() / 2) + "px");
			$(this.dialog).css("top", ($(window).height() / 2) - ($(this.dialog).height() / 2) + "px");
		};
		this._blurClose = function(e) {
			if (e.srcElement === this.dialogs || e.target === this.dialogs) {
				this.close();
			}
		};

		// public
		this.update = function(str,fn) {
			if (!str) { return false; }
			$(this.dialogContent).html(str);
			$(this.dialogContent).removeClass('loading');
			if (fn) {
				fn();
			}
		};
		this.updateTitle = function(str) {
			$(this.dialog).find('.title').html(str);
		};
		this.setLoading = function() {
			$(this.dialogContent).html('');
			$(this.dialogContent).addClass('loading');
		};
		this.close = function() {
			$(this.dialog).fadeOut();
			$(this.dialogs).fadeOut();
			$(this.overlay).fadeOut();
		};
		this.open = function() {
			var $this = this;
			$(this.dialogs).find('.lightbox').each(function(){
				if ($this.dialog !== this) {
					$(this).hide();
				}
			});
			$(this.dialog).fadeIn();
			$(this.dialogs).fadeIn();
			$(this.overlay).fadeIn();
		};
		this.addCloseCallback = function(fn,bool) {
			if (bool) {
				this.clearCloseCallbacks();
			}
			$(this.closeButton).click(function(){
				fn();
			});
		};
		this.clearCloseCallbacks = function() {
			var $this = this;
			$(this.closeButton).unbind('click');
			$(this.closeButton).click(function(e){
				e.preventDefault();
				$this.close();
			});
		};

		// init
		this._init();
		return this;
	}
});

// document ready and runtime inits

$(document).ready(function() {
	jawbone.init();
});

(function(){
	jawbone.runtimeInit();
})();


