td.nma = {} // non-members area
if(typeof console == 'undefined') { console = {}; console.log = function() {}; }
if(typeof td == "undefined") { td = {}; }
if(typeof td.pageinfo == 'undefined') { td.pageinfo = {}; }
if(typeof td.pageinfo.subsection == 'undefined') { td.pageinfo.subsection = 'null'; }
if(typeof td.pageinfo.currpage == 'undefined') { td.pageinfo.currpage = 'null'; }
if(typeof td.pageinfo.area == 'undefined') { td.pageinfo.area = 'null'; }
if(typeof td.pageinfo.environment == 'undefined') { td.pageinfo.environment = 0; }

td.htmlsetup = function() {
	if($('#m').length) {
		td.pageinfo.gender = 'm';
	}
	td.isIE6 = $.browser.msie && (parseInt(jQuery.browser.version) <= 6);
};
$(document).ready(td.htmlsetup);


jQuery.fn.fadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle'}, speed, easing, callback); 
};


// td.createElem({ id: 'someid', type: 'div', parent: jQuerySelector });
// div element type and body as parent are default
// returned element is hidden by default
td.createElem = function(options) {
	if(!options.id) { return; }
	var defaults = {
		type: 'div',
		parent: 'body'
	}
	var opts = $.extend({}, defaults, options);
	var lookup = $('#'+options.id);
	var elemExists = ( lookup.length != 0 );
	
	if(elemExists) {
		return lookup;
	} else {
		var newElem = $('<' + opts.type + '/>');
		newElem.attr('id', opts.id);
		newElemJqObj = newElem.appendTo(opts.parent);
		newElemJqObj.hide();
		return newElemJqObj;		
	}
}

// takes element ID and returns top and left offsets required to
// center element in viewport via aboslute positioning (useful for overlays)
td.getElemOffsets = function(id) {
	var container = $('#' + id);
	if(container.length == 0) { return {}; }
	var bodyWidth = $('body').width();
	var scrollTop = $(window).scrollTop() + 10;
	var containerWidth = container.width() || 780;
	var containerOffsetLeft = ((bodyWidth/2) - (containerWidth / 2));
	return { 
		'top' : scrollTop, 
		'left' : containerOffsetLeft,
		'z-index': 500,
	    'position': 'absolute'	
	};
}

td.togglediv = function(divID,cssPropsObject) {
	var id = '#' + divID;
	var o = $(id);
	if(o && o.size() > 0) { // already exists
		  $(id).fadeOut("slow", function () {
			$(id).remove();	
		  });
	} else { // doesn't exist yet
		var newDiv = $('<div/>');
		$(newDiv).attr('id', divID);
		if(typeof cssPropsObject != 'undefined') {
			$(newDiv).css(cssPropsObject);		 
		}
		$('body').append(newDiv);
		$(newDiv).fadeIn("slow"); 		
		return $(newDiv);
	}
}

// toggling overlay DIVs (they have to match page size)
td.overlay = function(overlayID) {
	var overlayID = overlayID || 'overlayBackground';	
	var cssPropsObject = {
		'width' : $('body').width(), 
		'height': $(document).height() 
	}
	if(td.isIE6) {
		var id = '#' + overlayID;
		var o = $(id);
		if(o && o.size() > 0) { // already exists, fade out
			$("select").css({'visibility': 'visible'});	
		} else { // fade in
			$("select").css({'visibility': 'hidden'});		
		}
	}
	return td.togglediv(overlayID,cssPropsObject);
}

// frontdoor background overlay
$(document).ready(function() {
	var fd = $('#frontdoor');			   
	if(fd.size() > 0) {
		td.overlay('overlayBackground');
		$('#fdher').click(function() {
			try {
				pageTracker._setVar('Female');
				pageTracker._trackEvent("Frontdoor overlay", "Female Click");
			} catch(e) { }
		});
		$('#fdhim').click(function() {
			try {					   
			pageTracker._setVar('Male');
			pageTracker._trackEvent("Frontdoor overlay", "Male Click");
			} catch(e) { }
		});		
	}
});

$(document).ready(function() {
	$(".wc-banner a").click(function() {
		try {
			pageTracker._trackEvent("World Cup PDF", "PDF Download");
		} catch(e) {}
	});
});
td.inputs = {
	
	init: function() {
		$('#acctid').click(td.inputs.clear);
		$('#password').click(td.inputs.clear);
		$('#email_newsletter').click(td.inputs.clear);		
	},
	
	clear: function() {
		if(this.value == this.defaultValue) { 
			this.value =''; 
		}
	}
	
};
$(document).ready(td.inputs.init);



