// kill the console in ie
var Void = function() { }; if (!window.console) { window.console = { log: Void} };

var Site = {

    proxy: "/Themes/Custom/Proxy/RegularProxy.ashx?url=",
    recipeImagePath: "http://www.ragu.com/custom/GetImage.php?ImageId={id}",
    paths: {
        services: '/webservices/',
        mealPlanAssets: '/Themes/Custom/img/',
        productItemImages: '/Themes/Custom/images/products-dynamic/'
    },
    init: function() {
        sfNavigation.Init();
        $("#tabs").tabs();

        Site.addGradients();
        Site.createArrowLinks();

        Site.Tracking.Init();

        if ($(".questiontree").length > 0) {
            CommonQuestions.init();
        }

        if ($(".tipWidget").length > 0) {
            //ali's bio
            var $alisBio = $('#alisBio');
            $alisBio.dialog({
                autoOpen: false,
                modal: true,
                resizable: false,
                width: 734,
                position: ['center', 130],
                dialogClass: 'askAliOverlay',
                open: function(e, ui) {
                    //$(ui).find('.ui-dialog-titlebar-close').hide();
                }
            });


            $('.aliLinks a').click(function() {
                $alisBio.dialog('open');
            });

            TipWidget.init();
        }

        $("input[id$=_Status]").attr("maxlength", "90");

        if ($('.calculators').length > 0) {
            weightLossCalculator.init();
            bmiCalculator.init();
        }

        if ($('.customGroupsSmall').length > 0) {
            customGroupsSmall.init();
        }
        if ($('.invite-user').length > 0) {
            //invite user error messaging here
            $('span.field-item-validation').after(' Please enter a valid email address.')
            $('span.field-item-input textarea').empty();
        }
        if ($('.homePage').length > 0) {
			Site.HPlookfabTout();
			//var mainURL = "/Themes/Custom/swf/SF_Homepage.swf";
			var mainURL = "/Themes/Custom/swf/slimFastHero.swf";
            var param = { wmode: "transparent", allowScriptAccess: "sameDomain" };
            var att = {}
            swfobject.embedSWF(mainURL, "flashHolder", "956", "450", "9.0.0", null, null, param, att);
            //URL needs " &enablejsapi=1 " appended to it in order to access vid by script;
            var videoURL = "http://www.youtube.com/v/" + youtubeLocation + "&showinfo=0&hl=en_US&fs=1&&rel=0&enablejsapi=1"
            //var flashvars = {};
            var params = { allowScriptAccess: "always", allowFullScreen: "true", wmode: "transparent" };
            var atts = { id: "youPlayer" };
            swfobject.embedSWF(mainURL, "flashHolder", "956", "450", "9.0.0", null, null, param, att);
            //URL needs " &enablejsapi=1 " appended to it in order to access vid by script;
            var videoURL = "http://www.youtube.com/v/" + youtubeLocation + "&showinfo=0&hl=en_US&fs=1&&rel=0&enablejsapi=1"
            //var flashvars = {};
            var params = { allowScriptAccess: "always", allowFullScreen: "true", wmode: "transparent" };
            var atts = { id: "youPlayer" };
            swfobject.embedSWF(videoURL, "vidTout", "303", "156", "9.0.0", null, null, params, atts);

            window.onYouTubePlayerReady = function(playerId) {
                var player = $('#youPlayer')[0];
                var vidObj = document.getElementById("vidTout");
                player.addEventListener("onStateChange", "onYouTubePlayerStateChange");
            };
            Site.toutYouTubeTracked = 0;
            window.onYouTubePlayerStateChange = function(newState) {
                //unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
                if (newState == 1 && Site.toutYouTubeTracked != 1) { // this is the cue event which only happens once when the vid is ready to play
                    var trackurl = "http://fls.doubleclick.net/activityi;src=468024;type=slim-957;cat=video692;ord=' + Math.random().toString().split('.').join('') + '?"
                    $('body').append('<iframe id="spotlightEventTagPlay" src="http://fls.doubleclick.net/activityi;src=468024;type=slim-957;cat=video692;ord=' + Math.random().toString().split('.').join('') + '?" width="1" height="1" frameborder="0"></iframe>');
                    Site.toutYouTubeTracked = 1; // we only want this to happen once
                }

            }

        }
        if ($('.resourcesLanding').length > 0) {
            //URL needs " &enablejsapi=1 " appended to it in order to access vid by script;
            var videoURL = "http://www.youtube.com/v/" + youtubeLocation + "&showinfo=0&hl=en_US&fs=1&&rel=0&enablejsapi=1"
            //var flashvars = {};
            var params = { allowScriptAccess: "always", allowFullScreen: "true", wmode: "transparent" };
            var atts = { id: "youPlayer" };
            swfobject.embedSWF(videoURL, "youtubeHolder", "400", "300", "9.0.0", null, null, params, atts);
        }
        if ($('ul.articleList').length > 0) {
            $('.filter').hide();
            $('.post-summary').each(function(i) {
                var str = $(this).html();
                var strLength = str.length
                var rev = str.substring(11, strLength);
                $(this).html(rev);
            })

            $('ul.articleList li:eq(0) .icon .imgHolder').css('background-image', 'url("/Themes/Custom/images/icon-pepper.gif")');
            $('ul.articleList li:eq(1) .icon .imgHolder').css('background-image', 'url("/Themes/Custom/images/icon-yoga.gif")');
            $('ul.articleList li:eq(2) .icon .imgHolder').css('background-image', 'url("/Themes/Custom/images/icon-asparagus.gif")');
        }

        if ($(".friendship-list").length > 0) {
            Site.createConvoFriendsToggler();
            if (!$('ul#slimfastFriendsList').length > 0) {
                //no friends
                $('.friendsHead').append("<p class='nofriends'>You haven't added any friends yet. It's easy to invite people you know to sign up, simply follow the instructions on the right side of the page.<p>")
            }
            if ($('.friendsHead').length > 0) {
                $('.post-actions').hide()
            }
        }
        //remove blogs files wikis from my stuff
        if ($('.user-activity-message-list .filter .view-type').length > 0) {
            $('.user-activity-message-list .filter .view-type span.separator:eq(3)').hide();
            $('.user-activity-message-list .filter .view-type span.filter-option:eq(4)').hide();
        }

        // set up some default values for jquery ajax.
        // we never want to cache
        $.ajaxSetup({
            cache: false
        });
		
		

		//set up landing cookies
		if($('.weddingLanding').length > 0){
			createCookie('landingCookie','Wedding');
		}
		if($('.tvLanding').length > 0){
			createCookie('landingCookie','Big Event');
		}
		if($('.vacationLanding').length > 0){
			createCookie('landingCookie','Vacation');
		}
		//read cookie and populate in templates.js line 80ish;
    },
    addGradients: function() {
        var attr = $(".sfContent:visible").attr("gradients");
        if (attr) {
            var gradientsPositions = $(".sfContent:visible").attr("gradients").split(",");
            $.each(gradientsPositions, function(i, item) {
                $("<img src='/Themes/Custom/images/bg-gradient.gif' class='bgGradient' />")
                        .prependTo(".sfContentInnerWrap")
                        .css({ "top": parseInt(item) });
            }); // end each
        }

    },
    createArrowLinks: function() {
        $("a.arrowLink").each(function() {
            if ($(this).hasClass("before")) {
                $(this).prepend("<img src='/Themes/Custom/images/icon-arrow.gif' class='imgArrow' />");
            } else {
                $(this).append("<img src='/Themes/Custom/images/icon-arrow.gif' class='imgArrow' />");
            }
        });
    },
    // this runs on the my connection page (community) to allow toggling of the conversation and my friends
    // panes
    createConvoFriendsToggler: function() {

        $profilePage = $(".user-userprofile");
        if ($profilePage.length > 0) {
            return;
        }

        $convWrap = $(".conversation-list");
        $convHeader = $convWrap.find(".content-fragment-header div");
        $friendWrap = $(".friendship-list");
        $friendHeader = $friendWrap.find(".content-fragment-header div");

        //console.log("cinveader:",$convHeader);    

        $("<a href='javascript:void(0);'>FRIENDSHIP LIST</a> <span> | </span>").prependTo($convHeader)
                    .click(function() {
                        $convWrap.hide();
                        $friendWrap.show();
                    });

        $("<span> | </span> <a href='javascript:void(0);'>MY CONVERSATIONS</a>").appendTo($friendHeader)
                    .click(function() {
                        $convWrap.show();
                        $friendWrap.hide();
                    });

    },
    Tracking: {
        DebugMode: function() {
            $.extend(window.tracker.settings, {
                TestMode: true,
                ShowMissingHolderWarnings: true,
                ShowDebugInfo: true,
                SanityCheckEnabled: true,
                SanityCheckMissingOnly: true,
                SanityCheckFromFlash: true
            });

            console.info("Debug Mode Enabled");
        },
        Init: function() {
            window.tracker = $.initTrackIt('ga', {
                XmlUrl: '/Themes/custom/xml/trackData.xml',
                GlobalHolders: {
                    handleGobalAnchor: function() {
                        return "";
                    },
                    getLocation: function() {
                        return (window.location.pathname == "/") ? "/default.aspx" : window.location.pathname;
                    },
                    getClass: function() {
                        return $(this).attr("className");
                    },
                    getContext: function() {
                        // determine where the link occured based on parent
                        var pars = $(this).parents(".sfLowerContent");
                        var mainNav = $(this).parents(".mainNavItem");
                        var subNav = $(this).parents(".sfSubNav");
                        var dropDown = $(this).parents(".dropDown");
                        var head = $(this).parents(".sfHead");
                        var content = $(this).parents(".sfContent");
                        var right = $(this).parents("right-sidebar");
                        var footer = $(this).parents(".sfFooter");
                        var dailyPlan = $(this).parents(".dailyPlan");

                        // return values if length of these arrays is great than 1
                        if (footer.length > 0) { return "footer" }
                        if (pars.length > 0) { return "bottom wells" }
                        if (right.length > 0) { return "right bar" }
                        if (dropDown.length > 0) { return "drop down" }
                        if (mainNav.length > 0) { return "main nav" }
                        if (subNav.length > 0) { return "sub nav" }
                        if (head.length > 0) { return "head" }
                        if (content.length > 0) { return "content area" }
                        return "content";
                    },
                    getClickDetail: function() {
                        if (($(this).text().length == 0) && $(this).find("img").length > 0) {
                            var alt = $(this).find("img").attr("alt");
                            alt = (alt) ? ":" + alt : "";
                            return "image" + alt;
                        } else {
                            return $(this).text();
                        }
                    }
                },
                Plugins: [
				    TrackItPlugins.DataSanityCheck,
				    TrackItPlugins.RecordLastTrack,
				    Site.Tracking.CustomVar35,
				    TrackItPlugins.CheckUrlMapping
				]
            });

            //Site.Tracking.DebugMode();

            $("a:not([trackkey])").live("click", function() {
                if (typeof $(this).attr("trackkey") == 'undefined') {
                    tracker.track("globalAnchor", { ele: this });
                }
            });

        }
    },
    calculateBMI: function(weight, height) {
        return Math.round((weight / (height * height)) * 703);
    }
};
$(Site.init);
var sfNavigation = {
	Init: function(){
		var path = document.location.pathname.toLowerCase();
		// normalize the path with "default.aspx" if it's not there
		if (path.indexOf('default.aspx') == -1) { path += "default.aspx"; }
        var self = this;
        // iterate through each main nav item
        $(".mainNavItem > a").each( function(i, item) {
            var href = $(item).attr("href"); // grab href
            href = (href.indexOf('?') == -1 ) ? href : href.substr(0,href.indexOf('?')); //get rid of querystring
            href = href.split('/').slice(3); // get rid of the domain name, which will end at third instance of slash            
            var firstTwo = href.slice(0,1); // just get the localization (e.g. 'us') and the first section name                      
            var firstThree = href.slice(0,2); // get the first and second section name            
            firstTwo = firstTwo.join('/');
            firstTwo = "/" + firstTwo; // prepend a leading slash to match against the path
            firstThree = firstThree.join('/');        
            // if the buttons cleaned href is a substring of the window location
            // then we are in that section, so prepare subnavs
            if ( path.indexOf( firstTwo ) != -1) {
                var $subCont = $("div.sfSubNav");
                var $sec = $(item);
                $sec.addClass("active");
                $subnav = $sec.parent().find("ul.dropDown");      
                $subnav
                    .removeClass("dropDown planDropDown")                         
                    .addClass("planSubNav")
                    .appendTo($subCont)
                    .show();
                $subCont.show();    
                // center the subnav by measuring it's width in relation to width of parent;
                var offset = ($subnav.parent().width()-$subnav.width())/2;
                $subnav.css("left",offset)   
                       .show();
                                
                $subnav.find("a[href*=" + path + "]")
                       .addClass("active");        
                var p = self.processPath(path); 
                                   
            }             
        });
         
		//events
		var $navLinks = $('.sfMainNav ul.main > li').not('.current');
		 
		//mouseover function
		$navLinks.mouseover(function(){
			$(this).find('.dropDown').show();
			$('.sfHead').css('z-index',2000);
		});
		//mouseout function
		$navLinks.mouseout(function(){
			$(this).find('.dropDown').hide();
			$('.sfHead').css('z-index',2);
		});
	},
	processPath: function(p) {
	        p = (p.indexOf('?') == -1 ) ? p : p.substr(0,p.indexOf('?')); //get rid of querystring
            p = p.split('/').slice(3); // get rid of the domain name, which will end at third instance of slash            
            var firstTwo = p.slice(0,2); // just get the localization (e.g. 'us') and the first section name                      
            var firstThree = p.slice(0,3); // get the first and second section name            
            firstTwo = firstTwo.join('/');
            firstTwo = "/" + firstTwo; // prepend a leading slash to match against the path
            firstThree = firstThree.join('/'); 
            return { firstTwo:firstTwo,firstThree:firstThree  }  
	}
};




