/**
 * @author digital-telepathy
 */
var CufonFonts = [
	{
		name: 'Futura',
		elements: ['#content h1', '#content h2', '#content h3', '.rightBox h4', '#label_terms span', '#cart_items li#cart_subtotal h4', '#footer h3', '.grandTotalTitle', '#content #col_left #call-to-action_container h1', '#content #col_right ul#home_features h4', '#footer h3', '#your_future h2 span.yourFuture', '#activation_accept_container label', '#member_profile_link', '.alphaNav', '#alphabetical_list a', '#tracking_results_list .trackingLabel' ,'#progess_percentage', 'span.questionNumber', 'h4.surveyQuestion', '#population-risk_level h5.riskLevel', 'span#bread_crumb_label', '#members_footer .sectionTitle','.pieLabelContainer .pieLabel','.haploGroupContainer .haploGroup','.futura' ]
	}
];

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
 
};

document.observe("dom:loaded",function(){
	// XHTML 1.0 Strict work around for external links
	$$('a[rel*="external"]').invoke('writeAttribute','target','_blank');

	// Automatic text clear
	$$('input.clearField').each(function(e){
		e.observe('focus',function(){
			this.value = "";
		}).observe('blur',function(){
			if(this.value == "") {
				this.value = this.defaultValue;
			}
		});
	});

	// Image roll-over setup
	$$('img.rollOver, input[type="image"].rollOver').each(function(e){
		e.observe('mouseover',function(){
			if (this.src.include("_i.")) {
				this.src = this.src.replace("_i.", "_o.");
			}
		}).observe('mouseout',function(){
			if (this.src.include("_o.")) {
				this.src = this.src.replace("_o.", "_i.");
			} else if(this.src.include("_a.")) {
				this.src = this.src.replace("_a.","_i.");
			}
			if(this.src.include("_a.")) {
				this.src = this.src.replace("_a.","_i.");
			}
		})
		if(e.match("input")) {
			e.observe('mousedown',function(){
				this.src = this.src.replace("_o.","_a.");
			}).observe('mouseup',function(){
				this.src = this.src.replace("_a.","_i.");
			});
		}
	});

	// Home page next button cross-faders
	$$('.fader_container .nextButton-small').each(function(e){
		e.observe('click',function(event){
			Event.stop(event);
			var pieces = e.up('.fader_container').childElements();
			var nextPiece = 0;
			if(pieces.indexOf(e.up()) < pieces.length-1) {
				nextPiece = pieces.indexOf(e.up())+1;
			}
			new Effect.Fade(e.up(),{duration:0.5});
			new Effect.Appear(pieces[nextPiece],{duration:0.5});
		}).onclick = function(){
			return false;
		}
	});
	
	//Check to see if the How It Works Nav is on the page
	if($('how-it-works_nav')){
		$$('a.howItWorksButton').each(function(e){
			//add click event to howItWorksButton(s)
			e.observe('click',function(event){
				Event.stop(event);
				if(!this.hasClassName('active')){
					var hiwIDshort = this.id.split("_").last();
					toggleHowItWorks(hiwIDshort, e);
				}
			}).onclick = function(){ return false; }
		});
	}
	
	//Secondary Nav - dropDowns
	if($('subnavigation')){
		$$('a.sectionTitle').each(function(e){
			if(e.up().select('ul.dropDown').length > 0){
				e.observe('click',function(event){
					Event.stop(event);
					var dropDown = e.next('ul.dropDown')
					if(e.hasClassName('active') || dropDown.style.display == 'block'){
					  e.removeClassName('active');
					} else {
					  e.addClassName('active');
					}
					new Effect.toggle(dropDown,'blind',{duration:0.5});


				}).onclick=function(){ return false; };
			}
		});
	}
	
	if($('signin_form')) {
		$('signin_form').setStyle({display:'none'}).select('a.signin_cancel').each(function(e){
			e.observe('click',function(event){
				signInForm.hide();
				$('link_user-login').removeClassName('active');
				$('link_physician-login').removeClassName('active');
				hideSigninErrorLayer();
			}).onclick = function(){ return false; }
		});
		if($('link_user-login')) {
			$('link_user-login').observe('click',function(event){
				Event.stop(event);
				if (signInForm.animating == false) {
					this.addClassName('active');
					$('link_physician-login').removeClassName('active');
					$('user_signin').show();
					$('physician_signin').hide();
					signInForm.show();
				}
			}).onclick = function(){return false;}
		}
		if($('link_physician-login')) {
			$('link_physician-login').observe('click',function(event){
				Event.stop(event);
				if (signInForm.animating == false) {
					this.addClassName('active');
					$('link_user-login').removeClassName('active');
					$('physician_signin').show();
					$('user_signin').hide();
					signInForm.show();
				}
			}).onclick = function(){return false;}
		}
	}
	
	if($('your_future')) {
		initYourFutureCycler('your_future');
	}
	
	if(typeof(Cufon) !== 'undefined'){
		CufonFonts.each(function(font){
			var existingElements = [];
			font.elements.each(function(cfe){
				if($$(cfe).length > 0) existingElements.push(cfe);
			});
			var cufonOptions = {
				fontFamily : font.name
			}
			if(!Object.isUndefined(font.options)){
				var optionKeys = Object.keys(font.options);
				var optionVals = Object.values(font.options);
				for(i=0 ; i < optionKeys.length ; i++){
					cufonOptions[optionKeys[i]] = optionVals[i];
				}
			}
			Cufon.replace(existingElements.join(","),cufonOptions);
		});
	}
	
	if($$('input.bigCheck').length > 0) {
		customInput.init();
		accountActivation.init();
	}
	BrowserDetect.init();
	if((BrowserDetect.browser != 'Opera') && (BrowserDetect.browser != 'Safari')){
		if($$('a.scrollTo')){
			$$('a.scrollTo').each(function(elem){
				elem.observe('click',function(event){
					//Get HREF val of link associated to anchor
					hrefVal = elem.readAttribute('href').gsub('#','');
					//Create new effect - and scroll to
					new Effect.ScrollTo(hrefVal);
					//Stops normal click event - no hash in URI
					Event.stop(event);
				});
			});
		}
	}
});