// displaying dietplan info on FDP
td.nma.dietplans = {
	
	ID: 'dietchoice',
	current: 1,
	IDprefix: 'plan',
	IDsamplemeals: 'sampleMeals',
	firstRun: true,
	
	init: function(i) {
		$('#chooseDiet div.planInfo').hide();
		td.nma.dietplans.current = $('#'+td.nma.dietplans.ID).val();
		$('#'+td.nma.dietplans.ID).change(function() {
			td.nma.dietplans.display($(this).val());
		});
		td.nma.dietplans.display(td.nma.dietplans.current);
		
		
		$('#chooseDiet a.showsamplemealplan').click(function() {
			
			var id = $(this).attr('id').replace('showsm','');
			var sm = $('#sampleMeals'+id);
			
			if(sm.is(':visible')) {
				sm.hide();				
			} else {
				sm.show();				
			}
				
			return false;
															 
		});
		

	},
	
	display: function(i) {
		$('#chooseDiet div.planInfo').hide();
		
		if(!td.nma.dietplans.firstRun) {
			var selectorSampleMeals = '#' + td.nma.dietplans.IDsamplemeals + td.nma.dietplans.current;
			$(selectorSampleMeals).hide();
		}		
		
		var selectorOld = '#' + td.nma.dietplans.IDprefix + td.nma.dietplans.current;
		td.nma.dietplans.current = i;
		var selectorNew = '#' + td.nma.dietplans.IDprefix + i;

		$(selectorOld).hide();
		if(td.nma.dietplans.firstRun) {
			$(selectorNew).fadeIn('slow');
		} else {
			$(selectorNew).show();	
		}
		
		if (i == 12) {                    					
			$('#LowCarb').show();	
			$('#importantInfoBox100').show();								
		}
		else {
			$('#LowCarb').hide();                
			$('#importantInfoBox100').hide();
		}
		
		if (i == 21) {                    					
			$('#totalWellBeingPlan').show();	
			$('#totalWellMedNotice').show();										
		}
		else {
			$('#totalWellBeingPlan').hide();                
			$('#totalWellMedNotice').hide();
		}
	
		td.nma.dietplans.firstRun = false;
		return false;	
	}
	
}


// motivation select on FDP
td.nma.motivation = {
	
	ID: 'motivationSelect',
	current: 0,
	IDprefix: 'motivateInfo',
	
	init: function(i) {
		$('#content div.motivateInfo').hide();
		td.nma.motivation.current = $('#'+td.nma.motivation.ID).val();
		$('#'+td.nma.motivation.ID).change(function() {
			td.nma.motivation.display($(this).val());
		});
		$('#motivateInfo6 input').click(function() {
			td.nma.motivation.displayOccasion($(this).val());
		});
		td.nma.motivation.display(td.nma.motivation.current);
	},
	
	display: function(i) {		
		$('#content div.motivateInfo').hide();
		var selectorOld = '#' + td.nma.motivation.IDprefix + td.nma.motivation.current;
		td.nma.motivation.current = i;
		var selectorNew = '#' + td.nma.motivation.IDprefix + i;
		var oldSelection = $(selectorOld);
		if(oldSelection.size() > 0) {
			$(selectorOld).hide();
			$(selectorNew).show();		
		} else {
			$(selectorNew).show();
		}

	},
	
	displayOccasion: function(i) {
		$('#motivateInfo6 div.motivateInfo').hide();
		if(i == 4 || i == 5) {
			var selectorNew = '#' + td.nma.motivation.IDprefix + i;
			$(selectorNew).show();
		}
	}
	
}

// on FDP - if TWB plan selected with medical conditions, we display a more approapriate plan instead
td.nma.twbconditions = {	
	init: function() {
		$('#twbconditions input').click(td.nma.twbconditions.change);
	},
	change: function() {
		var id = this.id;
		var cleaned_id = id.replace('affected','');
		$("#dietchoice").val(cleaned_id);		
		$("#dietchoice").change();
		td.nma.dietplans.current = cleaned_id;
		$('html,body').animate({scrollTop: 720}, 500);
	}
}


// setting up event handlers for FDP
$(document).ready(td.nma.dietplans.init);
$(document).ready(td.nma.motivation.init);
$(document).ready(td.nma.twbconditions.init);


$(document).ready(function() {		
						   
	$('#whatdoyougetlink').click(scrollToLink);	
	
	function scrollToLink() {
		var t = $('#whatdoyouget').offset().top; 
		if(t) {
			$('html,body').animate({scrollTop: t}, 500);
		}
	}
	
});


// rotating banner
td.nma.rb = {
	
	frequency: 6, // in seconds
	index: 1, // start animation from the second frame, as first shown onload
	framesSelector: '#rotatingbanner > li',
	activeClass: 'active',
	
	total: 0,
	timer: null,
	nodes: [],

	init: function() {
		var nodeSet = $(td.nma.rb.framesSelector);
		td.nma.rb.total = nodeSet.size();
		if(td.nma.rb.total == 0) { return; }
		td.nma.rb.nodes = nodeSet.get(); // caching DOM node references	
		td.nma.rb.timer = setInterval(td.nma.rb.increment, td.nma.rb.frequency * 1000);
	},
	
	increment: function() {
		if (td.nma.rb.index == td.nma.rb.total) { 
			td.nma.rb.index = 0;
		}
		td.nma.rb.activate(td.nma.rb.index);	
		td.nma.rb.index++;
	},
	
	activate: function(index) {
		td.nma.rb.index = index;
		$(td.nma.rb.framesSelector).each(function(i) {
			if( $(this).is('.' + td.nma.rb.activeClass) ) {
				$(this).hide().removeClass(td.nma.rb.activeClass);
			}
		});		
		$(td.nma.rb.nodes[index]).fadeIn();
		$(td.nma.rb.nodes[index]).addClass(td.nma.rb.activeClass);
	}
	
};
$(document).ready(td.nma.rb.init);





