// 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) {
            //killed wlc
            //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) {
            var mainURL = "/Themes/Custom/swf/21683_slimfast_homepage_anim_Look_Good.swf";
            var param = { wmode: "transparent", allowScriptAccess: "sameDomain" };
            var att = {}
            swfobject.embedSWF(mainURL, "flashHolder", "956", "450", "9.0.0", null, null, param, att);
        }
        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:gt(0)').hide();
            $('.user-activity-message-list .filter .view-type span.filter-option:gt(1)').hide();
        }
        $('.navigation-item .weblog, .navigation-item .media-gallery, .navigation-item .wiki').parent().hide();

        //restrict tags to pre-existing selections only
        $('.post-tags .field-item-input input').hide();

        // set up some default values for jquery ajax.
        // we never want to cache
        $.ajaxSetup({
            cache: false
        });

    },
    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");
        //New FriendRequest wrapper
        $requestWrap = $(".friendship-request-list");
        $requestHeader = $requestWrap.find(".content-fragment-header div");
        //console.log("cinveader:",$convHeader);    
        
        $(" <a href='javascript:void(0);'>Friend Requests</a> <span> | </span>").prependTo($convHeader)
        .click(function () {
            $requestWrap.show();
            $convWrap.hide();
            $friendWrap.hide();
        });
        $("<a href='javascript:void(0);'>FRIENDSHIP LIST</a> <span> | </span>").prependTo($convHeader)
                    .click(function () {
                        $requestWrap.hide();
                        $convWrap.hide();
                        $friendWrap.show();
                    });

        $(" <span> | </span> <a href='javascript:void(0);'>Friend Requests</a>").appendTo($friendHeader)
        .click(function () {
            $requestWrap.show();
            $convWrap.hide();
            $friendWrap.hide();
        });
        $("<span> | </span> <a href='javascript:void(0);'>MY CONVERSATIONS</a>").appendTo($friendHeader)
                    .click(function () {
                        $requestWrap.hide();
                        $convWrap.show();
                        $friendWrap.hide();
                    });

        // merging the Friend Request with Friend & Conversation List
        $("<a href='javascript:void(0);'>FRIENDSHIP LIST</a> <span> | </span> ").prependTo($requestHeader)
                    .click(function () {
                        $requestWrap.hide();
                        $convWrap.hide();
                        $friendWrap.show();
                    });
        $("<span> | </span> <a href='javascript:void(0);'>MY CONVERSATIONS</a>").appendTo($requestHeader)
                    .click(function () {
                        $requestWrap.hide();
                        $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 (measurementType, weight, height) {
        if (measurementType == 'standard') {
            return Math.round((weight / (height * height)) * 703);
        } else if (measurementType == 'metric') {
            return weight / ((height / 100) * (height / 100));
        }
    }
};
$(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 bmiCalculator = {
	init: function(){
		
		var measurementTypeHeight = 'metric';;
		var measurementTypeWeight = 'metric';;
		$('select.weightSelect').change(function(){
			if($(this).val() == 'Kg'){
				$('.weight').show();
				$('.weightSt').hide();
				$('td.lbsWrap').hide();
				$('.weightSt').val('');
				$('td.lbsWrap').val('');
				measurementTypeWeight = 'metric';
			}else{
				$('.weight').hide();
				$('.weight').val('');
				$('.weightSt').show();
				$('td.lbsWrap').show();
				measurementTypeWeight = 'standard';
			}
		});
		$('select.heightSelect').change(function(){
			if($(this).val() == 'm'){
				$('.inches').hide();
				$('.heightFt').hide();
				$('.heightMeters').show();
				$('span.inch').hide();
				$('span.cms').show();
				$('.heightIn').hide();
				$('.heightCentimeters').show();
				$('.heightFt').val('');
				$('.heightIn').val('');
				measurementTypeHeight = 'metric';
			}else{
				$('.heightMeters').hide();
				$('.heightFt').show();
				$('.inches').show();
				$('.heightCentimeters').hide();
				$('.heightIn').show();
				$('span.cms').hide();
				$('span.inch').show();
				$('.heightMeters').val('');
				$('.heightCentimeters').val('');
				measurementTypeHeight = 'standard';
			}
		});
		
		$('.calculateBmi a.btn').click(function(){
			bmiCalculator.validate(measurementTypeWeight,measurementTypeHeight);
		});
		
		$('.bmi .resetBtnHolder a.btn').click(function(){
			$('.bmi input').each(function(){
				$(this).val('')
			});
		});
		

	},
	validate: function(measurementTypeWeight,measurementTypeHeight){
		
		//WEIGHT
		var isNumWeightKilo = /^\d+(\.)?\d*$/.test($('#bmiyourCurrentWeightKilo').val());
		var isNumWeightSt = /^\d+$/.test($('#bmiyourCurrentWeightStones').val());
		
		if(isNumWeightKilo == false && isNumWeightSt == false){
			$('p.weightError').show();
			return;
		}else {
			$('p.weightError').hide();
		}
		
		//HEIGHT
		var isNumHeightMeters = /^\d+$/.test($('#bmiyourheightMeters').val());
		var isNumHeightFt = /^\d+$/.test($('#bmiyourHeightFt').val());
		
		if(isNumHeightMeters == false && isNumHeightFt == false){
			$('p.heightError').show();
			return;
		}else{
		
			if($('#bmiyourheightMeters').val() == '0'){
				$('p.heightError').show();
				return;
			}
			if($('#bmiyourHeightFt').val() == '0'){
				$('p.heightError').show();
				return;
			}
			
			$('p.heightError').hide();
		}
		

		var isNumHeightCenti = /^\d+$/.test($('#bmiyourheightCenti').val());
		var isNumHeightIn = /^\d+$/.test($('#bmiInches').val());
		if(isNumHeightIn == false && isNumHeightCenti == false){
			$('p.heightError').show();
			return;
		}
		var inches = Number($('#bmiInches').val());
		if(inches >= 12){
			$('p.heightError').show();
			return;
		}else{
			$('p.heightError').hide();
		}
		
		bmiCalculator.preformFunction(measurementTypeWeight,measurementTypeHeight);
	},
	preformFunction:function(measurementTypeWeight,measurementTypeHeight){
		//convert
		function turnToStone(n){
			return Math.round(n/14);
			// var numStr = new String(n/14);
			// return numStr.substring(0,4);
		}
		function turnToStoneLbs(n){
			var numStr = new String(n/14);
			var numSplit = numStr.split('.');
			var newStr;
			if(Math.round(n%14) > 0){
				newStr = numSplit[0]+'St '+Math.round(n%14)+'lbs ';
			}else{
				newStr =numSplit[0]+'St ';
			}
			return newStr;
		}
		
		
		$('.bmi .stepOne').slideUp();
		$('.bmi .stepTwo').slideDown();
		var weight;
		var height;
		var BMI;
		var yourW;
		var yourH;
		
		var bmis;
		var posLesser = 0;
		var posGreater;
		var greatBmis = [];
		var numberOneLess;
		var numberOneMore;
		var pos;
		
		
		//1 pound = 0.45359237 kilograms
		//1 inches = 2.54 centimeters

		var measurementType = measurementTypeWeight+'-'+measurementTypeHeight;
		switch(measurementType){
			case 'metric-metric':
				$('#wType').html('(Kg)');
				weight = $('#bmiyourCurrentWeightKilo').val();
				height = Number($('#bmiyourheightMeters').val()*100) + Number($('#bmiyourheightCenti').val());
				BMI = Site.calculateBMI('metric',weight,height)
				yourW = '<strong>'+ $('#bmiyourCurrentWeightKilo').val() + '</strong> Kg';
				yourH = '<strong>'+ $('#bmiyourheightMeters').val() + '</strong> m '+  '<strong>'+ $('#bmiyourheightCenti').val() + '</strong> cm';
				$('td.assessmentRow p').each(function(i){
					var avgBmiBot = Math.round($(this).children('span.avgBmiBot').html() * ( (height/100)*(height/100) ) );
					var avgBmiTop = Math.round($(this).children('span.avgBmiTop').html() * ( (height/100)*(height/100) ) );
					$(this).children('span.avgWeightBot').html(avgBmiBot + ' Kg');
					$(this).children('span.avgWeightTop').html(avgBmiTop+' Kg');
				});
				//fill in averageweights
				$('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/100)*(height/100) )));
					if(bmis < Math.round(BMI)){
						posLesser = $(this).position();
						numberOneLess = $(this).html();
					}
					if(bmis > Math.round(BMI)){
						greatBmis.push($(this));
					}
				});
			break;
			case 'standard-standard':
				$('#wType').html('(St)');
				weight = Number($('#bmiyourCurrentWeightStones').val() * 14 ) + Number($('#bmiyourCurrentWeightLbs').val());

				var heightInFt = $('#bmiyourHeightFt').val();
				var heightInIn =  $('#bmiInches').val() ;

				height = (Number(heightInFt) * 12) + Number(heightInIn);
				BMI = Site.calculateBMI('standard',weight,height);
				yourW = '<strong>'+ $('#bmiyourCurrentWeightStones').val()  + '</strong> St '+  '<strong>'+ $('#bmiyourCurrentWeightLbs').val() + '</strong> lbs';
				yourH = '<strong>'+ $('#bmiyourHeightFt').val() + '</strong> ft '+  '<strong>'+ $('#bmiInches').val() + '</strong> ins';

				
				$('td.assessmentRow p').each(function(i){
					var avgBmiBot = turnToStoneLbs($(this).children('span.avgBmiBot').html() * ((height*height) / 703));
					var avgBmiTop = turnToStoneLbs($(this).children('span.avgBmiTop').html() * ((height*height) / 703));
					
					
					
					$(this).children('span.avgWeightBot').html(avgBmiBot);
					$(this).children('span.avgWeightTop').html(avgBmiTop);
				});
				//fill in averageweights
				$('table.bmiChart td.bmiRow ol li').each(function(i){
					bmis = Number($(this).html());
					$('table.bmiChart td.weightRow ol li').eq(i).html(turnToStone((bmis * (height*height)) / 703));
					if(bmis < Math.round(BMI)){
						posLesser = $(this).position();
						numberOneLess = $(this).html();
					}
					if(bmis > Math.round(BMI)){
						greatBmis.push($(this));
					}
				});
			break;
			case 'metric-standard':
				$('#wType').html('(Kg)');
				weight = $('#bmiyourCurrentWeightKilo').val();
				var heightInFt = $('#bmiyourHeightFt').val();
				var heightInIn =  $('#bmiInches').val() ;
				standardHeight = (Number(heightInFt) * 12) + Number(heightInIn);
				height = standardHeight * 2.54;
				BMI = Site.calculateBMI('metric',weight,height);
				
				yourW = '<strong>'+ $('#bmiyourCurrentWeightKilo').val() + '</strong> Kg';
				yourH = '<strong>'+ $('#bmiyourHeightFt').val() + '</strong> ft '+  '<strong>'+ $('#bmiInches').val() + '</strong> ins';
				
				$('td.assessmentRow p').each(function(i){
					var avgBmiBot = Math.round($(this).children('span.avgBmiBot').html() * ( (height/100)*(height/100) ) );
					var avgBmiTop = Math.round($(this).children('span.avgBmiTop').html() * ( (height/100)*(height/100) ) );
					$(this).children('span.avgWeightBot').html(avgBmiBot + ' Kg');
					$(this).children('span.avgWeightTop').html(avgBmiTop+' Kg');
				});
				
				//fill in averageweights
				$('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/100)*(height/100) )));
					if(bmis < Math.round(BMI)){
						posLesser = $(this).position();
						numberOneLess = $(this).html();
					}
					if(bmis > Math.round(BMI)){
						greatBmis.push($(this));
					}
				});
			break;
			case 'standard-metric':
				$('#wType').html('(St)');
				weight = Number($('#bmiyourCurrentWeightStones').val() * 14 ) + Number($('#bmiyourCurrentWeightLbs').val());
				metricHeight = Number($('#bmiyourheightMeters').val()*100) + Number($('#bmiyourheightCenti').val());
				height = metricHeight / 2.54;
				
				BMI = Site.calculateBMI('standard',weight,height);
				yourW = '<strong>'+ $('#bmiyourCurrentWeightStones').val()  + '</strong> St '+  '<strong>'+ $('#bmiyourCurrentWeightLbs').val() + '</strong> lbs';
				yourH = '<strong>'+ $('#bmiyourheightMeters').val() + '</strong> m '+  '<strong>'+ $('#bmiyourheightCenti').val() + '</strong> cm';

				$('td.assessmentRow p').each(function(i){
					var avgBmiBot = turnToStoneLbs($(this).children('span.avgBmiBot').html() * ((height*height) / 703));
					var avgBmiTop = turnToStoneLbs($(this).children('span.avgBmiTop').html() * ((height*height) / 703));
					$(this).children('span.avgWeightBot').html(avgBmiBot);
					$(this).children('span.avgWeightTop').html(avgBmiTop);
				});
				//fill in averageweights
				$('table.bmiChart td.bmiRow ol li').each(function(i){
					bmis = Number($(this).html());
					
					$('table.bmiChart td.weightRow ol li').eq(i).html(turnToStone((bmis * (height*height)) / 703));
					
					if(bmis < Math.round(BMI)){
						posLesser = $(this).position();
						numberOneLess = $(this).html();
					}
					if(bmis > Math.round(BMI)){
						greatBmis.push($(this));
					}
				});
			break;
		}
		$('.yourStats .yourW span').html(yourW);
		$('.yourStats .yourH span').html(yourH);

		$('.yourBmiIs span.bmiIs').html(Math.round(BMI));
		$('.bmiOverlayInner .actualBmi').html(Math.round(BMI));
		
		//messaging
		if(BMI <= 18){
			$('.yourBmiIs span.considered').html('UNDERWEIGHT');
			$('.messaging').html('<p>If your BMI is within the underweight category (less than 18.5), this can indicate that you should not be trying to lose weight and instead should be trying to achieve a healthy body weight. If you have any questions about your weight you should speak to your GP. </p>')
		}
		if(BMI > 18){
			$('.yourBmiIs span.considered').html('Healthy body weight');
			$('.messaging').html('<p>If your BMI calculation is within the normal healthy range (18.5-25), this can indicate that you are a healthy weight for your height, and that no further weight loss is needed. You should try and maintain your existing body weight.</p>')
			
			if(BMI.toFixed(0) == 25) {
			    $('.messaging').append('<p>While our BMI has come out within the borderline healthy range of 25, a BMI of 25 and over actually puts you in the overweight category.</p>');
			}
		}
		if(BMI > 25){
			$('.yourBmiIs span.considered').html('OVERWEIGHT');
			$('.messaging').html('<p>Body Mass Index (BMI) is a calculation that uses your height and weight to determine a number which gives an indication of whether your weight fits into a healthy recommended range or whether you are at risk of being under- or over weight. If you are an adult and your BMI is over 25, this can indicate that you are overweight and that you may benefit from weight loss.</p>')
		}
		if(BMI > 29){
			$('.yourBmiIs span.considered').html('OBESE');
			$('.messaging').html('<p>If your BMI calculation is greater than 30, this can indicate that you are obese, and currently have more than 20% of your body weight to lose. You should consult your GP or dietician about your weight loss plans. </p>')
		}
		
		//animations
		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 > 23 && Math.round(BMI) == 24){
			var aniTo = -192;
			$('.bmiOverlayInner').animate({
				top: aniTo
			});
			return;
		}
		if(BMI > 24 && BMI < 26){
			var aniTo = -152;
			$('.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");
}