var accountActivation = {
	checkID: 'input_accept',
	submitID: 'btn_continue',
	enable: function(){
		$(this.submitID).enable()
			.setStyle({
				cursor:'pointer'
			});
		if($(this.submitID).src.include('_d.')){
			$(this.submitID).src = $(this.submitID).src.replace('_d.','_i.');
		}
	},
	disable: function(){
		$(this.submitID).disable()
			.setStyle({
				cursor:'default'
			});
		if($(this.submitID).src.include('_i.')) {
			$(this.submitID).src = $(this.submitID).src.replace('_i.','_d.');
		}
	},
	init: function(){
		if($(this.submitID)) {
			if($(this.checkID)){
				if($(this.checkID).checked == false) {
					this.disable();
				} else {
					this.enable();
				}
			}
		}
	}
}



var customInput = {
	elements: 'input.bigCheck',
	checkBoxes: {
		template: '<span id="customcheckfor___#{id}">X</span>',
		assign: function(elem,options){
			var thisObj = {
				id: $(elem).identify(),
				left: $(elem).positionedOffset().left,
				top: $(elem).positionedOffset().top,
				templateObj: new Template(customInput.checkBoxes.template),
				options: options
			}
			$(elem).insert({
				before:thisObj.templateObj.evaluate(thisObj)
			}).setStyle({
				zIndex: 1,
				visibility: 'hidden'
			});
			$('customcheckfor___'+thisObj.id).setStyle({
				position: 'absolute',
				lineHeight: '19px',
				fontSize: '10px',
				zIndex: 9999,
				width: '19px',
				height: '19px',
				overflow: 'hidden',
				textIndent: '-9999px',
				backgroundImage: 'url(/images/input_checkbox.png)',
				backgroundPosition: '0 0',
				cursor: 'pointer'
			}).
			clonePosition(elem,{
				setLeft: true,
				setTop: true,
				setWidth: false,
				setHeight: false
			}).
			observe('mouseover',function(event){
				if(!$(this).hasClassName('checked')) {
					$(this).setStyle({
						backgroundPosition: '0 -19px'
					});
				}
			}).
			observe('mouseout',function(event){
				if(!$(this).hasClassName('checked')) {
					$(this).setStyle({
						backgroundPosition: '0 0'
					});
				}
			}).
			observe('mousedown',function(event){
				if (!$(this).hasClassName('checked')) {
					$(this).setStyle({
						backgroundPosition: '0 -57px'
					});
				}
			}).
			observe('click',function(event){
				Event.stop(event);
				customInput.checkBoxes.click(this,options);
			}).onclick = function(){ return false; }
			
			$$('label').each(function(e){
				if (e.readAttribute('for') == thisObj.id) {
					e.observe('mouseover',function(event){
						if(!$('customcheckfor___'+thisObj.id).hasClassName('checked')) {
							$('customcheckfor___'+thisObj.id).setStyle({
								backgroundPosition: '0 -19px'
							});
						}
					}).
					observe('mouseout',function(event){
						if(!$('customcheckfor___'+thisObj.id).hasClassName('checked')) {
							$('customcheckfor___'+thisObj.id).setStyle({
								backgroundPosition: '0 0'
							});
						}
					}).
					observe('click', function(event){
						Event.stop(event);
						customInput.checkBoxes.click($('customcheckfor___' + thisObj.id),thisObj.options);
					}).setStyle({
						cursor: 'pointer'
					}).onclick = function(){ return false; };
				}
			});
			
			if($(thisObj.id).checked == true){
				$('customcheckfor___'+thisObj.id).addClassName('checked');
			}
			
			if(Prototype.Browser.Gecko || Prototype.Browser.Opera){
				// Is Firefox or Opera, make position accommodations
				$('customcheckfor___'+thisObj.id).setStyle({
					marginLeft: '19px',
					marginTop: '-3px'
				});
			}
		},
		click: function(elem,options){
			var parentID = $(elem).identify().split('___').last();
			if ($(parentID).checked == true) {
				$(parentID).checked = false;
				$(parentID).removeAttribute('checked');
				$(elem).setStyle({
					backgroundPosition: '0 0'
				}).removeClassName('checked');
			} else {
				$(parentID).checked = true;
				$(parentID).writeAttribute('checked','checked');
				$(elem).setStyle({
					backgroundPosition: '0 -76px'
				}).addClassName('checked');
			}
			
			if(!Object.isUndefined(options)) {
				if(!Object.isUndefined(options)){
					if (Object.isFunction(options.afterFinished())) {
						options.afterFinished();
					}
				}
			}
		}
	},
	init: function(){
		$$(this.elements).each(function(e){
			if(e.match('input[type="checkbox"]')) {
				customInput.checkBoxes.assign(e,{
					afterFinished: function(){
						accountActivation.init();
					}
				});
			}
		});
	}
}