td.nma.whyjoin = {
	
	frequency: 8, // in seconds
	index: 1, // start animation from the second frame, as first shown onload
	framesSelector: '#tabbedPromo > dl, #carousel2 > #rotator div',
	navSelector: '#tabbedPromo > ul:first > li, #carousel2 > ul:first > li',
	activeClass: 'active',
	
	total: 0,
	timer: null,
	nodes: [],
	nodesNav: [],

	init: function() {
		var nodeSet = $(td.nma.whyjoin.framesSelector);
		var nodeSetNav = $(td.nma.whyjoin.navSelector);
		td.nma.whyjoin.total = nodeSet.size();
		if(td.nma.whyjoin.total == 0) { return; }
		td.nma.whyjoin.nodes = nodeSet.get(); // caching DOM node references
		td.nma.whyjoin.nodesNav = nodeSetNav.get(); // caching DOM node references
		nodeSetNav.find('a').click(function() {
			var index = this.hash.substr(5);
			if(!isNaN(index)) { 
				index--;
				clearInterval(td.nma.whyjoin.timer);
				td.nma.whyjoin.timer = null;
				td.nma.whyjoin.index = index;
				td.nma.whyjoin.increment();
				td.nma.whyjoin.timer = setInterval(td.nma.whyjoin.increment, td.nma.whyjoin.frequency * 1000);
			}
			return false;
		});
		td.nma.whyjoin.timer = setInterval(td.nma.whyjoin.increment, td.nma.whyjoin.frequency * 1000);
	},
	
	increment: function() {
		if (td.nma.whyjoin.index == td.nma.whyjoin.total) { 
			td.nma.whyjoin.index = 0;
		}
		td.nma.whyjoin.activate(td.nma.whyjoin.index);	
		td.nma.whyjoin.index++;
	},
	
	activate: function(index) {
		td.nma.whyjoin.index = index;
		$(td.nma.whyjoin.framesSelector).each(function(i) {
			if( $(this).is('.' + td.nma.whyjoin.activeClass) ) {
				$(this).hide().removeClass(td.nma.whyjoin.activeClass);
			}
		});		
		$(td.nma.whyjoin.nodes[index]).fadeIn();
		$(td.nma.whyjoin.nodes[index]).addClass(td.nma.whyjoin.activeClass);
		
		$(td.nma.whyjoin.navSelector).each(function(i) {
			if( $(this).is('.' + td.nma.whyjoin.activeClass) ) {
				$(this).removeClass(td.nma.whyjoin.activeClass);
			}
		});			
		$(td.nma.whyjoin.nodesNav[index]).addClass(td.nma.whyjoin.activeClass);
	}
	
};
$(window).load(td.nma.whyjoin.init);




td.nma.promos = {
	
	frequency: 22, // in seconds
	index: 1, // start animation from the second frame, as first shown onload
	framesSelector: '#tabbedPromo2 > dl',
	navSelector: '#tabbedPromo2 > ul:first > li',
	activeClass: 'active',
	
	total: 0,
	timer: null,
	nodes: [],
	nodesNav: [],

	init: function() {
		var nodeSet = $(td.nma.promos.framesSelector);
		var nodeSetNav = $(td.nma.promos.navSelector);
		td.nma.promos.total = nodeSet.size();
		if(td.nma.promos.total == 0) { return; }
		td.nma.promos.nodes = nodeSet.get(); // caching DOM node references
		td.nma.promos.nodesNav = nodeSetNav.get(); // caching DOM node references
		nodeSetNav.find('a').click(function() {
			var index = this.hash.substr(5);
			if(!isNaN(index)) { 
				index--;
				clearInterval(td.nma.whyjoin.timer);
				td.nma.promos.timer = null;
				td.nma.promos.index = index;
				td.nma.promos.increment();
				td.nma.promos.timer = setInterval(td.nma.promos.increment, td.nma.promos.frequency * 1000);
			}
			return false;
		});
		td.nma.promos.timer = setInterval(td.nma.promos.increment, td.nma.promos.frequency * 1000);
	},
	
	increment: function() {
		if (td.nma.promos.index == td.nma.promos.total) { 
			td.nma.promos.index = 0;
		}
		td.nma.promos.activate(td.nma.promos.index);	
		td.nma.promos.index++;
	},
	
	activate: function(index) {
		td.nma.promos.index = index;
		$(td.nma.promos.framesSelector).each(function(i) {
			if( $(this).is('.' + td.nma.promos.activeClass) ) {
				$(this).hide().removeClass(td.nma.promos.activeClass);
			}
		});		
		$(td.nma.promos.nodes[index]).fadeIn();
		$(td.nma.promos.nodes[index]).addClass(td.nma.promos.activeClass);
		
		$(td.nma.promos.navSelector).each(function(i) {
			if( $(this).is('.' + td.nma.promos.activeClass) ) {
				$(this).removeClass(td.nma.promos.activeClass);
			}
		});			
		$(td.nma.promos.nodesNav[index]).addClass(td.nma.promos.activeClass);
	}
	
};
$(document).ready(td.nma.promos.init);