var Helpers = {
    isNumeric: function(sText) {
        var ValidChars = "0123456789.";
        var IsNumber=true;
        var Char;
        for (i = 0; i < sText.length && IsNumber == true; i++) 
        { 
        Char = sText.charAt(i); 
          if (ValidChars.indexOf(Char) == -1) 
             {
             IsNumber = false;
             }
        }
        return IsNumber;
    }

};

var CommonQuestions = {
    init: function() {
        $("#example > li > span").addClass("category");
        $("#example").treeview()
            .find("li.answer")
            .prepend("<div class='answerTitle'>Answer</div>")
            .end()
            .children("li").addClass("dottedLine");
    }
};

var TipWidget = {
    position: 0,
    $tips: [],
    $btnBack: null,
    $btnNext: null,
    init: function() {
        var self = this;
        this.$tips = $(".tipWidget .tip");
        $(this.$tips[this.$tips.length - 1]).show();
        this.position = this.$tips.length-1;
        this.$btnBack = $(".btnBack");
        this.$btnNext = $(".btnNext");
        this.$btnBack.click(function() { self.back() });
        this.$btnNext.click(function() { self.next() });
        this.setButtons();

    },
    next: function() {
        if (this.position < this.$tips.length - 1) {
            this.position++;
            this.$tips.hide();
            $(this.$tips[this.position]).show("slide", null, 1000);
            this.setButtons();
        }else{
			this.position = this.$tips.length - 1;//0;
			//this.$tips.hide(); 
	    	//$(this.$tips[this.position]).show("slide", null, 1000);  
		}
    },
    back: function() {
        if (this.position > 0) {
            this.position--;
            this.$tips.hide();
            $(this.$tips[this.position]).show("slide", null, 1000);
            this.setButtons();
        }else{
	        this.position = 0;//this.$tips.length - 1;
			//this.$tips.hide();
			//$(this.$tips[this.position]).show("slide", null, 1000); 
		}
        this.setButtons();    
    },
    setButtons: function() {
        if (this.position == this.$tips.length - 1) {
            this.$btnNext.css("opacity", 0.3);
        } else {
            this.$btnNext.css("opacity", 1);
        }
        if (this.position == 0) {
            this.$btnBack.css("opacity", 0.3);
        } else {
            this.$btnBack.css("opacity", 1);
        }
    }
};