var cycler = {
	period: 4,				// Period between cross-fades in seconds
	id: "",
	current: 0,
	elements: 0,
	last: 0,
	from: 1,
	to: 0,
	cycle: function(){
		new Effect.Opacity(cycler.elements[cycler.current],{
			duration: 1,
			from: cycler.from,
			to: cycler.to,
			delay: cycler.period,
			afterFinish: function(){
				if(cycler.current == 1) {
					cycler.current = cycler.last;
					cycler.from = 0;
					cycler.to = 1;
				} else {
					if(cycler.current == cycler.last && cycler.elements[1].getStyle('opacity') == 0) {
						cycler.current = cycler.last;
						cycler.elements.invoke('setStyle','opacity:1');
					} else {
						cycler.current--;
					}
					cycler.from = 1;
					cycler.to = 0;
				}
				cycler.cycle();
			}
		});
	}
}
function initYourFutureCycler(cyclerID){
	cycler.id = cyclerID;								// Cycler parent container ID
	cycler.elements = $(cycler.id).childElements();		// Array of immediate child elements of parent container
	cycler.last = cycler.elements.length - 1;			// Index of last child element in child elements array
	cycler.current = cycler.last;						// Currently visible child element
	
	cycler.cycle();
}


var signInForm = {
	id: 'signin_form',
	visible: false,
	animating: false,
	toggle: function(){
		if(signInForm.visible == false) {
			signInForm.show();
		} else {
			signInForm.hide();
		}
	},
	hide: function(){
		if(signInForm.visible == true)
			signInForm.move(0,0,1);
	},
	show: function(){
		if(signInForm.visible == false)
			signInForm.move(40,1,0);
	},
	move: function(destY,destOp,startOp){
		signInForm.animating = true;
		$(signInForm.id).setStyle({
			display:'block',
			'opacity': startOp
		});
		new Effect.Parallel([
			new Effect.Move(signInForm.id,{
				x: 70,
				y: destY,
				mode: 'absolute'
			}),
			new Effect.Opacity(signInForm.id,{
				sync: true,
				from: startOp,
				to: destOp
			})
		],{
			duration: 0.5,
			afterFinish: function(){
				if(destOp == 1) {
					signInForm.visible = true;
				} else {
					signInForm.visible = false;
				}
				signInForm.animating = false;
			}
		});
	}
}