// homepage - promotions carousel
td.nma.hppromos = {
	
	rotate: true,
	frequency: 6, // in seconds

	index: 1,
	total: 0,
	timer: null,

	init: function() {
		td.nma.hppromos.total = $('#tabbed > ul li').size();
		if(td.nma.hppromos.total == 0) { return; }
		$('#tabbed > ul a').click(td.nma.hppromos.onclick);
		if(td.nma.hppromos.rotate) {
			td.nma.hppromos.timer = setInterval("td.nma.hppromos.increment()", td.nma.hppromos.frequency * 1000);
		}
	},
	
	increment: function() {
		if (td.nma.hppromos.index == td.nma.hppromos.total) { 
			td.nma.hppromos.index = 0;
		}
		td.nma.hppromos.index++;
		td.nma.hppromos.activate(td.nma.hppromos.index);	
	},
	
	activate: function(index) {
		td.nma.hppromos.index = index;
		// containers
		$('#tabbed div.active').hide().removeClass("active");
		$("#t" + index).fadeIn();
		$("#t" + index).addClass("active");
		// navigation
		$("#tabbed > ul li.active").removeClass("active");
		$("#tabbed > ul a[href='#t" + index  + "']").parent().addClass("active");
	},
	
	onclick: function() {
		var href = this.href;
		var lastHash = href.lastIndexOf('#');
		var index = href.substr(lastHash + 2); // stripping '#r'
		td.nma.hppromos.activate(index);
		if(td.nma.hppromos.rotate) {
			clearInterval(td.nma.hppromos.timer);
		 	td.nma.hppromos.timer = setInterval("td.nma.hppromos.increment()", td.nma.hppromos.frequency * 1000);
		}
		return false;
	}

}

$(document).ready(td.nma.hppromos.init);







function retrieveComputedStyle(element, styleProperty)
{
  var computedStyle = null;
  if (typeof element.currentStyle != "undefined")
  {
    computedStyle = element.currentStyle;
  }
  else
  {
    computedStyle = document.defaultView.getComputedStyle(element, null);
  }
  return computedStyle[styleProperty];
}



function initNewsTicker()
{
  var newsScroller = document.getElementById("newsScroller");
  if(!newsScroller) { return; }	
  newsScroller.style.left = 0;
  if (retrieveComputedStyle(newsScroller, "position") == "relative")
  {
    var relativeWidth = newsScroller.offsetWidth;
    newsScroller.style.position = "absolute";
    newsScroller.calculatedWidth = newsScroller.offsetWidth;
    if (relativeWidth > newsScroller.calculatedWidth)
    {
      newsScroller.calculatedWidth = relativeWidth;
    }
    newsScroller.style.position = "relative";
  }
  else
  {
    newsScroller.calculatedWidth = newsScroller.clientWidth;
  }
  moveNewsScroller();
  return true;
}



function moveNewsScroller()
{
  var increment = 5;
  var newsScroller = document.getElementById("newsScroller");
  var currLeft = parseInt(newsScroller.style.left);

  if (currLeft < newsScroller.calculatedWidth * -1)
  {
    newsScroller.style.left = newsScroller.parentNode.offsetWidth + "px";
  }
  else
  {
    newsScroller.style.left = (parseInt(newsScroller.style.left) - increment) + "px";
  }
  newsScroller.timeout = setTimeout("moveNewsScroller()", 85);
  return true;
}



//News scroller
$(document).ready(initNewsTicker);





function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}


// http://www.dustindiaz.com/getelementsbyclass/
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


function toggleObj(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}


function toggleEl(el) {	
	if(el) {
		if ( el.style.display != 'none' ) {
			el.style.display = 'none';
		}
		else {
			el.style.display = '';
		}
	}
}


function toggleVisibility() {	
	
	var CSSclass = 'jstoggle';
	var ts = getElementsByClass(CSSclass);	
	
	if(ts) {	
		for(var i = 0; i < ts.length; i++) {	
			
			var n = getNextDiv(ts[i]);
			if(n) {
				toggleEl(n);				
				ts[i].onclick = function() { toggleEl(getNextDiv(this)); return false; }
			}
		}
	}	
	
	function getNextDiv(elem) { 
		do {			
			// if element has siblings, check if they're divs
			if(elem.nextSibling) { 
				elem = elem.nextSibling;
			} else { // if not, go up the DOM
				// note: parent itself (even if it's a div) can't be used, we can only use subsequent siblings
				if(elem.parentNode.nextSibling) { // if parent has siblings, check them
					elem = elem.parentNode.nextSibling;
				} else { // otherwise, continue up going up the DOM until we find parent with siblings					
					do {
						elem = elem.parentNode;
					} while(elem.nextSibling == null)					
					elem = elem.nextSibling; // start checking the sibling(s)
				} 
			}
		} while (elem && elem.nodeName.toUpperCase() != 'DIV');
		
		return elem;
	}	
	
}

// window.addEvent('domready', toggleVisibility);
addLoadEvent(toggleVisibility);


