// originally based on the Custom Check Box and Radio Buttons plug-in by Darren Mason
// takes container element and will customise all checkboxes and radio btns within
// can take an optional more specific selector for inputs to customise e.g.
// $("#somecontainer").customiseInputs();
// $("#somecontainer").customiseInputs("input.specificinputs");
$.fn.customiseInputs = function(inputsSelector){
	
	// selectors for elements inside the container
	var defInputsSelector = "input[type='checkbox'],input[type='radio']";
	var inputsSelector = inputsSelector || defInputsSelector;
	var spansSelector = "span.cust_checkbox,span.cust_radio";
	var labelsSelector = "label.cust_label";
	var offSpanClass = "cust_radio_off";
	var allowedActiveParent = "fieldset";
	var activeParentClass = "active";
	
	// internal function, takes custom input and modifies 
	// it's and relevant span's ID and class accordingly
	function toggleCustInput(input) {		
		
		var input = $(input);
		var isChecked = input.attr("checked");
		var isDisabled = input.attr("disabled");
		var inputType = input.attr("type");
		var span = input.prev('span');
		
		var parent = input.parent();
		var setParentClass = false;
		
		if(parent.size() > 0) {
			var node = parent.get(0);
			if(node && node.nodeName) {
				var nodename = node.nodeName.toLowerCase();
				if(nodename == allowedActiveParent) {
					setParentClass = true;	
				}
			}
		}
		

		// input will be checked
		if(!isChecked && !isDisabled) {
			
			// check the input
			input.attr("checked","checked");
			// swap the ID on the span
			var currentID = span.attr('id');
			
			var newID = currentID.replace('_off','');
			span.attr('id',newID);
			span.removeClass(offSpanClass);
			
			// if you check a radio btn, modify span IDs of other radios with the same name
			if(inputType == 'radio') {
				var name = input.attr("name");
				var containerToSearchIn = input.form; // for efficiency, restrict search to the form
				$("input[name='" + name + "']", containerToSearchIn).filter('input[type=radio]').each(function() {	
																				   
					if( $(input).get(0) != this ) { // except the one being checked
						var span = $(this).prev('span').get(0);
						if(span && span.id && span.id.indexOf('_off') == -1) {
							span.id += '_off';
						}
						$(span).addClass(offSpanClass);
						if(setParentClass) {
							$(span).parent().removeClass(activeParentClass);	
						}
					}
				});
			}
			
			if(setParentClass) {
				parent.addClass(activeParentClass);	
			}
			
			input.trigger("custominputcheck");
			
		}
		
		// input will be unchecked
		else if(!isDisabled) {
			
			// uncheck the input
			input.removeAttr("checked");
			// swap the ID on the span
			var currentID = span.attr('id');
			var newID = currentID + '_off';
			span.attr('id',newID);
			span.addClass(offSpanClass);
			
			if(setParentClass) {
				parent.removeClass(activeParentClass);	
			}
			
			input.trigger("custominputuncheck");
			
		}
			
	}
	
	// looping over all the container elements passed in
	return this.each(function() {
		
		// looping over inputs in each container
		$(this).find(inputsSelector).each(function() {
				
			// get data about the current input
			var currElem = $(this);
			var isChecked = currElem.attr("checked");
			var inputType = currElem.attr("type");
			var inputID =  currElem.attr("id");
			
			// only process supported input types
			if(!inputType || (inputType.toLowerCase() !== 'radio' && inputType.toLowerCase() !== 'checkbox') ) { return; }
			
			var label = currElem.next('label').addClass('cust_label');
			
			// set approapriate classes & IDs on the current span
			var spanClass = "cust_" + inputType;
			var spanID = inputID.replace('input','');
			if(!isChecked) {
				spanID += '_off';
				spanClass += ' ' + offSpanClass;
			}
	
			// hide input & insert span before it
			currElem.hide(); 
			var HTML2insert = '<span id="' + spanID  + '" class="' + spanClass + '">&nbsp;&nbsp;&nbsp;&nbsp;</span>';
			var span = $(HTML2insert).insertBefore(currElem); 
		
		});

		// event handler for spans
		$(this).find(spansSelector).click(function() {
			var input = $(this).next("input");
			toggleCustInput(input);		   
		});

		// event handler for labels
		$(this).find(labelsSelector).click(function() {
			var input = $(this).prev("input");
			toggleCustInput(input);		   
		});
		
	}); 
		
};