document.observe('lightview:opened',function(event){
	if ($('dna_stories_movie-list')) {
		initScrollerObj('dna_stories_movie-list', 'btn_scroller-left', 'btn_scroller-right');
	}
	if($$('a.videoThumbnail').length > 0) {
		$$('a.videoThumbnail').each(function(e){
			e.observe('click',function(event){
				Event.stop(event);
				
				var videoName = this.href.split("#").last();
				
				var so = new SWFObject('/flash/player.swf','mpl','765','310','9');
				so.addParam('bgcolor','#000000');
				so.addParam('allowscriptaccess','always');
				so.addParam('allowfullscreen','true');
				so.addParam('flashvars','&file=/videos/'+videoName+'.mov&autostart=true&backcolor=000000&frontcolor=FFFFFF&lightcolor=81c016&screencolor=000000&skin=http://www.longtailvideo.com/jw/upload/overlay.swf&controlbar=over');
				so.write('player');
				
				$$('a.videoThumbnail').invoke('removeClassName','active');
				$(this).addClassName('active');
			}).onclick = function(){ return false; }
		});
	}
	if ($('btn_close-lightbox')) {
		$('btn_close-lightbox').observe('click', function(event){
			Event.stop(event);
			Lightview.hide();
			ScrollerObj.resetObject();
		}).onclick = function(){
			return false;
		};
	}
	if($$('a.lightboxSideButton').length > 0) {
		initProductBox();
	}
});


var ScrollerObj = {
	animating: false,
	scroller_id: "",
	container_id: "",
	left_id: "",
	right_id: "",
	childWidth: 0,
	maxLeftOffset: 0,
	updateButtons: function(){
		if($(ScrollerObj.scroller_id).positionedOffset().left >= 0) {
			$(ScrollerObj.left_id).addClassName('disabled');
		} else {
			$(ScrollerObj.left_id).removeClassName('disabled');
		}
		if($(ScrollerObj.scroller_id).positionedOffset().left == (0 - ScrollerObj.maxLeftOffset)) {
			$(ScrollerObj.right_id).addClassName('disabled');
		} else {
			$(ScrollerObj.right_id).removeClassName('disabled');
		}

		ScrollerObj.animating = false;
	},
	move: function(moveDistance){
		ScrollerObj.animating = true;
		new Effect.Move(ScrollerObj.scroller_id, {
			x: moveDistance,
			y: 0,
			mode: 'relative',
			duration: 0.5,
			afterFinish: function(){
				ScrollerObj.updateButtons();
			}
		});
	},
	resetObject: function(){
		this.animating = false;
		this.scroller_id = "";
		this.container_id = "";
		this.left_id = "";
		this.right_id = "";
		this.childWidth = 0;
		this.maxLeftOffset = 0;
		this.width = 0;
	}
}
function initScrollerObj(scrollerListID,leftButtonID,rightButtonID) {
	ScrollerObj.scroller_id = scrollerListID;
	ScrollerObj.left_id = leftButtonID;
	ScrollerObj.right_id = rightButtonID;
	
	ScrollerObj.container_id = $(ScrollerObj.scroller_id).up(0).identify();
	ScrollerObj.width = $(ScrollerObj.container_id).getDimensions().width;
	$(ScrollerObj.scroller_id).childElements().each(function(e){
		ScrollerObj.childWidth += e.getDimensions().width;
	});
	ScrollerObj.maxLeftOffset = ((Math.ceil((ScrollerObj.childWidth / ScrollerObj.width))) * ScrollerObj.width) - ScrollerObj.width;

	if ($(ScrollerObj.left_id)) {
		$(ScrollerObj.left_id).observe('click', function(event){
			Event.stop(event);
			if (ScrollerObj.animating != true) {
				if ($(ScrollerObj.scroller_id).positionedOffset().left < 0) {
					ScrollerObj.move(ScrollerObj.width);
				}
			}
		}).onclick = function(){
			return false;
		};
	}

	if ($(ScrollerObj.right_id)) {
		$(ScrollerObj.right_id).observe('click', function(event){
			Event.stop(event);
			if (ScrollerObj.animating != true) {
				if ($(ScrollerObj.scroller_id).positionedOffset().left <= 0 && $(ScrollerObj.scroller_id).positionedOffset().left > (0 - ScrollerObj.maxLeftOffset)) {
					ScrollerObj.move((0 - ScrollerObj.width));
				}
			}
		}).onclick = function(){
			return false;
		};
	}
	
	ScrollerObj.updateButtons();
}