// create closure
(function($) {
  
	// plugin definition
	$.fn.togglers = function(options) {
		
		// build main options before element iteration
		var opts = $.extend({}, $.fn.togglers.defaults, options);
		
		// iterate over each matched element
		return this.each(function(i) {
			$(this)[opts.eventType](handle);
			if(i == 0) {
				$(this)[opts.eventType]();	
			}
		});
			
		function handle() {
			var curID = this.id;
			var regex = "[0-9]+";
			var curNum = curID.match(regex);
			var selectorOld = opts.target + opts.current;
			opts.current = curNum;
			var selectorNew = opts.target + opts.current;
			if(opts.useDisplayInline) {
				$(selectorOld).removeClass('inline');
				$(selectorNew).addClass('inline');
			} else {
				$(selectorOld).hide();
				$(selectorNew).show();
			}
		};
		
	};
	
	// plugin defaults
	$.fn.togglers.defaults = {
		current: 0,
		target: '#cont', // containers to toggle
		eventType: 'mouseover', // e.g. mouseover, click
		useDisplayInline: false // by default show function used which sets display to block
	};

// end of closure
})(jQuery);




$(document).ready(function() {	
						  
	$('#specialistHealth li').togglers({
		target: '#plan',
		useDisplayInline: true
	}); 
	
	$('#weightloss li').togglers({
		target: '#plan',
		useDisplayInline:  true
	}); 
	
});



td.nma.dietplanspage = {
	
		current: 0,
	
		init: function() {		
		
		$('.mealtypes').click(td.nma.dietplanspage.mealtypes);
		
		$('.mealdetails').click(td.nma.dietplanspage.mealdetails);
		
		},
		
		mealdetails: function(){
		
		var parentid =  $(this).parent().attr('id');
		
		var selectorold = td.nma.dietplanspage.current;
		var selectormealold = td.nma.dietplanspage.current;
		selectormealold = '#'+selectormealold+'_details';	
		
		var selectormealnew = '#'+parentid+'_details';			
		
		$(selectormealold).hide();
		$(selectormealnew).show();
		
		var tabold = '#tab'+selectorold;		
		var tabnew = '#tab'+parentid;
		
		$(tabold).hide();
		// $(tabnew).show();
		$(tabnew).css({ display: 'block' });
		
		td.nma.dietplanspage.current = parentid;
		
		},
		
		mealtypes: function(){
		
		var mealtype =  $(this).attr('id');
		
		mealtype = mealtype.replace('mealtype',"");	
		
		},
		
		mealtypeselect: function(){
			
		var mealtypecount =  $( '#mealtypes .mealtypes' ).size();
			
			
			var amtmealtypes = $( '#mealtypes' );
				
			
			
			if (mealtypecount == 1){
				
				amtmealtypes = amtmealtypes.addClass('singlemealtype');
				
			}
			
			if (mealtypecount == 2){
				
				amtmealtypes = amtmealtypes.addClass('dualmealtype');
				
			}
			
			
		
		
			
		}
	
															   													   
}

$(document).ready(td.nma.dietplanspage.init);
$(document).ready(td.nma.dietplanspage.mealtypeselect);


// play video links
td.nma.successvideos = {
	
	selectorMain: '#successStoryHead p.play-video a', // main video
	selectorSidebar: '#success-videos p.play-video a', // sidebar videos
	selectorMid: '#success-videos-mid p.play-video a', // success page videos
	selectorCol: '#success-videos p.colVid a', // Colette's video on Angela and frieds

	
	init: function() {		
		$(td.nma.successvideos.selectorSidebar).addClass('sidebarvideo').click(td.nma.successvideos.handleclick);
		$(td.nma.successvideos.selectorMid).addClass('sidebarvideo').click(td.nma.successvideos.handleclick);
		$(td.nma.successvideos.selectorMain).click(td.nma.successvideos.handleclick);
		$(td.nma.successvideos.selectorMain).click(td.nma.successvideos.stopRotator);
		$(td.nma.successvideos.selectorCol).addClass('sidebarvideo').click(td.nma.successvideos.handleclick);// Colette's video on Angela and frieds
	},
	
	stopRotator: function(){
		clearInterval(td.nma.whyjoin.timer);
	},
	
	handleclick: function() {
		
		// gettting filename via container ID
		var container = $(this).parents('div:first');
		var videoID = container.attr('id');
		
		// obtaining siteid
		var containerClass = $('#success-videos').attr('class');
		if(containerClass) {
			containerClass = containerClass.replace('code','');	
		}
		var code = containerClass ? containerClass : 24030;
		
		// writing video player
		
		var videoWidth = 448;
		var videoHeight = 252;
		
		if( $(this).is('.sidebarvideo') ) {
			videoWidth = 300;
			videoHeight = 169;
		}
		
		var so = new SWFObject("/video-resources/player-newip_autoplay.swf", "tdPlayer", videoWidth, videoHeight, "9", "#ffffff");
		so.addParam("quality", "right");
		so.addParam("wmode", "transparent");
		so.addParam("auto", "true");
		so.addParam("allowScriptAccess", "always");
		so.addVariable("fileName", videoID);
		so.addVariable("promoCode", code);
		so.write(videoID);
		container.addClass('nobg');
		
		// track homepage video views
		if(td && td.pageinfo && td.pageinfo.subsection && td.pageinfo.subsection == "home") {
			try {
				pageTracker._trackEvent("Homepage videos", videoID);
			} catch(e) {}
		}		
		
		return false;		
	}	
	
}
$(document).ready(td.nma.successvideos.init);


