/* jQuery Cookie plugin */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000))}else{date=options.expires}expires='; expires='+date.toUTCString()}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('')}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break}}}return cookieValue}};

/* Document ready */
$(function(){
		   
	// IE
	var isIE = /msie|MSIE/.test(navigator.userAgent);
	
	// IE6
	var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
	
	// PNGfix
	if(isIE6 && typeof(DD_belatedPNG) != 'undefined'){
		DD_belatedPNG.fix('.png');
	}
	
	//
	// Print page btn
	$('#header a.print').click(function(){ 
		s.linkTrackVars = 'events'; s.linkTrackEvents = 'event13'; s.events = 'event13'; (s.tl(this, 'o', 'Print Page:'+s.pageName));
		window.print();
		return false;
	});
	// Print page btn on print page
	$('#printPageHeader .PrintButton').click(function(){ 
		window.print();
		return false;
	});
	
	//
	// Search 
	var searchField = $('#search'),
		searchTxt = 'Search';
	searchField.bind('focus', function(){
		if(searchField.val() == searchTxt){
			searchField.val('');
		}
	}).bind('blur', function(){
		if(searchField.val() == ''){
			searchField.val(searchTxt);
		}
	})
	
	//
	// Font size
	var fontBtns = $('ul.font-size li a'),
		content = $('div.information, div.thanks, div.sitemap, div.glossary');
	if(fontBtns.length && content.length){
		var thisBtn,
			fontSize,
			resizebleElements = 'p,h1,h2,h3,h4,h5,h6,li,th,td, dl,dt,dd',
			excludeElements = '.no-resize, .no-resize *',
			thisElement,
			fSize,
			lHeight,
			prevFontSize = 'small',
			currentFontSize,
			resizeStep;
			
		fontBtns.bind('click', function(){
			thisBtn = $(this);
			if(!thisBtn.hasClass('active')){
				setFontSize(thisBtn.attr('class'));
			}
			return false;
		});
		
		var setFontSize = function(fontSize){
			
			// get previous state
			currentFontSize = getCookie();
			if(!currentFontSize || prevFontSize == 'small'){
				currentFontSize = 'small';
			}
			
			// calculate resize step
			if(currentFontSize == 'small'){
				if(fontSize == 'small')	{ resizeStep = 0; }
				if(fontSize == 'medium'){ resizeStep = 2; }
				if(fontSize == 'big')	{ resizeStep = 4; }
			}
			if(currentFontSize == 'medium'){
				if(fontSize == 'small')	{ resizeStep = -2; }
				if(fontSize == 'medium'){ resizeStep = 0; }
				if(fontSize == 'big')	{ resizeStep = 2; }
			}
			if(currentFontSize == 'big'){
				if(fontSize == 'small')	{ resizeStep = -4; }
				if(fontSize == 'medium'){ resizeStep = -2; }
				if(fontSize == 'big')	{ resizeStep = 0; }
			}			
			
			//
			fontBtns.removeClass('active');
			fontBtns.filter('.'+fontSize).addClass('active');
			content.removeClass('small medium big').addClass(fontSize);
			
			// change font size
			if(resizeStep != 0){
				content.find(resizebleElements).not(excludeElements).each(function(){
					thisElement = $(this);
					fSize = parseInt(thisElement.css('font-size'));
					lHeight = parseInt(thisElement.css('line-height'));
					if(fSize && lHeight){
						thisElement.css({fontSize: (fSize+resizeStep)+'px', lineHeight: (lHeight+resizeStep)+'px'});
					}
				});
			}
			
			// save new state
			prevFontSize = fontSize;
			setCookie(fontSize);
		}
		
		var setCookie = function(fontSize){
			$.cookie('FONT_SIZE', fontSize, {path: '/', expires: 10000});
		}
		
		var getCookie = function(){
			return $.cookie('FONT_SIZE');
		}
		
		// init
		fontSize = getCookie();
		if(fontSize){
			setFontSize(fontSize);
		} else {
			setFontSize('small');
		}
	}
	
	//
	// custom selects
	var cusomSelects = $('.custom-select'),
		thisSelect;
	if(cusomSelects.length && !isIE6){
		cusomSelects.each(function(){
			thisSelect = $(this);
			thisSelect.css({opacity:0}).wrap('<div class="select-wrapper"></div>');
			thisSelect.parent().prepend('<span></span>').find('span').text(thisSelect.find('option:selected').text());
			//
			thisSelect.bind('change', function(){
				thisSelect = $(this);
				thisSelect.prev('span').text($(this).find('option:selected').text());
				validateControl(thisSelect);
			});
		});
	}
	
	//
	// Submit btns
	var submitBtn = $('a.btn-submit').not('.js-only');
	if(submitBtn.length){
		submitBtn.bind('click', function(){
			$(this).parents('form').submit();
			return false;
		});
	}
	
	//
	// Learn More form validation
	var lmForm = $('#learn-more');
	if(lmForm.length){
		var required = lmForm.find('.required'),
			thisClass,
			thisVal,
			thisType,
			result,
			err,
			isError,
			errMsgs = $('div.error-msg');
			
		required.bind('focus', function(){
			removeError($(this));
		}).bind('blur', function(){
			validateControl($(this));
		});
		
		//
		// form submit event
		lmForm.bind('submit', function(){
			$('.error').removeClass('error');
			errMsgs.hide();
			
			// show err messages
			required.each(function(){
				validateControl($(this));
			});
			isError = finalValidate();
			
			if(!isError){
				// submit form
				lmForm.unbind('submit').submit(); 
				return false;
			}
			return false;
		});
		
		var validateControl = function(obj){
			thisType = obj.attr('type');
			thisClass =  obj.attr('class');
			thisVal = obj.val();
			err = 0;
			if(thisType == 'text'){ // inputbox
				
				// is empty
				if(!thisVal){
					err++;
				}
				
				// email
				if(thisClass.indexOf('email')!= -1){
					result = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(thisVal);
					if(!result){
						err++;
					}
				}
				
				// zip
				if(thisClass.indexOf('zip')!= -1){
					result = /^-?\d+$/.test(thisVal);
					if(!result){
						err++;
					}
				}
				
			} else if(thisType == 'select-one'){ // selectbox
				if(obj.find('option:selected').text() == 'choose'){
					err++;
				}
			}
			
			if(err){
				addError(obj);
			} else {
				removeError(obj);
			}
			
			return err;
		
		}
		
		var finalValidate = function(){
			
			var fErr = 0;
			
			// age-confirmation
			var age = $('input.age-confirmation:checked');
			if(!age.length){
				$('div.err-age-confirmation').show();
				fErr++;
			}
			
			// fname
			var fname = $('input.fname');
			if(validateControl(fname)){
				$('div.err-fname').show();
				fErr++;
			}
			
			// lname
			var lname = $('input.lname');
			if(validateControl(lname)){
				$('div.err-lname').show();
				fErr++;
			}
			
			// emails
			var email1 = $('input.email1'),
				email2 = $('input.email2');
			if(email1.val() && email2.val()){
				// is emails equal
				if(email1.val() != email2.val()){
					$('div.err-email-equal').show();
					addError(email1);
					addError(email2);
					fErr++;
				}
			} else {
				//email1
				if(validateControl(email1)){
					$('div.err-email1').show();
					fErr++;
				}
				// email2
				if(validateControl(email2)){
					$('div.err-email2').show();
					fErr++;
				}
			}	
				
			// full address
			// address1, city, state, zip
			var address1 = $('input.address1'),
				city = $('input.city'),
				state = $('input.state'),
				zip = $('input.zip');
			if(validateControl(address1) || validateControl(city) || validateControl(state) || validateControl(zip)){
				$('div.err-address').show();
				fErr++;
			}
			
			// zip
			if(validateControl(zip) || zip.val().length < 5){
				$('div.err-zip').show();
				addError(zip);
				fErr++;
			}
			
			return fErr;
			
		}
		
		var addError = function(obj){
			obj.addClass('error');
			if(obj.hasClass('custom-select')){
				// custom selectbox error
				obj.parents('div.select-wrapper').addClass('error');
			}
		}
		
		var removeError = function(obj){
			obj.removeClass('error');
			if(obj.hasClass('custom-select')){
				// custom selectbox error
				obj.parents('div.select-wrapper').removeClass('error');
			}
		}
	}
	
	//
	// Low T quiz
	var lowTQuiz = $('#low-t-quiz');
	if(lowTQuiz.length){
		var currPart = 1,
			backBtn = $('#backBtn'),
			nextBtn = $('#nextBtn'),
			finishBtn = $('#finishBtn'),
			quizPart = new Array();
		quizPart[1] = lowTQuiz.find('div.quiz-part1');
		quizPart[2] = lowTQuiz.find('div.quiz-part2');
			
		nextBtn.bind('click', function(){
			if(checkPart(currPart) < 5){
				alert('Please answer all of the questions.');
				return false;
			}
			//
			s.linkTrackVars = 'events'; s.linkTrackEvents = 'event9'; s.events = 'event9'; s.tl(this, 'o', 'Low T Quiz Step 2');
			quizPart[1].hide();
			quizPart[2].show();
			currPart = 2;
			//
			backBtn.show();
			nextBtn.hide();
			finishBtn.show();
			
			return false;
		});
		
		backBtn.bind('click', function(){
			quizPart[2].hide();
			quizPart[1].show();
			currPart = 1;
			//
			backBtn.hide();
			nextBtn.show();
			finishBtn.hide();
			
			return false;
		});
		
		finishBtn.bind('click', function(){
			if(checkPart(currPart) < 5){
				alert('Please answer all of the questions.');
				return false;
			}
			lowTQuiz.submit();
			return false;
		});
		
		var checkPart = function(currPart){
			return quizPart[currPart].find('input:radio:checked').length;
		}
	}
	
	// print res btn
	var printResultBtn = $('#printResultBtn');
	if(printResultBtn.length){
		printResultBtn.attr('href', printResultBtn.attr('href')+location.search); 
	}

	var emailResultBtn = $('#emailResultBtn');
	if (emailResultBtn.length) {
	    emailResultBtn.attr('href', emailResultBtn.attr('href') + location.search);
	}
	
	// printer friendly results
	var printResult = $('#printResult');
	if(printResult.length){
		var tmp = new Array(),
			tmp2 = new Array(),
			param = new Array(),
			get = location.search;
		if(get != '') {
			tmp = (get.substr(1)).split('&');
			for(var i=0; i < tmp.length; i++) {
				tmp2 = tmp[i].split('=');
				param[tmp2[0]] = tmp2[1]; 
			}
			for (var key in param) {
				var res = param[key]=='1' ? 'YES' : 'NO';
				$('#'+key).append('<strong> '+ res +'</strong>');
			}
			//print
			//window.print();
			// close result page
			//self.close();
			return false;
		}
	}
	
	//
	// BMI Calc
	var bmiCalc = $('#bmi-calc');
	if(bmiCalc.length){
		var calcBlock = bmiCalc.find('div.calc'),
			resultBlock = bmiCalc.find('div.res'),
			bmiResult = $('#bmi'),
			bmiMessage = $('#res'),
			weight, 
			height1, 
			height2, 
			inches,
			bmi,
			message = '';
		$('#calculate').bind('click', function(){
			weight = parseInt($('#weight').val());
			height1 = parseInt($('#height1').val());
			height2 = parseInt($('#height2').val());
			
			// verification
			// weight
			if(isNaN(weight)){
				alert('Please enter a valid weight in pounds (must be a number).');
				return false;
			}
			if(weight <= 0){
				alert('Weight must be greater than 0.');
				return false;
			}
			// height1
			if(isNaN(height1)){
				alert('Please enter a valid height in feet (must be a number).');
				return false;
			}
			if(height1 <= 0){
				alert('Height in feet must be greater than 0.');
				return false;
			}
			// height2
			if(isNaN(height2)){
				height2 = 0;
			}
			if(height2 > 11){
				alert('Height in inches must not be greater than 11.');
				return false;
			}
			
			// calculation
			inches = (height1 * 12) + height2;
			bmi = (weight / (inches * inches) * 702).toFixed(1);
			if(bmi < 18.5) { message = 'Underweight'; }
			if(bmi >= 18.5 && bmi < 24.9) { message = 'Normal'; }
			if(bmi >= 24.9 && bmi <= 29.9) { message = 'Overweight'; }
			if(bmi > 30) { message = 'Obese'; }
			
			//
			s.linkTrackVars = 'events'; s.linkTrackEvents = 'event7'; s.events = 'event7'; (s.tl(this, 'o', 'BMI Calculator Completion'));
			calcBlock.hide();
			bmiResult.text(bmi);
			bmiMessage.text(message);
			resultBlock.show();
			
		});
	
	}
	
	// clickable call ouuts
	var quizLink = $('div.box-low-bottom'),
		doctorLink = $('div.box-talk');
	if(quizLink.length){
		quizLink.bind('click', function(){
			document.location = '../do-you-have-low-t/low-t-quiz-test.html';
		});
	}
	if(doctorLink.length){
		doctorLink.bind('click', function(){
			document.location = '../what-you-can-do/talk-to-your-doctor.html';
		});
	}
	
});