function toggleHowItWorks(hiwIDshort, hiwID){
	var hiwCont = hiwIDshort+"-container";
	var buttonID = hiwID;
	var hiwButtons = $$('#how-it-works_nav a')
	
	// Just a check to make sure they didn't do something retarded on another page
	if(document.getElementById('diagram_wrapper')){
		var hiwContainer = document.getElementById('diagram_wrapper');
	}	
	hiwButtons.invoke('removeClassName','active');
	//check to see which container to hide/show
	if(hiwCont == "what-you-do-container"){
		new Effect.Fade('what-we-do-container', {duration: 0.5});
		new Effect.Appear(hiwCont, {duration: 0.5});
		$(buttonID).addClassName('active');
		// jQuery animate to change the height of the fucking container
		jQuery(hiwContainer).animate({height:'390px'});
	}else if(hiwCont == "what-we-do-container"){
		new Effect.Fade('what-you-do-container', {duration: 0.5});
		new Effect.Appear(hiwCont, {duration: 0.5});
		$(buttonID).addClassName('active');
		// same as above
		jQuery(hiwContainer).animate({height:'480px'});
	}
}


function initProductBox() {
	$$('a.lightboxSideButton').each(function(e){
		e.observe('click',function(event){
			var container_id = 'lightbox_content_container';
			if (!$(container_id).hasClassName('animating') && !e.href.include('#none')) {
				$(container_id).addClassName('animating');
				new Effect.Fade($(container_id).select('.lightbox_container')[0], {
					duration: 0.5,
					afterFinish: function(){
						new Ajax.Request(e.href, {
							method: 'get',
							onFailure: function(){
								new Effect.Appear($(container_id).select('.lightbox_container')[0], {
									duration: 0.5,
									afterFinish: function(){
										$(container_id).removeClassName('animating');
									}
								});
							},
							onComplete: function(transport){
								if (transport.status == 200) {
									var newInner = "";
									var newLeftLink = "";
									var newRightLink = "";
									
									var tempDiv = new Element('div', {
										id: 'temp_content_container',
										style: 'display:none;'
									});
									$(document.body).insert({
										bottom: tempDiv
									});
									tempDiv.update(transport.responseText.gsub(container_id, container_id + "_temp").gsub('btn_lightboxSideLeft', 'btn_lightboxSideLeft_temp').gsub('btn_lightboxSideRight', 'btn_lightboxSideRight_temp'));
									
									$(container_id + '_temp').select('.lightbox_container')[0].setStyle({
										display: 'none'
									});
									
									var newInner = $(container_id + '_temp').innerHTML;
									
									if ($('btn_lightboxSideLeft_temp')) 
										newLeftLink = $('btn_lightboxSideLeft_temp').href;
									if ($('btn_lightboxSideRight_temp')) 
										newRightLink = $('btn_lightboxSideRight_temp').href;
									
									$(container_id).update(newInner);
									tempDiv.remove();
									
									new Effect.Appear($(container_id).select('.lightbox_container')[0], {
										duration: 0.5,
										afterFinish: function(){
											var showLeft = newLeftLink.include('#none') ? 'none' : 'block';
											var showRight = newRightLink.include('#none') ? 'none' : 'block';
											
											$('btn_lightboxSideLeft').writeAttribute('href', newLeftLink).setStyle({
												display: showLeft
											});
											$('btn_lightboxSideRight').writeAttribute('href', newRightLink).setStyle({
												display: showRight
											});
											
											$('btn_close-lightbox').observe('click', function(event){
												Event.stop(event);
												Lightview.hide();
											}).onclick = function(){
												return false;
											};
											$(container_id).removeClassName('animating');
										}
									});
								}
							}
						});
					}
				});
			}
		}).onclick = function(){ return false; }
	});
}

// Analytics Event
jQuery('.lightview').click(function(){
	pageTracker._trackEvent('modal', 'open', this.className);
});