$(document).ready(function() {

	$('#bookmarks').click(function() {
		$('#additionalTools').fadeToggle();
		return false;
	});

	$('#emaltofriend').click(function() {
		$('#friendForm').fadeToggle();
		return false;
	});
	
	if(typeof jQuery.fn.jFav != 'undefined') {
		$('#buttonOne').jFav();
	}
						   
});



$(document).ready(function() {
	
	$('#mealPlanTourLink').click(function() {
										  
		td.overlay('overlayBackground');

		var bodyWidth = $('body').width();
		var scrollTop = $(window).scrollTop() + 10;

		var container = $('div#mealPlanTour');
		var containerWidth = container.width() || 780;
		var containerOffsetLeft = ((bodyWidth/2) - (containerWidth / 2));

		container.css({
		   'top' : scrollTop,
		   'left' : containerOffsetLeft
		 });

		$('div#mealPlanTour').fadeIn();
		return false;									
	});
	
	
	$('#mealPlanTourClose').click(function() {

		td.overlay('overlayBackground');
		
		if(typeof td.isIE6 != 'undefined' && td.isIE6) {
			$('select').show();
		}

		$('div#mealPlanTour').fadeOut();

		return false;
		
	});
	
});




// oursupport page
$(document).ready(function() {
			
	// default
	var currentSelection = $('#teamdescriptions div:first').attr('id');
	var className = 'active';		
		
	$('#teamContainer a').click(function() {
										 
		var h = this.href;
		var lastHashPos = h.lastIndexOf('#');
		if(lastHashPos != -1) {			
			h = h.substr(lastHashPos);
			if(h != currentSelection) {
				$(this).parents('div:first').addClass(className);
				$('#teamContainer a[href^=' + currentSelection + ']:first').parents('div:first').removeClass(className);		
				currentSelection = h;
				var visibleDivs = $('#teamdescriptions div:visible');
				
				if(visibleDivs.size() > 0) {
					$('#teamdescriptions div:visible').fadeOut('slow', function() {				
						$(h).fadeIn('slow');				
					});
				} else {
					$(h).fadeIn('slow');					
				}
			}
		}
		return false;
	});
	
	$('#teamContainer a:first').click();

});

function hasclass(obj,cssc1ass) {
	var found = false;
	var temparray = obj.className.split(' ');
	for(var i=0; i<temparray.length; i++){
		if(temparray[i]==cssc1ass){found=true;}
	}
	return found; 
}



$(document).ready(function() {
						   
	$("#newsletterSignup").submit(function() {
			
			var signupCallback = function() {
				$('#newsletterSignup p').fadeOut(function() {
					$(this).remove();	}
				);
				$('#newsletterSignup fieldset').fadeOut(function() {
					$(this).remove();																 
				 	$('#newsletterSignup').append('<p>Thank you for registering.</p>'); }
				);
			};
			
			var url = location.href;
			var params = $(this).serializeArray();
			$.post(url, params, signupCallback);
			
			return false;
	});

});



td.rctour = {
	
	contID: 'recipetourcontent',

	init: function() {
		$('#recipetour').unbind().click(td.rctour.open);
		$('#recipetourclose').click(td.rctour.close);
	},

	open: function() {
		td.overlay('overlayBackground');
		var tourCont = td.createElem({ id: td.rctour.contID });
		var cssPos = td.getElemOffsets(td.rctour.contID);
		tourCont.css(cssPos).hide().fadeIn();
		return false;	
	},

	close: function() {
		td.overlay('overlayBackground');
		$('div#' + td.rctour.contID).fadeOut();
		return false;
	}
};
$(document).ready(td.rctour.init);


td.fitnesstour = {

	contID: 'fitnesstourcontent',

	init: function() {
		$('#fitnesstour').unbind().click(td.fitnesstour.open);
		$('#fitnesstourclose').click(td.fitnesstour.close);		
	},

	open: function() {
		td.overlay('overlayBackground');
		var tourCont = td.createElem({ id: td.fitnesstour.contID });
		var cssPos = td.getElemOffsets(td.fitnesstour.contID);
		tourCont.css(cssPos).hide().fadeIn();
		return false;		
	},

	close: function() {
		td.overlay('overlayBackground');
		$('div#' + td.fitnesstour.contID).fadeOut();
		return false;	
	}
	
};
$(document).ready(td.fitnesstour.init);




// opening windows based on rel attribute, this can be used to replace target="_blank"
// if width & height given, sizes the new window respectively
function popups() {                      
    if(!document.getElementsByTagName) { return; }		
	
	var relValuetoCheck = 'popup';
	var popupClassname = 'popup';
	
	var anchors = document.getElementsByTagName('a'); 
    for (var i = 0; i < anchors.length; i++) {        
         var anchor = anchors[i];   		 
		 
         var relIndex = anchor.rel;                  
		 if (relIndex) { 
		 var relSplit = relIndex.split('|');  	
		 
		 if (relSplit[0] == relValuetoCheck) { 		 	
			if(anchor.className) {  
				anchor.className += ' ' + popupClassname; 
			} else
			{
				anchor.className = popupClassname;
			}
			
			if(relSplit[1]) { anchor.popupHeight = relSplit[1]; }
			if(relSplit[2]) { anchor.popupWidth = relSplit[2]; } 
			if(relSplit[3]) { anchor.popupScroll = relSplit[3]; }  
			
			anchor.onclick = function() {
				if(this.popupHeight && this.popupWidth && this.popupScroll){
					
					var newWin = window.open(this.href, '_blank', "resizable,height="+this.popupHeight+",width="+this.popupWidth+",scrollbars=1"); 
				}
				else if(this.popupHeight && this.popupWidth) { // for links with rel values like rel="popup|471|534"
					
					var newWin = window.open(this.href, '_blank', "resizable,height="+this.popupHeight+",width="+this.popupWidth); 
				}
				else // for links with rel="popup"
				{
					
					var newWin = window.open(this.href, '_blank'); 	
				}
				newWin.focus();
				return false;
				};			
		 }
		 }				 
	} 	
	
}
$(document).ready(popups);