// Cookie plugin
// Copyright (c) 2006 Klaus Hartl (stilbuero.de) Dual licensed under the MIT and GPL licenses.
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        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(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        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 { // only name given, get cookie
        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]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



// TODO: refactor as a plug-in
td.healthtabs = {
	
	frequency: 10, // in seconds
	index: 1, // start animation from
	framesSelector: '#healtresults > div.healthcontainer',
	navSelector: '#healthresultsnav li:not(.navtitle)', // skip the nav title
	activeClass: 'active',
	
	total: 0,
	timer: null,
	nodes: [],
	nodesNav: [],

	init: function() {
		var nodeSet = $(td.healthtabs.framesSelector);
		var nodeSetNav = $(td.healthtabs.navSelector);
		td.healthtabs.total = nodeSet.size();
		if(td.healthtabs.total == 0) { return; }
		td.healthtabs.nodes = nodeSet.get(); // caching DOM node references
		td.healthtabs.nodesNav = nodeSetNav.get(); // caching DOM node references
		nodeSetNav.find('a').click(td.healthtabs.navclick);
		td.healthtabs.timer = setInterval(td.healthtabs.increment, td.healthtabs.frequency * 1000);
	},

	increment: function() {
		if (td.healthtabs.index == td.healthtabs.total) { 
			td.healthtabs.index = 0;
		}
		td.healthtabs.activate(td.healthtabs.index);	
		td.healthtabs.index++;
		
		// $('#healtresults').trigger('tabchange', [td.healthtabs.index]);
		
		// stop on the last frame
		if(td.healthtabs.index == 5) {
			clearInterval(td.healthtabs.timer);
			td.healthtabs.timer = null;
			// $('#animationcontrol').fadeOut();
		}
		
	},
	
	activate: function(index) {
		td.healthtabs.index = index;
		$(td.healthtabs.framesSelector).each(function(i) {
			if( $(this).is('.' + td.healthtabs.activeClass) ) {
				$(this).hide().removeClass(td.healthtabs.activeClass);
			}
		});		
		$(td.healthtabs.nodes[index]).stop().fadeIn();
		$(td.healthtabs.nodes[index]).addClass(td.healthtabs.activeClass);
		
		$(td.healthtabs.navSelector).each(function(i) {
			if( $(this).is('.' + td.healthtabs.activeClass) ) {
				$(this).removeClass(td.healthtabs.activeClass);
			}
		});			
		$(td.healthtabs.nodesNav[index]).addClass(td.healthtabs.activeClass);
	},

	navclick: function() {
		var index = this.hash.substr(2); // TODO: don't hardcode
		if(!isNaN(index)) { 
			index--;
			clearInterval(td.healthtabs.timer);
			td.healthtabs.timer = null;
			td.healthtabs.index = index;
			td.healthtabs.increment();
			// td.healthtabs.timer = setInterval(td.healthtabs.increment, td.healthtabs.frequency * 1000);
		}
		return false;
	}

};
$(document).ready(td.healthtabs.init);


$(document).ready(function() {
						   
	$('#maincontent .learnmore, #maincontent .terms').click(function() {
		
		var maincontent = $('#maincontent');
		var requiredOffsets = maincontent.offset();
		var activeLink = $(this);
		var fetchdietinfo = activeLink.is('.fetchdietinfo');
	
		// overlay
		if($('#overlayBackgroundWhite').size() == 0) { 
			var newDiv = $('<div/>');
			newDiv.attr('id', 'overlayBackgroundWhite');
			newDiv.css({
				width: 700,
				height: maincontent.outerHeight() + 30,
				position: 'absolute',
				top: requiredOffsets.top,
				left: requiredOffsets.left
			});
			$('body').append(newDiv);
		} else {
			var newDiv = $('#overlayBackgroundWhite');
			newDiv.css({
				// maincontent height can change due to jstoggle links
				height: maincontent.outerHeight() + 30
			});
			
		}
		$(newDiv).show();
		
		if(td.isIE6) {
			$('select').css('visibility', 'hidden');
		}
		
		// content
		/* try { location.hash = this.hash; } catch(e) {} */
		var content = $(this.hash);
		content.css({
			// display: 'block',			
			width: 700,
			height: maincontent.outerHeight(),
			position: 'absolute',
			top: requiredOffsets.top,
			left: requiredOffsets.left
		});
		
		if(fetchdietinfo) {
			
			var classes = activeLink.parent().attr('class');
			var dietchoice = classes.replace('dietchoices','');
			var url = "/dietPlans/dietintro.cfm?dietchoice=" + dietchoice;
			
			$('#fdpStepID_ChoosePlanContinue').val(dietchoice);
			
			function fetchInfo(url) {
				$('#planinfocontent').load(url, {}, function(responseText, textStatus, XMLHttpRequest) {
															 
					content.fadeIn();
					td.nma.dietplanspage.init();
					td.nma.dietplanspage.mealtypeselect();
					
					$('#mealtypes a').click(function() {
						fetchInfo(this.href);
						return false;
					});
				});
			}
			
			fetchInfo(url);
			
		} else {		
			content.fadeIn();
		}
		
		$('html,body').animate({scrollTop: 0}, 1500);
		
		return false;
	});
	
	$('#content .closeoverlay,#content .closeoverlay2').click(function() {
		$(this).parents('.overlay').fadeOut();	
		$('#overlayBackgroundWhite').hide();
		if(td.isIE6) {
			$('select').css('visibility', 'visible');
		}
		/* try { location.hash = ""; } catch(e) {} */
		return false;				
	});
	
});



// to be moved into base.js
$(document).ready(function() {
	// if(td && td.isIE6) {					   
		var fieldsets = $('#maincontent .healthactivity_ctr fieldset');
		fieldsets.mouseover(function() {
			$(this).addClass('ie6hover');								 
		});
		fieldsets.mouseout(function() {
			$(this).removeClass('ie6hover');								 
		});	
	// }
});



$(document).ready(function() {						   
	$('#genderinputs input').click(function() {
		if(this.value == '1' && this.checked) {
			$('#femalequestions').hide();	
		} else {
			$('#femalequestions').show();
		}
	});
});


$(document).ready(function() {
	$('#animationcontrol').click(function() {
		var currentLink = $(this);
		if(currentLink.is('.pause')) { // stop
			currentLink.removeClass('pause').addClass('play').text('Play Animation');
			clearInterval(td.healthtabs.timer);
			td.healthtabs.timer = null;
		} else { // play
			currentLink.addClass('pause').removeClass('play').text('Pause Animation');
			var newindex = td.healthtabs.index + 1;
			td.healthtabs.navclick.apply({hash: '#h' + newindex});
		}
		return false;
	});	
	
	// $('#healtresults').bind('tabchange', function(evt, tabindex) { });
	
});

$(document).ready(function() {
						   
	var medicalWarnings = $('#maincontent .medical_ctr diabetes_ctr');
	if(medicalWarnings.size() == 0) {
	
		// medical conditions page on FDP
		$('#medical_ctr_inputs input[type=checkbox]').bind('custominputcheck', function() {
			$('#specialMedicalNone').removeClass('active').		
			find('input').attr('checked', false).end().
			find('span').addClass('cust_radio_off');														
		});
		$('#specialMedicalNone input').bind('custominputcheck', function() {
			var activeInput = this;
			$('#medical_ctr_inputs input').each(function() {
				if(this != activeInput) {
					$(this).attr('checked', false).
					prev('span').addClass('cust_radio_off').
					parents('fieldset').removeClass('active');
				}
			});																	
		});	
	
	}

	// dietary requirements page on FDP
	$('#dietaryrequirements_ctr_inputs input[type=checkbox]').bind('custominputcheck', function() {
		$('#dietaryPreferenceNone').removeClass('active').		
		find('input').attr('checked', false).end().
		find('span').addClass('cust_radio_off');														
	});
	$('#dietaryPreferenceNone input').bind('custominputcheck', function() {
		var activeInput = this;
		$('#dietaryrequirements_ctr_inputs input').each(function() {
			if(this != activeInput) {
				$(this).attr('checked', false).
				prev('span').addClass('cust_radio_off').
				parents('fieldset').removeClass('active');
			}
		});																	
	});	
	
	// editable options sidebar
	$('#sidebar .edit_section').click(function() { 
		$(this).next().fadeToggle(); return false; 
	});
	
	// FDP options selects
	$('#sidebar .da_progress select').change(function() {
		var activeLabel = $(this).find('option:selected').text();
		$(this).parents('li:first').find('p em').text(activeLabel);
		$(this).parents('div.editcontainer').fadeOut();
	});

	// FDP options checkboxes
	$('#sidebar .da_progress input:checkbox').click(function() {
		var checkboxLabels = [];
		$(this).parents('div.editcontainer').find('input:checkbox').each(function() {
			if(this.checked) {
				checkboxLabels.push( $(this).next().text() );
			}
		});												 
		var text = checkboxLabels.join(', ');
		$(this).parents('li:first').find('p em').text(text);
	});
	
	$('#sidebar a.closeoptions').click(function() {
	    $(this).parents('div.editcontainer').fadeOut();
		return false;											
	});

});


$(document).ready(function() {
						   
	// captures all the data & redirects to a different gender's page if respective radio box selected
	function captureGender(gender){
		
		var hiddengenderInput = document.getElementById('hiddenSwitchGender');		
		if(!hiddengenderInput) { return; }

		// don't redirect on the 'welcome back' page
		var welcomebackform = document.getElementById('welcomebackform');		
		if(welcomebackform) { return; }

		var hiddengender = hiddengenderInput.value;
		if (hiddengender != gender)	{
			if(document.FormLanding && document.FormLanding.dietchoice && document.FormLanding.userChosenDiet)
			{
			var dietchoice = document.FormLanding.dietchoice.value;		
			}
			var fname = document.FormLanding.fname.value;
			var lname = document.FormLanding.lname.value;
			var email = document.FormLanding.email.value;
			var age = document.FormLanding.age.value;
			var code = document.getElementById('code').value;		
			
			if(gender == 1) {
				var genderstring = 'm';	
			} else {
				var genderstring = 'f';	
			}
			
			if(dietchoice)
			{
			window.location="/startfdp.cfm?ck_gender="+genderstring+"&dietchoice="+dietchoice+"&gender="+gender+"&age="+age+"&fname="+fname+"&lname="+lname+"&email="+email+"&code="+code; 
			}
			else
			{
			window.location="/startfdp.cfm?ck_gender="+genderstring+"&gender="+gender+"&age="+age+"&fname="+fname+"&lname="+lname+"&email="+email+"&code="+code; 
			}
		}
	
	}
	
	$('#genderinputs input').click(function() {
		captureGender(this.value);										
	});

}); 


function switchFields(which) {
	if (which == "metric") {
		var imp = document.getElementById("imperial");
		if(imp) { imp.style.visibility = "hidden"; }
		var met = document.getElementById("metric");
		if(met) { met.style.visibility = "visible";	}
		try { document.form1.bmtype.value = 1; } catch(e) {}
		if(td.isIE6) {
			$('#imperial select').css('visibility', 'hidden');
			$('#metric select').css('visibility', 'visible');
		}
	}
	else {	
		var imp = document.getElementById("imperial");
		if(imp) { imp.style.visibility = "visible"; }
		var met = document.getElementById("metric");
		if(met) { met.style.visibility = "hidden";	}
		try { document.form1.bmtype.value = 0; } catch(e) {}
		if(td.isIE6) {
			$('#imperial select').css('visibility', 'visible');
			$('#metric select').css('visibility', 'hidden');
		}	
	}
	return false;
}

$(document).ready(function() {
	$('a.slide-toggle').click(function(){		
		var cont = $('#showsamplemealplans');
		if(cont.is('.showcont')) {
			cont.hide().removeClass('showcont');
		} else {
		 cont.fadeIn().addClass('showcont');
		}	
		return false;
	})
}); 


$(document).ready(function() {
						   
	// captures all the data & redirects to a different gender's page if respective radio box selected 
	function captureGender(gender){

		if(gender == 1) {
			var genderstring = 'm';	
		} else {
			var genderstring = 'f';	
		}

		var healthBMI = document.getElementById('dietprofile_HealthBMI');
		if(healthBMI) {
			var currentGender = $.cookie('CK_GENDER') || '';
			currentGender = currentGender.toLowerCase();
			if( currentGender && (currentGender != genderstring) ) {
				var newURL = location.href.toLowerCase();
				if(newURL.indexOf('ck_gender=') != -1) {
					newURL = location.href.replace(/ck_gender=[fm]/,'ck_gender=' + genderstring);
				} else {
					newURL += '&ck_gender=' + genderstring;	
				}
				location.href = newURL;
				return;				
			}
		}
		
		var hiddengenderInput = document.getElementById('hiddenSwitchGenderBMI');
		
		if(!hiddengenderInput) { return; }
		
		var hiddengender = hiddengenderInput.value;
		if (hiddengender != gender)	{
			if(document.FormLanding && document.FormLanding.dietchoice && document.FormLanding.userChosenDiet)
			{
			var dietchoice = document.FormLanding.dietchoice.value;		
			}
			var fname = document.FormLanding.fname.value;
			var lname = document.FormLanding.lname.value;
			var email = document.FormLanding.email.value;
			var age = document.FormLanding.age.value;
			var code = document.getElementById('code').value;	
			
			if(dietchoice)
			{
			window.location="/startfdp.cfm?ck_gender="+genderstring+"&dietchoice="+dietchoice+"&gender="+gender+"&age="+age+"&fname="+fname+"&lname="+lname+"&email="+email+"&code="+code; 
			}
		}
	
	}
	
	$('#genderinputs input').click(function() {
		captureGender(this.value);										
	});

}); 

//CLose DNA page when opened from the FDP dietprofile_RecommendedPlan page.
$(document).ready(function() {
	
	$('#dnaBanner a').click(function() {
		 window.dnaWindow = window.open(this.href,"dna","resizable=yes,scrollbars=yes,status=yes");
		return false;
	});
						   
	$('#upsellsbtn a.closePage').click(function() {	
	    jQuery.cookie("fdpEntryPoint", "4", { expires: 100, path: '/' });
		if(window.opener) {
			window.opener.dnaWindow.close();
		}
		return false;
	});
});


// connected selects on FDP (BMI results)
td.selects = {

	selects:[],
	current:null,
	firstName:'userSetTargetWeight', // ID of original select
	secondName:'userSetTargetWeightSt', // name for new selects
	
	init:function(){
		
		var s = document.getElementById(td.selects.firstName);
		if(!s) { return; }
		var c = document.createElement('select');
		c.onchange = function(){
			td.selects.choose(this.selectedIndex);
		}
		s.parentNode.insertBefore(c, s);
		var g = s.getElementsByTagName('optgroup');
		for(var i = 0, j = g.length; i < j; i++){
			var o = g[i].getElementsByTagName('option');
			var newselect = document.createElement('select');
			s.parentNode.insertBefore(newselect, s);
			newselect.style.display='none';
			td.selects.selects.push(newselect);
			var k = 0;
			var menuooption = new Option(g[i].label, o[0].value, false, false);
			menuooption.innerText = g[i].label;
			// c.appendChild(o[0]);
			c.appendChild(menuooption);
			var selectedindex = 0,
				selectedindexfound = false;
			while(o[k]){
				if(o[k].getAttribute('selected')==='selected'){
					td.selects.current = i;
					newselect.style.display = 'inline';
					newselect.name = td.selects.secondName;
					selectedindexfound = true;
				} else {
					if(!selectedindexfound) {
						selectedindex++;
					}
				}
				newselect.appendChild(o[k]);
			}
			try {
			newselect.selectedIndex = selectedindex;
			} catch(e) {}
		}
		c.selectedIndex = td.selects.current;
		s.parentNode.removeChild(s);
		c.id = td.selects.firstName;
		// c.name = td.selects.firstName;
		
		if(td.selects.current === null) {
			td.selects.selects[0].name = td.selects.secondName;
			td.selects.selects[0].selectedIndex = 0;
			c.selectedIndex = 0;
			td.selects.current = 0;
			td.selects.selects[0].style.display = 'inline';
		}
	},
	
	choose:function(o){
		
		if(td.selects.current !== null){
			td.selects.selects[td.selects.current].style.display='none';
			td.selects.selects[td.selects.current].name='';
		}
		td.selects.selects[o].style.display='inline';			
		td.selects.selects[o].name = td.selects.secondName;
		td.selects.selects[o].selectedIndex = 0;
		td.selects.current = o;
	}
}

$(document).ready(td.selects.init);


// TODO: don't hardcode the container ID & merge this with $.fn.rotators
(function($) {
  
	// plugin definition
	$.fn.rotators2 = function(options) {
		
		// build main options before element iteration
		var opts = $.extend({}, $.fn.rotators2.defaults, options);
		var timer = null;
		var activeIndex = 0;
		var elements = [];

		if(this.size() != 0) {
			// init
			timer = setInterval(rotate, opts.delay);
		}

		// iterate over each matched element set
		return this.each(function(i) {
			elements[i] = this;
			if(i < opts.itemsdisplayed) {
				if(!opts.slideup) {
					$(this).fadeIn(opts.fadespeed);
				} else {
					$(this).css({ top: 150, display: 'block' }).animate({ opacity: 1, top: 0  }, 500);	
				}
			}
		});
		
		//Rotate the images
		function rotate() {	
		
			var fadeIndex = activeIndex + opts.itemsdisplayed;
			if(fadeIndex > elements.length - 1) {
				if(opts.itemsdisplayed != 1) {
					fadeIndex = activeIndex - opts.itemsdisplayed;
				} else {
					fadeIndex = 0;	
				}
			}
			
			if(!opts.slideup) {
				$(elements[fadeIndex]).appendTo(opts.containerselector);
				$(elements[activeIndex]).fadeOut(opts.fadespeed, function() {
					$(elements[fadeIndex]).fadeIn(opts.fadespeed);										  
				});	
			} else {
				$(elements[activeIndex]).animate({ 
					top: -30
				  }, 500, function() {
					$(elements[fadeIndex]).css({ 
						top: 30,
						display: 'block'
					}).animate({ 
						top: 0 }, 500);
				});				
			}
			activeIndex++;
			if(activeIndex > elements.length - 1) {
				activeIndex = 0;
			}
		};

	};
	
	// plugin defaults
	$.fn.rotators2.defaults = {
		delay: 1000,
		fadespeed: 500,
		itemsdisplayed: 1,
		containerselector: '',
		slideup: false
	};

})(jQuery);


$(document).ready(function() {
	$('#s2 p').rotators2({ delay: 6000, fadespeed: 400, itemsdisplayed: 1,  containerselector: '#s2', slideup: true });   
});