var WeightLossCalc = {
    Init: function() {
        var tab = $('.weightLossCalc');
        var inputs = $('.weightLossCalc input');
        $("#datepicker").datepicker();
        var oldVal;
        var newVal;
        $(inputs).focus(function() {
            oldVal = this.value;
            this.value = '';
        });
        $(inputs).blur(function() {
            newVal = this.value;
            if (newVal == '') {
                this.value = oldVal;
            }
        });


    }
};

var weightLossCalculator = {
	init: function(){
	$("#datepicker").datepicker({ dateFormat: 'mm/dd/yy' });

		$('.submitBtn a.btn').click(function(){
			weightLossCalculator.validate()
		});
		$('.howMuchCanILose .resetBtnHolder a.btn').click(function(){
			$('.howMuchCanILose input').each(function(){
				$(this).val('')
			});
		});
	},
	validate: function(){
		var isNumWeight = /^\d+$/.test($('#yourCurrentWeight').val());
		if(isNumWeight == false){
			$('#yourCurrentWeight').parent().children('p.error').show();
			return;
		}else{
			if($('#yourCurrentWeight').val() < 88 ||$('#yourCurrentWeight').val() > 550){
				$('#yourCurrentWeight').parent().children('p.error').html('We process numbers between 88 and 550.').show();
				return;
			}else {
				$('#yourCurrentWeight').parent().children('p.error').hide();
			}
			
		}
		var isNumHeightFt = /^\d+$/.test($('#yourHeight').val());
		if(isNumHeightFt == false){
			$('#yourHeight').parent().children('p.error').show();
			return;
		}else{
			$('#yourHeight').parent().children('p.error').hide();
		}
		if(Number($('#yourHeight').val()) >= 8 || Number($('#yourHeight').val()) < 4){
			$('#yourHeight').parent().children('p.error').html('Please enter a height greater than 4 feet.').show();
			return;
		}
		var isNumHeightIn = /^\d+$/.test($('#heightIn').val());
		if(isNumHeightIn == false){
			$('#heightIn').parent().children('p.error').show();
			return;
		}else{
			$('#heightIn').parent().children('p.error').hide();
		}
		if(Number($('#heightIn').val()) >= 12){
			$('#heightIn').parent().children('p.error').show();
			return;
		}
		if($('#datepicker').val() == ''){
			$('#datepicker').parent().children('p.error').show();
			return;
		}
		weightLossCalculator.preformFunction();
	},
	preformFunction: function(){
		$('.howMuchCanILose .stepOne').slideUp();
		$('.howMuchCanILose .stepTwo').slideDown();
		
		if($('.visitorPlanSubNav').length > 0){
			$('.startMyPlanLoggedIn').hide();
			$('.startMyPlanVis').show();
		}else{
			$('.startMyPlanLoggedIn').show();
			$('.startMyPlanVis').hide();
		}
		
		
		var heightInFt = $('#yourHeight').val();
		var heightInIn =  $('#heightIn').val() ;
		
		var weight = $('#yourCurrentWeight').val();
		var height = (Number(heightInFt) * 12) + Number(heightInIn);
		var BMI = (weight/(height*height))*703;
		
		var d = new Date();
		var todaysMonth = d.getMonth() + 1;
		var todaysDate = d.getDate();
		var todaysYear = d.getFullYear();
		
		var selectedMonth = $('input.date').val().toString().substring(0,2);
		var selectedDate  = $('input.date').val().toString().substring(3,5);
		var selectedYear  = $('input.date').val().toString().substring(6,10);
		
		var date1 = todaysMonth+'/'+todaysDate+'/'+todaysYear;
		var date2 = selectedMonth+'/'+selectedDate+'/'+selectedYear;
		var numOfweeks = totalWeeks(date1,date2);
		var pounds = Math.round(numOfweeks * 2);
		
		var newBMI = ((weight - pounds)/(height*height))*703;
		//alert('bmi: '+BMI+'/  pounds: '+pounds+'/  numweeks: '+numOfweeks +'/   newBMI: '+newBMI)

		if(BMI <= 18){
			$('p.couldLose').html("You do not need to lose weight. In fact, it may be recommended that you gain weight. Please consult your physician.")
			return;
		}
		if(BMI <= 20){
			$('p.couldLose').html("Congratulations! You are already at a healthy weight. There is no need to lose more weight prior to <span class='date'>" + date2 + '</span>.')
			return;
		}
		if(BMI <= 22){
			$('p.couldLose').html("Congratulations! You are already at a healthy weight. There is no need to lose more weight prior to <span class='date'>" + date2 + '</span>.')
			return;
		}
		if(newBMI <= 21){
			var lowestWeight = Math.round((21 * (height*height)) / 703);
			pounds = (weight - lowestWeight);
		}
		$('.couldLose span.lbs').html(pounds  + ' pounds');
		$('.couldLose span.date').html(date2)
	}
};
var bmiCalculator = {
	init: function(){

		$('.calculateBmi a.btn').click(function(){
			bmiCalculator.validate();
		});
		
		$('.bmi .resetBtnHolder a.btn').click(function(){
			$('.bmi input').each(function(){
				$(this).val('')
			});
		});
		

	},
	validate: function(){
		var isNumWeight = /^\d+$/.test($('#bmiyourCurrentWeight').val());
		if(isNumWeight == false){
			$('#bmiyourCurrentWeight').parent().children('p.error').show();
			return;
		}else{
			$('#bmiyourCurrentWeight').parent().children('p.error').hide();
		}
		var isNumHeightFt = /^\d+$/.test($('#bmiyourHeightFt').val());
		if(isNumHeightFt == false){
			$('#bmiyourHeightFt').parent().children('p.error').show();
			return;
		}else{
			$('#bmiyourHeightFt').parent().children('p.error').hide();
		}
		if(Number($('#bmiyourHeightFt').val()) >= 8|| Number($('#bmiyourHeightFt').val()) < 4){
			$('#bmiyourHeightFt').parent().children('p.error').html('Please enter a height greater than 4 feet.').show();
			return;
		}

		var isNumHeightIn = /^\d+$/.test($('#bmiInches').val());
		if(isNumHeightIn == false){
			$('#bmiInches').parent().children('p.error').show();
			return;
		}else{
			$('#bmiInches').parent().children('p.error').hide();
		}
		
		if(Number($('#bmiInches').val()) >= 12){
			$('#bmiInches').parent().children('p.error').show();
			return;
		}
		bmiCalculator.preformFunction();
	},
	preformFunction:function(){
		$('.bmi .stepOne').slideUp();
		$('.bmi .stepTwo').slideDown();
		
		var yourW = '<strong>'+ $('#bmiyourCurrentWeight').val() + '</strong> lbs';
		var yourH = '<strong>'+ $('#bmiyourHeightFt').val() + '</strong> ft '+  '<strong>'+ $('#bmiInches').val() + '</strong> in';
		$('.yourStats .yourW span').html(yourW);
		$('.yourStats .yourH span').html(yourH);
		
		var heightInFt = $('#bmiyourHeightFt').val();
		var heightInIn =  $('#bmiInches').val() ;
		
		var weight = $('#bmiyourCurrentWeight').val();
		var height = (Number(heightInFt) * 12) + Number(heightInIn);
		var BMI = Site.calculateBMI(weight,height);
		
		$('.yourBmiIs span.bmiIs').html(Math.round(BMI));
		$('.bmiOverlayInner .actualBmi').html(Math.round(BMI));
		if(BMI <= 18){
			$('.yourBmiIs span.considered').html('UNDERWEIGHT');
			$('.messaging').html('<p>Your BMI is <strong>'+ Math.round(BMI) +'</strong>, indicating that you are in the underweight category for adults of your height. Based on your height, a healthy weight range would be from <strong>'+Math.round((18 * (height*height)) / 703)+'</strong> to <strong>'+Math.round((25 * (height*height)) / 703)+'</strong> pounds.</p><p>We recommend that you talk to your healthcare provider to determine possible causes of being underweight, as well as to determine if you need to gain weight.</p>')
		}
		if(BMI > 18){
			$('.yourBmiIs span.considered').html('APPROPRIATE');
			$('.messaging').html('<p>Your BMI is <strong>'+ Math.round(BMI) +'</strong>, indicating that you are in the normal category for adults of your height. Based on your height, a healthy weight range would be from <strong>'+Math.round((18 * (height*height)) / 703)+'</strong> to <strong>'+Math.round((25 * (height*height)) / 703)+'</strong> pounds. </p><p>It is important to maintain a healthy body weight, as it can decrease the risk of developing certain chronic conditions that are associated with overweight and obesity. Keep up the great work!</p>')
		}
		if(BMI > 25){
			$('.yourBmiIs span.considered').html('OVERWEIGHT');
			$('.messaging').html('<p>Your BMI is <strong>'+ Math.round(BMI) +'</strong>, indicating that you are in the overweight category for adults of your height. Based on your height, a healthy weight range would be from <strong>'+Math.round((18 * (height*height)) / 703)+'</strong> to <strong>'+Math.round((25 * (height*height)) / 703)+'</strong> pounds.</p><p>People who are overweight or obese are at a higher risk for developing chronic conditions such as high blood pressure, diabetes, and heart disease. For information on getting started on the Slim&middot;Fast Plan, go to: <a href="/plan/default.aspx">About the Plan</a></p>')
		}
		if(BMI > 29){
			$('.yourBmiIs span.considered').html('Obese');
		}
		
		$('td.assessmentRow p').each(function(i){
			$(this).children('span.avgWeightBot').html(Math.round((Number($(this).children('span.avgBmiBot').html()) * (height*height)) / 703));
			$(this).children('span.avgWeightTop').html(Math.round((Number($(this).children('span.avgBmiTop').html()) * (height*height)) / 703));
		});

		var bmis;
		var posLesser;
		var posGreater;
		var greatBmis = [];
		var numberOneLess;
		var numberOneMore;
		
		var pos;
		
		$('table.bmiChart td.bmiRow ol li').each(function(i){
			bmis = Number($(this).html());
			$('table.bmiChart td.weightRow ol li').eq(i).html(Math.round((bmis * (height*height)) / 703));
			
			if(bmis < Math.round(BMI)){
				posLesser = $(this).position();
				numberOneLess = $(this).html();
			}
			if(bmis > Math.round(BMI)){
				greatBmis.push($(this));
			}
		});
		
		if(BMI < 17){
			$('.bmiOverlayInner').animate({
				top: -262
			});
			return;
		}
		if(BMI > 107){
			$('.bmiOverlayInner').animate({
				top: 275
			});
			return;
		}
		numberOneMore = greatBmis[0].html();
		posGreater = greatBmis[0].position();
		
		var posX = (posGreater.top - posLesser.top);
		var numX = (numberOneMore - numberOneLess);
		var newBmi =(BMI - numberOneLess);
		
		var x = (newBmi * posX) / numX;
		if(BMI <= 18){
			var aniTo = -245;
			$('.bmiOverlayInner').animate({
				top: aniTo
			});
			return;
		}
		if(BMI < 25){
			var aniTo = -205;
			$('.bmiOverlayInner').animate({
				top: aniTo
			});
			return;
		}
		if(BMI < 29){ 
			var aniTo = -140;
			$('.bmiOverlayInner').animate({
				top: aniTo
			});
			return;
		}
		var aniTo = (-272 + (posLesser.top + Math.round(x))) +'px';
		$('.bmiOverlayInner').animate({
			top: aniTo
		});
	}
};