// payment option with weighing scales on FDP - togggling address capture
$(document).ready(function() {
	
	var addressbox = $('#weighinscalescapture');
	if(addressbox.size() > 0) {
		
		// onload handler
		if( $('#membership_options input:checked').val() == "387" ) {
			addressbox.fadeIn();	
		}		
		
		// event handler for membership option radio buttons
		$('#membership_options input').click(function() {
			// if scales option selected, show address capture, otherwise hide
			if(this.value == 387 && this.checked) { 
				addressbox.fadeIn();
			} else {
				addressbox.fadeOut();	
			}
		});
		
	}
						   
});




function invi(flag,divID) {
	if(typeof flag == "undefined" || typeof divID == "undefined") { return; }
	var x = document.getElementById(divID);
	if(x) { x.style.visibility = (flag) ? 'hidden' : 'visible' }
}


// FDP
$(document).ready(function() {
						   
	if(typeof jQuery.datepicker != 'undefined') {
		$('#calendardate').datepicker({ dateFormat: 'dd-M-yy', minDate: 0 });
		$('#weddingcalendardate').datepicker({ dateFormat: 'dd-M-yy', minDate: 0,
		showOn: 'both', buttonImageOnly: true, buttonImage: '/design/structure/img/freedietprofile/btn/transpbtn.gif', buttonText: 'Select date' });
		$('#dnapicker1,#dnapicker2,#dnapicker3').datepicker({ 
			dateFormat: 'dd-M-yy', 
			minDate: 0, 
			showOn: 'both', 
			buttonImageOnly: true, 
			buttonImage: '/design/structure/img/freedietprofile/btn/transpbtn.gif', 
			buttonText: 'Select date',			
			beforeShowDay: function(dateToShow){ 
				var datesToExclude = ['231209', '241209', '251209', '281209', '291209', '301209', '311209', 
									  '010110', '040110', '251210', 
									  '251211', 
									  '251212'];
				var dayOfWeek = dateToShow.getDay();
				var isWeekday = !(dayOfWeek == 0 || dayOfWeek == 6);
				var notExcluded = ($.inArray($.datepicker.formatDate('ddmmy', dateToShow),datesToExclude) == -1);
				var isValid = (isWeekday && notExcluded);
				return [isValid, ''];
			}
		});		
	}
	
	if(typeof $.fn.customiseInputs != 'undefined') { 
		$("#maincontent").customiseInputs("input.custominput");
	}
	
});


// Fitness and recipe Club Upsell check box replacement
$(document).ready(function() {
						   
	if(typeof $.fn.customiseInputs != 'undefined') { 
		$("#fdpUpsell").customiseInputs("input.custominput");		
		$("#removeCtr").customiseInputs("input.custominput").
		find("input.custominput").bind("custominputcheck", function() {
			var parent=$(this).parent();
				parent.find('label span').html("You are currently <strong>subscribed</strong> to");
				parent.find('label small').html("<strong>Click here to unsubscribe</strong>");
		}).bind("custominputuncheck", function() { 
			var parent=$(this).parent();
				parent.find('label span').html("You are currently <strong>unsubscribed</strong> to");
				parent.find('label small').html("<strong>Click here to subscribe</strong>");
		});
	}
	
	//fitness
	var fitInput = $("#fdpUpsellFitness #ftcbinput");
	if(!fitInput.attr("checked")){
		$('#fitWarning').hide();
	}
	
	var fitnessSelectBg;
	var recipeSelectBg;
	var dnaSelectBg;
	
	if (td.pageinfo.gender == 'f'){
		
		fitnessSelectBg = '-479px 0px';
		recipeSelectBg = '-477px -156px';
		dnaSelectBg = '-479px -312px';
	}
	else {		
		fitnessSelectBg = '-239px 0px';	
		recipeSelectBg = '-237px -156px';
		dnaSelectBg = '-238px -312px';
	}
	
	fitInput.bind("custominputcheck", function() {
		   $(this).parent().children('.cust_label').find("strong").html('Fitness added');	
		   $('#fdpUpsellFitness').css('background-position',fitnessSelectBg);
		   $('#fitWarning').show();
		   
	}).bind("custominputuncheck", function() {
		    $('#fitWarning').hide();
			 $('#fdpUpsellFitness').css('background-position','0px 0px');
		    $(this).parent().children('.cust_label').find("strong").html('Click to add Fitness');
	});  
	
	//recipe club
	var recInput = $("#fdpUpsellRecipe #rccbinput");
	if(!recInput.attr("checked")) {
			 $('#recWarning').hide();
	}
	recInput.bind("custominputcheck", function() {
		   $(this).parent().children('.cust_label').find("strong").html('Recipe Club added');
		   $('#fdpUpsellRecipe').css('background-position',recipeSelectBg);
		   $('#recWarning').show();
	}).bind("custominputuncheck", function() {		   
		    $('#recWarning').hide();
			$('#fdpUpsellRecipe').css('background-position','2px -156px');
			$(this).parent().children('.cust_label').find("strong").html('Click to add Recipe Club');
	});
	
	//dna
	var recInput = $("#fdpUpsellDNA #dnainput");
	if(!recInput.attr("checked")) {
			 $('#dnaWarning').hide();
	}
	recInput.bind("custominputcheck", function() {
		   $(this).parent().children('.cust_label').find("strong").html('DNA added');	
		   $('#fdpUpsellDNA').css('background-position',dnaSelectBg);
		   $('#dnaWarning').show();
	}).bind("custominputuncheck", function() {
		    $('#dnaWarning').hide();
			$('#fdpUpsellDNA').css('background-position','-0px -312px');
			$(this).parent().children('.cust_label').find("strong").html('Click to add DNA');
	});
	
	
	
});
////------------//////////////
   
   
   
