// JavaScript Document
var displaySearchResults;
var displayFacebookCommentString;

(function($) {
    $(document).ready(function() {
        // Campaign home page
        //Function calls (Michael DeWeese)
        AddClassToFooter();
        AddClickEventToAdditionalLink();
        ShowConfirmation();
        AddAlertToRecipeFromMGC();
 
   //fixes ie7 z-index on workout popups
   if($('.workouts').length !==0) {

        var zIndexNumber = 1000;
        $('.workouts div').each(function() {
	        $(this).css('zIndex', zIndexNumber);
	        zIndexNumber -= 5;
        });
     }


        hookUpInifiniteScroll();
        var imageIndex = 0;
        var resume = true;
        if (location.hash != '')
        {
            var deepLinkName = location.hash.substring(1);
            var hiddeninput = $('#cycleContainer input[value="' + deepLinkName + '"]');
            if (hiddeninput != null)
            {
                var deepLinkImageIndex = hiddeninput.prev().attr('rel');
                if (deepLinkImageIndex != null)
                {
                    imageIndex = deepLinkImageIndex - 1;
                    resume = false;
                }
            }

            //setPagingPage(deepLinkName);
        }
        
        var slideshow = $('.slideshow').cycle({
                fx: 'scrollHorz',
                pager: '#cyclePagination',
                timeout: 5000,
                pause: 1,
                after: ResumeSlideShow,
                startingSlide: imageIndex,
                pagerAnchorBuilder: function(idx, slide) {
                    return '<li><a href="#"></a></li>';
                }
            });

        slideshow.cycle(resume ? 'resume' : 'pause', true);



        $("#sub_column img").error(function() {
            $(this).hide();
        });

        $('#topics_overview #sections .item ol li:last').css('border-bottom', 'none');


        // Stories select resize
        $('select.styled').css({ width: '287px', height: '34px', '-webkit-appearance': 'menulist-button' });

        // Search form label
        $('#search_form label').perfectForm();
        $('#search_form label').css({ top: '13px', color: '#898989' });

        //Fancybox
        var shareFrame = $("#shareStoryFrame");

        $("#shareStory, #shareStoryTitle, a.campaign-page.submit-story")
            .fancybox({
                    width: 'auto',
                    height: 'auto',
                    autoDimensions: true,
                    autoScale: false,
                    padding: 0,
                    showCloseButton: true,
                    hideOnOverlayClick: false,
                    hideOnContentClick: false,
                    enableEscapeButton: false
                })
            .click(function() {
                shareFrame.attr("src", "/layouts/Stories/Story.aspx");
            })
            .css('cursor', 'pointer');
        ;

        $('.product_breadcrumb .view_all')
            .fancybox({
                    width: 'auto',
                    height: 'auto',
                    autoDimensions: true,
                    autoScale: false,
                    padding: 0
                });


        //jscrollpane initialization
        $('.scroll').jScrollPane();


        $('#product_carousel .carousel').jcarousel({
                visible: 5,
                scroll: 3,
                itemFallbackDimension: 158,
                buttonNextHTML: '<a href="#" class="button next">Next</a>',
                buttonPrevHTML: '<a href="#" class="button prev">Previous</a>'
            });

        //search result view switching
        $('.list_view a').click(function(e) {
            e.preventDefault();
            var state = $(this).attr('rel');
            switchView(state);
        });

        $('.grid_view a').click(function(e) {
            e.preventDefault();
            var state = $(this).attr('rel');
            switchView(state);
        });

        //jQuery UI Accordion
        var icons = {
            header: "ui-icon-circle-arrow-e",
            headerSelected: "ui-icon-circle-arrow-s"
        };
        $("#accordion").accordion({
                /* icons: icons */
                icons: { 'header': 'expand', 'headerSelected': 'collapse' },
                change: function(e, els) {
                    $(els.newContent).jScrollPane();
                }
            });

        $("#toggle").button().toggle(function() {
            $("#accordion").accordion("option", "icons", false);
        }, function() {
            $("#accordion").accordion("option", "icons", icons);
        });

        //Image Carousel
        $('#display img:first')
            .addClass('active')
            .css({ 'opacity': '1.0', 'z-index': '2' })
            ;

        var thumbCounter = 1;
        $('#display img:not(a img)')
            .each(
            function() {
                var thumbImg = $(this)
                    .clone()
                    .css('width', 'auto')
                    ;
                var thumbImageLink = $('<a href="#" rel="' + thumbCounter + '"></a>').html(thumbImg);
                var listItemWrapper = $('<li></li>').html(thumbImageLink);
                $('#nav ol').append(listItemWrapper);
                thumbCounter++
            }
    		)
            ;

        $('#nav li:first')
            .addClass('active')
            ;
        $('#nav li a').click(function(e) {
            e.preventDefault();
            clearInterval(play);
            if ($(this).parent('li').attr('class') != 'active') {
                carSwitch($(this).attr('rel'));
            }
            play = setInterval(carAutoSwitch, 5000);
        });

        var play = setInterval(carAutoSwitch, 5000);

        var selectedSearchTermUrl = null;

        $('input.search_input').autocomplete({
                source: function(request, response) {
                    var searchTerm = $('input.search_input').val()
                    $.ajax({
                            url: "/Services/SearchServiceASMX.asmx/GetSearchResults?Query='" + searchTerm + "'",
                            type: 'GET',
                            dataType: "json",
                            contentType: 'application/json; charset=utf-8',
                            success: function(data) {
                                response($.map(data.d, function(item) {
                                    return {
                                        label: item.Title.replace(new RegExp(searchTerm, "i"), '<strong>' + searchTerm + '</strong>'),
                                        value: item.Title,
                                        url: item.URL
                                    };
                                }));
                            },
                            error: function(request, status, error) {

                            }
                        });
                },
                minLength: 2,
                html: true,
                select: function(event, ui) {
                    window.location.pathname = ui.item.url;
                },
                focus: function(e) {
//				var el = $(e.relatedTarget);
//				el.parents("ul:first").find(".ui-state-hover")
//					.removeClass("ui-state-hover");
//				
//				if(el.is("span")){
//					el.parent().addClass("ui-state-hover");	
//				}
//				else{
//					el.addClass("ui-state-hover");
//				}
                },
                open: function() {
                    //Auto Complet DropDown

                    $('.ui-autocomplete').css('margin-top', '3px');
                    $('.ui-autocomplete li:odd').addClass('odd');

                    $('.ui-autocomplete li a').each(function() {
                        var item = '<span>' + $(this).html() + '</span>';
                        $(this).html(item);
                    });
                    $('.ui-autocomplete li a span').widthTruncate({ width: 360 });
                }
            });


		$('.dropdown .drop_list')
			.hide()
		;
		$('.dropdown .drop_trigger')
			.click(function(e) {
				e.preventDefault();
		   		$(this).siblings('.drop_list').show();
			})
		;
		$('.dropdown .drop_list li:first')
			.click(function(e) {
				e.preventDefault();
		   		$(this).parent('.drop_list').hide();
			})
		;
		$('.dropdown .drop_list .close')
			.click(function() {
		   		$(this).parent('.drop_list').hide();
			})
		;
		$('.dropdown')
			.mouseleave(function() {
				$(this).find('.drop_list').hide();
			})
		;

		$('.dropdown .drop_list li a')
			.click(function(e) {
				if(hasValidClientSideTarget())
				{
                    $('#gridResults').infinitescroll('rebind',null);
					e.preventDefault();
                    var href = setClientSideHref($(this).attr('href'));
                    href = addPagingToCategory(href);
                    var category = $(this).text();
                    $('#gridResults').infinitescroll('hashCurrentPage',category);
                    href = href.replace(category.toLowerCase(),category);
                    displaySearchResultsWithCategory(href, $(this).text());
                    
				}
			})
		;




        //Modified Event to add paging (Michael DeWeese)
        $('select[id$=ddlCategories]')
            .change(function(e) {
                if (hasValidClientSideTarget())
                {
                    $('#gridResults').infinitescroll('rebind',null);
                    var href = setClientSideHref($(this).val());
                    href = addPagingToCategory(href);
                    var category = getCurrentCategory();
                    $('#gridResults').infinitescroll('hashCurrentPage',category);
                    displaySearchResultsWithCategory(href, $(this).find('option[value=' + $(this).val() + ']').text());
                    
                }
            })
            ;



        //Paged List Grid
        $('a[id*=SearchResultsList_next]')
            .click(function(e) {
                if (hasValidClientSideTarget())
                {
                    e.preventDefault();
                    var href = setClientSideHref($(this).attr('href'));
                    displaySearchResults(href);
                }
            })
            ;
        $('a[id*=SearchResultsList_prev]')
            .click(function(e) {
                if (hasValidClientSideTarget())
                {
                    e.preventDefault();
                    var href = setClientSideHref($(this).attr('href'));
                    displaySearchResults(href);
                }
            })
            ;

        //Click Event for the BMI Calculator (Michael DeWeese)
        $('#btn_bmicalculate').click(function (e) {
            DoBMICalculations();
            return false;
        });


        //sidbar box text shrink
        $(".mod .mod_content").each(function() {
            var el = $(this);
            var copy = el.find(".mod_copy");
            var trimmed = false;
            while (el[0].clientHeight < el[0].scrollHeight) {
                var text = copy.text();
                copy.text(text.slice(0, text.length - 1));
                trimmed = true;
            }
            if (trimmed) {
                copy.html(copy.text().slice(0, text.length - 10) + "&hellip;");
            }
        });

        //setup tracking events
        (function() {
            $("a[data-unica],a[data-floodlight],a[data-sem]").each(function() {
                var te = new TrackingEvent(this);
                var $el = $(this);
                if ($el.is("[data-unica]")) {
                    te.unica($el.attr("data-unica"));
                }
                if ($el.is("[data-floodlight]")) {
                    te.floodlight($el.attr("data-floodlight"));
                }
                if ($el.is("[data-sem]")) {
                    te.sem($el.attr("data-sem"));
                }
            });
        })();

        
        var workoutHoverTimer;
        $("#workout_grid .workouts td").hover(function() {
            var $this = $(this);
            clearTimeout(workoutHoverTimer);
            workoutHoverTimer = setTimeout(function() {
                var $thisPopout = $(".popout", $this);
                $(".popout").not($thisPopout).hide();
                $thisPopout.show();
            }, 500);
        }, function() {
            clearTimeout(workoutHoverTimer);
            $(".popout").hide();
        });

        $.positionWorkoutPlayer = function(hide) {
            var position;
            if( hide ) {
                position = { top: -10000, left: -10000 };
            }else {
                position = $("#workout_modal .ooyala").offset();
                $("#VideoPlayerOoyalaPlayerOutterWrapper").parents().each(function() {
                    if ($(this).css("position") != "static") {
                        var wrapperOffset = $("#wrapper").offset();
                        position.left -= wrapperOffset.left;
                        position.top -= wrapperOffset.top;
                    }
                });   
            }

            $("#VideoPlayerOoyalaPlayerOutterWrapper").css(position);
        };
        
        // Workout FancyBox (Ken Beck)
        var populateWorkoutModal = function() {
            $(".popout").hide();
            $.positionWorkoutPlayer(true);

            var $this = $(this);
            var id = $("#workout_modal").data("id");
            var allExercises = $.workouts[id].AllExercises;
            var circuitExercises = $.workouts[id].CircuitExercises;

            var idx = $this.data("idx") || 0;
            var circuit = $this.data("circuit") || 0;
            var currentExercise = 0;
            if(circuit == 2)
            {
                currentExercise = allExercises[allExercises.length - 1];
            }
            else
            {
                currentExercise = $this.hasClass("modal_nav") ? circuitExercises[idx] : allExercises[circuit][idx];
            }
            var tmplData =
                        {
                            CurrentExercise: currentExercise,
                            Index: idx,
                            Exercises: circuitExercises,
                            ShowProgress: $this.data("showProgress") || $this.hasClass("modal_nav")
                        };

            var videoId = currentExercise.OoyalaVideoId;
            var videoParams = { };
            var videoIdParts = videoId.split( /&/ );
            for(var i=0;i<videoIdParts.length;i++) {
                var kvp = videoIdParts[i].split( /=/ );
                if( kvp.length == 1 ) {
                    videoParams["embedCode"] = kvp[0];
                }else {
                    videoParams[kvp[0]] = kvp[1];
                }
            }

            videoParams["hide"] = "sharing";
            
            if(document.getElementById("VideoPlayer").setQueryStringParameters) {
                $.playerVideoParams = videoParams;
                if( !$.playerWaiting ) {
                    document.getElementById("VideoPlayer").setQueryStringParameters(videoParams);
                    $.playerWaiting = true;
                }
                
            }

            $("#workout_modal").html($("#workout_modal_tmpl").tmpl(tmplData).html());
            if( tmplData.ShowProgress ) {
                // Set progress bar
                $("#workout_modal .progress-bar").each(function () {
                    $(this).progressbar({ value: (idx+1) / circuitExercises.length * 100 | 0 });
                    var progressHead = $('<div class="progress_head" />');
                    var progressTail = $('<div class="progress_tail" />');
                    var progressValue = $('.ui-progressbar-value', $(this));

                    // adds rounded end cap and progress arrow
                    if (idx >= 0) {
                        progressValue.append(progressHead);
                        progressValue.append(progressTail);
                    }

                    // adds a different class if progress complete (for rounded edge)
                    if (idx == circuitExercises.length-1) {
                        progressHead.addClass('progress_complete');
                    }
                });
            }
            
            return false;
        };
  
        $("#workout_modal .modal_nav").live('click', function() {
            if($("#VideoPlayer")[0].setEmbedCode) {
                $("#VideoPlayer")[0].setEmbedCode("");
            }
            populateWorkoutModal.call(this);
        });
        $(".workout_modal_link").each(function() {
            var $this = $(this);
            var id = $this.data("id") || $this.parents("ul").data("id");
            
            if (!$.workouts) $.workouts = { };
            if (!$.workouts[id]) {
                // Cache workout data
                id = id.substring(1,id.length-1);
                var path = "/Services/WorkoutService.asmx/GetWorkout?WorkoutId='" + id  +"'";
                $.ajax({
                        type: "GET",
                        dataType: "json",
                        cache: true,
                        contentType: 'application/json; charset=utf-8',
                        url: path,
                        success: function(data) {
                            var workout = data["d"];
                            var exercises = [workout.Circuit1Exercises, workout.Circuit2Exercises];

                            var circuitExercises = [];
                            for (var i = 0; i < exercises.length; i++) {
                                for (var j = 0; j <= 2; j++) {
                                    circuitExercises = circuitExercises.concat(exercises[i]);
                                }
                            }
                            if(workout.FinishWithExercise != null)
                            {
                                circuitExercises = circuitExercises.concat(workout.FinishWithExercise);
                                exercises = exercises.concat(workout.FinishWithExercise);
                            }

                            $.workouts[id] = {
                                AllExercises: exercises,
                                CircuitExercises: circuitExercises
                            };
                        }
                    });
            }

            $this.click(function() {
                $("#workout_modal").data("id", id);
                populateWorkoutModal.call($this);
                return false;
            });
        });
        
        $("#VideoPlayerOoyalaPlayerOutterWrapper").css({ left: -1000, top: -1000 });
        $(".workout_modal_link")
            .fancybox({
                autoDimensions: false,
                width: 'auto',
                height: 'auto',
                autoScale: false,
                padding: 0,
                showCloseButton: true,
                hideOnOverlayClick: false,
                hideOnContentClick: false,
                enableEscapeButton: false,
                onCleanup: function() {
                    $.playerVisible = false;
                    if($("#VideoPlayer")[0].pauseMovie) {
                        $("#VideoPlayer")[0].pauseMovie();
                        $("#VideoPlayer")[0].setPlayheadTime(0);
                        $("#VideoPlayer")[0].setEmbedCode("");
                    }
                    $.positionWorkoutPlayer(true);
                },
                onComplete: function() {
                    $.playerVisible = true;
                }
            });

        var resizeTimer;
        $(window).resize(function() {
            clearTimeout(resizeTimer);
            $.positionWorkoutPlayer(true);
            resizeTimer = setTimeout(function() {
                if ($.playerVisible)
                    $.positionWorkoutPlayer(false);
            }, 500);
        });
        
        
        // Cardio Workout FancyBox
        $(".cardio_modal_link").each(function() {
            var $this = $(this);
            var id = $this.data("id");

            if(!$.cardio) $.cardio = { };
            if(!$.cardio[id]) {
                // Cache cardio data
                id = id.substring(1,id.length-1);
                var path = "/Services/WorkoutService.asmx/GetCardioWorkout?CardioWorkoutId='" + id  +"'";
                $.ajax({
                        type: "GET",
                        cache: true,
                        dataType: "json",
                        contentType: 'application/json; charset=utf-8',
                        url: path,
                        success: function(data) {
                            $.cardio[id] = data["d"];
                        }
                    });
            }
            
            $this.click(function() {
                $("#cardio_workout_modal").html($("#cardio_modal_tmpl").tmpl($.cardio[id]).html());

                return false;
            });
        })
        .fancybox({
            autoDimensions: false,
            width: 'auto',
            height: 'auto',
            autoScale: false,
            padding: 0,
            showCloseButton: true,
            hideOnOverlayClick: false,
            hideOnContentClick: false,
            enableEscapeButton: false
        });
    });

    function ResumeSlideShow() {

        $('.slideshow').cycle('resume');
    }

    var setPagingPage = function(pageNumber)
    {
        if($('#search_results').length !== 0)
        {
            var action = $('form').attr('action');
            var url = action + '?p=' + pageNumber;
            var href = setClientSideHref(url);
            displaySearchResults(href);
        }
    }

	var setClientSideHref = function(originalHref)
	{
        originalHref = originalHref.toLowerCase();
		if(!hasValidClientSideTarget()) 
		{
			return originalHref;
		}

		if(pagedListGridClientTargetUrl.indexOf("?") >= 0 && originalHref.indexOf("?") >= 0 && pagedListGridServerTargetUrl.indexOf("?") < 0)
		{
			// If we're in here, we're about to have two query-string start characters (?) and we need to change one, giving priority to the base url
			originalHref = originalHref.replace("?","&");
		}
		return originalHref.replace(pagedListGridServerTargetUrl.toLowerCase(), pagedListGridClientTargetUrl.toLowerCase());
	};

	var hasValidClientSideTarget = function()
	{
		return !(!pagedListGridClientTargetUrl || !pagedListGridServerTargetUrl);
	};



    getCurrentCategory = function()
    {
        if($('select[id$=ddlCategories]').length == 0)
        {
            return $('.dropdown div.drop_trigger').text();
        }
        else
        {
            return $('select[id$=ddlCategories]').find('option[value=' + $('select[id$=ddlCategories]').val() + ']').text();
        }
    };

    //Hooks up infinite scroll js to the grid paging.
    hookUpInifiniteScroll = function() {
        if($('#gridResults').length == 0)
        {
            return;
        }
        var infiniteScroll = $('#gridResults').infinitescroll({
            navSelector : ".paginator",
            nextSelector : ".paginator .next2",
            itemSelector : "#gridResults li",
            debug : false,
            loading : {
                img : "",
                msgText : "",
                finishedMsg : ""
            }
        }, 
        function(arrayOfNewElems){
            var category = getCurrentCategory();
            
            $('#gridResults').infinitescroll('hashCurrentPage',category);
        });

        $('.paginator').hide();
        if(location.hash != '')
        {
            var categoryString = location.hash.substring(location.hash.lastIndexOf('&') + 1).substring(2);
            var currentPage = parseInt(location.hash.substring(4, location.hash.lastIndexOf('&')));
            if(isNaN(currentPage))
            {
                currentPage = 1;
            }
            var action = $('form').attr('action');
            var url = action + '?p=' + currentPage + '&s=1';

            if(action.indexOf('?') != -1)
            {
                var url = action + '&p=' + currentPage + '&s=1';
            }
            var href = setClientSideHref(url);
            if(categoryString == '')
            {
                displaySearchResults(href);
            }
            else 
            {
                href = href + '&c=' + categoryString
                displaySearchResultsWithCategory(href,categoryString);
            }
            $('#gridResults').infinitescroll('updateCurrentPage',currentPage);
        }
        
    };

    addPagingToCategory = function(href) {
        var currentPage = 1;
        var startPage = 1;
        if(location.hash != '')
        {
            currentPage = parseInt(location.hash.substring(1)); 
            if(isNaN(currentPage))
            {
                currentPage = 1;
            }
        }
        href = href + "&p=" + currentPage + "&s=" + startPage;
        return href;
    };

    //Added to get past a weird logic loop with the Category text not being upper cased (Michael DeWeese)
    displaySearchResultsWithCategory = function(href, category) {

		$.get( href, function(data) {
			var pageCountText = $(data).find('#PageCountText').val();
			var currentPage = parseInt($(data).find('#CurrentPageValue').val());
			var totalPages = parseInt($(data).find('#TotalPagesValue').val());
            var totalResults = parseInt($(data).find('#CurrentTotalResults').val());

			// Handle category dropdown
			$('.dropdown .drop_trigger').text((category == '') ? 'View All Results' : category);
    		$('.dropdown .drop_list').hide();

			// Replace data
            if($("#gridResults li").length == 0)
            {
                $("#gridResults").append($(data).find("li"));
            }
            else
            {
			    $("#gridResults li").replaceWith($(data).find("li"));
            }
            if(totalResults != '' && isNaN(totalResults) == false)
            {
                $("#result_info span.result_span").text(totalResults + " Results");
            }
            else
            {
                $("#result_info span.result_span").text($(data).find("li").length + " Results");
            }

            var currentNextNav = $(".paginator .next2").attr('href');
            
            if(currentNextNav.indexOf('&c=') >= 0)
            {
                currentNextNav = currentNextNav.substring(0,currentNextNav.indexOf('&c='));
            }



            $(".paginator .next2").attr('href', currentNextNav + '&c=' + escape(category));
            $('#gridResults').infinitescroll('updatePath');
		});
    };

	displaySearchResults = function(href) {
		$.get( href, function(data) {
			var categoryText = $(data).find('#CurrentCategory').val();
			var pageCountText = $(data).find('#PageCountText').val();
			var currentPage = parseInt($(data).find('#CurrentPageValue').val());
			var totalPages = parseInt($(data).find('#TotalPagesValue').val());
            var totalResults = parseInt($(data).find('#CurrentTotalResults').val());

			//Handle paging
			//handlePagedListGridPaging(currentPage, totalPages, pageCountText, categoryText);

			// Handle category dropdown
			$('.dropdown .drop_trigger').text((categoryText == '') ? 'View All Results' : categoryText);
    		$('.dropdown .drop_list').hide();

			// Replace data
            if($("#gridResults li").length == 0)
            {
                $("#gridResults").append($(data).find("li"));
            }
            else
            {
			    $("#gridResults li").replaceWith($(data).find("li"));
            }
            if(totalResults != '')
            {
                $("#result_info span").text(totalResults + " Results");
            }
            else
            {
                $("#result_info span").text($(data).find("li").length + " Results");
            }
//			$("#gridResults").quicksand($(data).find('li'), {
//				duration: 800,
//				easing: 'easeInOutQuad',
//				adjustHeight: 'auto'
//			});
		});
    };


	var handlePagedListGridPaging = function(currentPage, totalPages, pageCountText, currentCategory)
	{
		$(".paginator li.page_count").text(pageCountText);
		var nextButtons = $('a[id*=SearchResultsList_next]');
		var prevButtons = $('a[id*=SearchResultsList_prev]');
        
		//location.hash = '#' + currentPage;

		if(nextButtons && nextButtons.length > 0)
		{
			if(currentPage >= totalPages) 
			{
				nextButtons.hide();
			}
			else
			{
				nextButtons.show();
			}

			var href = nextButtons.attr('href');
			var newHref= href.replace(/p=(\d*)/, 'p='+(currentPage+1));
			//Handle Reverse Moves
			if(href == newHref) newHref = href.replace('p='+(currentPage+2), 'p='+(currentPage+1));

			newHref = setPagingUrlCategory(newHref, currentCategory);
			nextButtons.attr('href',newHref);
		}

		if(prevButtons && prevButtons.length > 0)
		{
			if(currentPage <= 1)
			{
				prevButtons.hide();
			}
			else
			{
				prevButtons.show();
			}
				
			var href = prevButtons.attr('href');
			var newHref= href.replace(/p=(\d*)/, 'p='+(currentPage-1));
			//Handle Reverse Moves
			if(href == newHref) newHref = href.replace('p='+(currentPage), 'p='+(currentPage-1));

			newHref = setPagingUrlCategory(newHref, currentCategory);
			prevButtons.attr('href',newHref);
		}
	};

    var DoBMICalculations = function()
    {
           var weight = $('#bmi_weight').val();
            var feet = $('#bmi_height').val();
            var inches = $('#bmi_height_in').val();
            if(weight == '' || feet == '' || inches == '')
            {
                ShowBMIError("Please fill out all fields");
                return false;
            }
            var inchesParsed = parseInt(inches);
            var feetParsed = parseInt(feet);
            var height = (feetParsed * 12) + inchesParsed

            if(isNaN(parseInt(weight)) || parseInt(weight) <= 0)
            {
                ShowBMIError("Please enter a valid weight in lbs.");
                return false;
            }

            var SHORTEST_KNOWN_PERSON_IN_THE_WORLD = 23; //inches ref: http://en.wikipedia.org/wiki/List_of_shortest_people

            if(height <= SHORTEST_KNOWN_PERSON_IN_THE_WORLD)
            {
                ShowBMIError("Please enter a valid height.");
                return false;
            }

            var result = Math.round(((weight * 703) / Math.pow(height, 2)) * 10) / 10;
            if(isNaN(result))
            {
                ShowBMIError("Enter in whole numbers");
                return false;
            }

            //Chop off the decimal if it's over 3 digits
            if(result > 100) {
                result = Math.round(result);
            }

            $('#bmi_height').val(parseInt(height / 12));
            $('#bmi_height_in').val(height % 12);
            $('#bmi_weight').val(parseInt(weight));
            
            $('.error').hide();
            $('.instructions').hide();
            if(result < 18.5)
            {
                $('.bmi_obese').hide();
                $('.bmi_overweight').hide();
                $('.bmi_underweight').fadeIn();
                $('.bmi_normal').hide();
            }
            else if(result >= 18.5 && result <= 24.9)
            {
                $('.bmi_obese').hide();
                $('.bmi_overweight').hide();
                $('.bmi_underweight').hide();
                $('.bmi_normal').fadeIn();
            }
            else if(result >= 25 && result <= 29.9)
            {
                $('.bmi_obese').hide();
                $('.bmi_overweight').fadeIn();
                $('.bmi_underweight').hide();
                $('.bmi_normal').hide();
            }
            else if(result >= 30)
            {
                $('.bmi_obese').fadeIn();
                $('.bmi_overweight').hide();
                $('.bmi_underweight').hide();
                $('.bmi_normal').hide();
            }
            $('.bmi_indicator').removeClass('not_complete',400);
            $('.your_result').text(result);

            return false;
    };

    var ShowBMIError = function(message)
    {
          $('.error').text(message);
          $('.error').show();
          $('.bmi_type').hide();
          $('.instructions').fadeIn();
          $('.bmi_indicator').addClass('not_complete',400);
    };

	var setPagingUrlCategory = function(url, currentCategory)
	{
		var regx = new RegExp("&c=[^&$]*");
		var m = regx.exec(url);
		if(m != null)
		{
			url = url.replace(regx, "&c="+currentCategory);
		}
		else
		{
			if(url.indexOf("?") >= 0)
			{
				url += "&c="+currentCategory;
			}
			else
			{
				url += "?c="+currentCategory;
			}
		}
		
		return url;
	};

    //Filter results by category [deprecated?]
    var filterCat = function(cat, sortList, replacement) {
		$('.dropdown .drop_trigger').text(cat.text());
    	$('.dropdown .drop_list').hide();
    	
    	var category = cat.attr('id');
    	
    	if(category == 'all') {
	    	var filteredData = replacement.find('li');
    	} else {
	    	var filteredData = replacement.find('li[data-type="'+ category +'"]');
    	}
    	
    	//console.log(filteredData);
    	
		sortList.quicksand(filteredData, {
			duration: 800,
			easing: 'easeInOutQuad'
	    });
    }

    //Adding Class to the More from Cheerios Interior Footer based on the page (Michael DeWeese)
    var AddClassToFooter = function()
    {
        if($('.recipe_detail').length == 0)
        {
            return;
        }

        $('#interior_footer').addClass('recipe_list');
    }

    var AddClickEventToAdditionalLink = function()
    {
        if($('.additional_link_box').length == 0)
        {
            return;
        }


        $('.additional_link_box, .third_link').click(function(e)
        {
            var url = $(this).find(">:first-child").data('url');
            if(url.length == 0)
            {
                return;
            }
            var showConfirm = $(this).find(">:first-child").data('showconfirm');
            var confirmMessage = $(this).find(">:first-child").data('confirmmessage');
            e.preventDefault();
            e.stopPropagation();
            if(showConfirm == "True")
            {
                if(!confirm(confirmMessage))
                {
                    return;
                }
                window.open(url, '_blank');
                return;
            }
            window.open(url, '_self');
            return;
        });
    }

    var AddAlertToRecipeFromMGC = function()
    {
        if($('.multigrain .menuRecipes').length == 0)
        {
            return;
        }
        $('.multigrain .menuRecipes').click(function(e)
        {
            if(!confirm("The recipes in other sections of Cheerios.com are not associated with the Fitness Magazine weight loss plan. Continue?"))
            {
                e.preventDefault();
                e.stopPropagation();
            }
        });
    }

    var ShowConfirmation = function()
    {
        $('.show_confirmation').click(function(e) {
            var message = $(this).data('confirmmessage');
            if (!confirm(message))
            {
                e.preventDefault();
                e.stopPropagation();
            }
        });
    }

    
    //Carousel Click Switch
    var carSwitch = function(slideNum) {
        var activeDisplay = $('#display img.active');
        var activeThumb = $('#nav li.active');
        
        $('#display img[rel*="'+slideNum+'"]')
            .stop()
            .addClass('active')
            .css({'opacity': '0', 'z-index': '2.0'})
            .animate({'opacity': '1.0'}, 1000)
        ;
        $('#nav li a[rel*="'+slideNum+'"]')
            .stop()
            .parent('li')
            .addClass('active')
        ;
        activeDisplay
            .stop()
            .removeClass('active')
            .animate({'opacity': '0'}, 1000)
        ;
        activeThumb
            .stop()
            .removeClass('active')
        ;
        
    }

    //Switched the Tab active state (Michael DeWeese)
    var switchTabActive = function() {
        if($('.tabs').length == 0)
        {
            return;
        }


    }
    
    //Carousel Auto Switch
    var carAutoSwitch = function() {
        var activeDisplay = $('#display img.active');
        var activeThumb = $('#nav li.active');
        if(activeDisplay.next('img').length) {
            activeDisplay
                .next('img')
                .stop()
                .addClass('active')
                .css({'opacity': '0', 'z-index': '2.0'})
                .animate({'opacity': '1.0'}, 1000)
            ;
            activeThumb
                .next('li')
                .stop()
                .addClass('active')
            ;
        } else {
            $('#display img:first')
                .stop()
                .addClass('active')
                .css({'opacity': '0', 'z-index': '2.0'})
                .animate({'opacity': '1.0'}, 1000)
            ;
            $('#nav li:first')
                .stop()
                .addClass('active')
            ;
        }
        activeDisplay
            .stop()
            .removeClass('active')
            .animate({'opacity': '0'}, 1000)
        ;
        activeThumb
            .stop()
            .removeClass('active')
        ;
    }
        
    
    //search result view switching
    var switchView = function(state) {
        var list = $('.list');
        var grid = $('.grid');
        var list_btn = $('.list_view a')
        var grid_btn = $('.grid_view a')
        
        list_btn.removeClass('active');
        grid_btn.removeClass('active');
        
        grid.fadeOut(0);
        list.fadeOut(0);
        
        if(state == 'list') {
            grid.addClass('list');
            grid.removeClass('grid');
            list_btn.addClass('active');
            grid.find('img').css('visibility','hidden');
        } else if(state == 'grid') {
            list.addClass('grid');
            list.removeClass('list');
            grid_btn.addClass('active');
            list.find('img').css('visibility','visible');
        }
        
        grid.fadeIn();
        list.fadeIn();
        
    }

    jQuery.fn.perfectForm = function(options)
    {
        var settings = {
            overlap: true,
            ignore: ''             
        }

        if(options) {
            jQuery.extend(settings, options);
        };

        this.not(settings.ignore).each(function(){
            var input = $(this).next('input, textarea');
            var label = $(this);
        
            // first check all inputs for values, then hide it's label if it has a value
            if( settings.overlap ) {
                label.addClass('overlap');
            }
        
            if( settings.overlap && input.val() != '' ) {
                label.hide();
            }
        
            label.click(function(){
                label.hide();
                input.focus();
            }, function(){
                if( input.val() == '' ) {
                    label.show();
                }
            });
        
            // then add a focus event to all inputs to hide their labels when focused on, 
            // and remain hidden on blur if a value is entered
            input.focus(function(){
                label.hide();
            }).blur(function(){
                if( $(this).val() == '' ) {
                    label.show();
                }
            });
        });
    };

	displayFacebookCommentString = function(itemId, targetId) {
		$.ajax({
			type: "POST",
			contentType: "application/json; charset=utf-8",
			url: "/sitecore%20modules/FacebookFieldType/ContentDelivery.aspx/GetFacebookComments",
			data: "{'itemId': '" + itemId + "', 'getFromCacheOnly':false}",
			dataType: "json",
			success: function (msg) {
				$(targetId).text(msg.d);
			}
		});
	};
})(jQuery);