var customGroupsSmall = {
	init: function(){
		var CONSTANT = 0;
		var ulLength = $('.customGroupsSmall ul.customGroupsList').length -1;
		$('.customGroupsSmall ul.customGroupsList').hide();
		$('.customGroupsSmall ul.customGroupsList').eq(0).show();
		
		$('.customGroupsSmallArrows a.prev').click(function(){
			if(CONSTANT == 0){
				CONSTANT = ulLength;
			}else{
				CONSTANT -= 1;
			}
			$('.customGroupsSmall ul.customGroupsList').hide();
			$('.customGroupsSmall ul.customGroupsList').eq(CONSTANT).show();
		});
		$('.customGroupsSmallArrows a.next').click(function(){
			if(CONSTANT >= ulLength){
				CONSTANT = 0;
			}else{
				CONSTANT += 1;
			}
			$('.customGroupsSmall ul.customGroupsList').hide();
			$('.customGroupsSmall ul.customGroupsList').eq(CONSTANT).show();
		});
	}
};

var printWindow = null; //global variable used for print popup




// remedial javascript methods
String.prototype.supplant = function(o) {
    return this.replace(/{([^{}]*)}/g, function(a, b) {
		var r = o[b];
		return typeof r === 'string' || typeof r === 'number' ? r : a;
	});
};

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}