$(document).ready(function(){
						  
		var flag = false;	
						   
		$('#qsb').submit(function(){
				
				if (flag){
					$("#bmiErrorMsg").remove();
				}
							
				var wtstVal = $('#wt_st').val();
				var wtlbVal = $('#wt_lb').val();
				var htftVal = $('#htft').val();
				var htinVal = $('#htin').val();					
				
				if (((wtstVal > 30) || (wtstVal < 7)) || (wtlbVal > 13)){	
					
					$("#tdBmiScale").append("<div id='bmiErrorMsg'><p>Weight entered must be between 7st and 30st 13lbs</p></div>");
					flag = true;
					return false;
				}
				
				if (((htftVal > 7) || (htftVal < 4)) || (htinVal > 11)) {
										
					$("#tdBmiScale").append("<div id='bmiErrorMsg'><p id='height'>Height entered must be between 4ft and 7ft 11in</p></div>");
					flag = true;
					return false;
				}				
				
				
  });	
		
				   
 });


$(document).ready(function(){   
	
	var browser;
	var browserImg;
	var browserVersion;
	var browserSteps;
		
		if($.browser.mozilla){
		  browser = 'Firefox';
		  browserImg = 'firefox';
		  }
		else if($.browser.msie){
		  browser = 'Internet Explorer';
		  browserImg = 'ie';
		  }	
		else if($.browser.safari){
		  browser = 'Safari/Chrome';
		  browserImg = 'safari';
		  browserSteps = '#safariSteps';
		  }
		else{
		  browser = 'Unknown';
		  browserImg = 'unknown';
		  }
	  
	 $('#browserName').append(browser); 
	  
		if($.browser.mozilla && $.browser.version.substr(0,5)=='1.9.1'){
			browserVersion = 3.5;
			browserSteps = '#firefox35Steps';
			}
		else if($.browser.mozilla && $.browser.version.substr(0,3)=='1.9'){
			browserVersion = 3;
			browserSteps = '#firefox3Steps';
			}
		else if($.browser.mozilla && $.browser.version.substr(0,5)=='1.8.1'){
			browserVersion = 2;
			browserSteps = '#firefoxSteps';
			}
		else if($.browser.mozilla && $.browser.version.substr(0,3)=='1.8'){
			browserVersion = 1.5;
			browserSteps = '#firefoxSteps';
			}
		else{
			browserVersion = $.browser.version;
			}
		
	$('#browserVersion').append(browserVersion);
		
			if($.browser.msie && $.browser.version.substr(0,2)=='6.'){
				$('#browserName').addClass('ie6');
				browserSteps = '#ie6Steps';
			}
			else if($.browser.msie && $.browser.version.substr(0,2)=='7.'){
				$('#browserName').addClass('ie7');
				browserSteps = '#ie7Steps';
			}
			else if($.browser.msie && $.browser.version.substr(0,2)=='8.'){
				$('#browserName').addClass('ie7');
				browserSteps = '#ie8Steps';
			}
			else{
			$('#browserName').addClass(browserImg);	
			}
	
		$(browserSteps).prependTo('#browserSteps');
		
	
	$('#cookieinstructions').click(function() {
		$link = $(this);
		$link.next('div').fadeToggle();
		if($link.is('.activated')) {
			$link.removeClass('activated').html('<span>View Instructions</span>');
		} else {
			$link.addClass('activated').html('<span>Hide Instructions</span>');	
		}
		return false;
	});
		
		
  });
				 
				 
$(document).ready(function() {
	$('#diabetesinputs input').click(function() {
		if(this.value == 'Yes' && this.checked) {
			$('#sufferdiabetes').show();	
		} else {
			$('#sufferdiabetes').hide();
		}											  
	});
	$('#sufferdiabetes input, #sufferdiabetes label').togglers({
		target: '#specialMedicalText',
		eventType: 'click'
	});
});