// date methods
Date.prototype.getMidnight = function() {
    return this.setHours(0, 0, 0, 0);
}

Date.prototype.getNoon = function() {
    return this.setHours(12, 0, 0, 0);
}

String.prototype.supplant = function(o) {
    return this.replace(/{([^{}]*)}/g,
        function(a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};


/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/

var dateFormat = function() {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function(val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function(date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function(mask, utc) {
    return dateFormat(this, mask, utc);
};


//

function trackFlash(arg) {
    window.tracker.track("home flash");
}

Site.HPlookfabTout = function(){
	var leftArrow = $('.lookFab .events a.leftArrow'),
	rightArrow = $('.lookFab .events a.rightArrow'),
	scrollWrap = $('.lookFab .events .scrollWrap'),
	scrollContent = $('.lookFab .events .scrollWrap ul'),
	listItemWidth = $('.lookFab .events .scrollWrap ul li').width(),
	listlength = $('.lookFab .events .scrollWrap ul li').length,
	newScrollWidth = (listItemWidth*listlength)+listItemWidth;
	
	//set scrollContent width;
	scrollContent.width(newScrollWidth);
	//events
	leftArrow.click(function(){
		var position = scrollContent.position();
		if(position.left < 0){
			scrollContent.animate({
				left: '+='+listItemWidth
			});
		}
	});
	rightArrow.click(function(){
		var position = scrollContent.position();
		var remainder = newScrollWidth + position.left;
		if((newScrollWidth-Math.abs(position.left)) > scrollWrap.width()){
			scrollContent.animate({
				left: '-='+listItemWidth
			});
		}
	});
	
	//click
	var cookieVal;
	$('.lookFab .events .scrollWrap ul li a').click(function(){
		$('.lookFab .events .scrollWrap ul li a').removeClass('active');
		$(this).addClass('active');
		cookieVal = $(this).html();
		createCookie('landingCookie',cookieVal);
	});
}

//cookie functions
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


























