﻿var curdate = new Date();
var seconds = curdate.getTime();
//Checks if a div exists
function checkForDiv(id) {
    var div = document.getElementById(id);
    if (div) {return true; } else {return false; }
}
jQuery(document).ready(function() {
    //Hide Restart dialog message
    jQuery('#dialogRestartProgram').hide();
    //Account/Profile Buddy dialog
    jQuery('#dialogBuddyProfile').hide();

    jQuery('#lnkBuddyProfile').click(function() {
        jQuery('#dialogBuddyProfile').dialog("open");
        jQuery('#dialogBuddyProfile').dialog({ bgiframe: true, resizable: false, closeOnEscape: true,
            height: 180, modal: true, buttons: {
                'Yes': function() {
                    window.location = "/members/community/buddies/my-profile.aspx";
                },
                'No': function() {
                    jQuery(this).dialog('close');
                }
            }
        });
    });

    //Intro Profile
    var $healthInfo = jQuery('#healthyWeightRangeMsgIntro');
    var $closeMsgTop = jQuery('#learnHealthyWeightLnkClose');
    var $closeMsgBottom = jQuery('#closeChart');
    var $openMsg = jQuery('#learnHealthyWeightLnkOpen');

    $openMsg.click(function() {
        $healthInfo.slideToggle("slow");
        jQuery(this).toggle();
        $closeMsgTop.toggle();
        return false;
    });

    $closeMsgBottom.click(function() {
        $closeMsgTop.toggle();
        closePanal();
    });

    $closeMsgTop.click(function() {
        jQuery(this).toggle();
        closePanal();
    });

    function closePanal() {
        $healthInfo.slideToggle("slow");
        $openMsg.toggle();
        return false;
    }


    //Load side module for "In the Community"
    if (checkForDiv("buddiesSideModule")) {
        jQuery.ajax({
            url: "/members/community/buddies/buddiesSideModulePage.aspx",
            cache: false,
            success: function(html) {
                jQuery('#buddiesSideModule').append(html);
            },
            dataType: "html",
            global: false,
            type: "PUT",
            error: function() { jQuery("#buddiesSideModule").hide(); }

        });
    }
});


function btnRestart_ClientClick() {
    var ans = confirm("Are you sure you want to restart?\nOnce you click \"Yes,\" this can't be undone.");
    if (ans) {
        return true;
    } else {
    return false;
    }
}

function largerImage() {
    var $largerImage = jQuery('#largerImage');

    //Add collapse/expand link after the smaller image
    jQuery('.ct_article_imageDIV img').after('<div id="expandColapseLinks" class="smlTxt"><center><div style="cursor:pointer; text-decoration:underline;" id="enlargeImg">click to expand</div><div style="cursor:pointer; text-decoration:underline;" id="enlargeImgClose">click to close</div></center></div>');
    jQuery('#enlargeImgClose').toggle();

    //The XSLT template needs to have a defined place for the image.
    //By cloning it, the div can be moved anywhere
    var $copyOfLargerDiv = $largerImage.clone();

    //Get the HTML from the clone
    var viewLargerImage = $copyOfLargerDiv.html();

    //Put the element after the first paragraph into a variable
    jQuery('#body_content p:eq(0)').append('<div id="viewImg" style="text-align:center;display:none;">' + viewLargerImage + '</div>');

    jQuery('#enlargeImg').click(function() {
        //Show/hide expand/collapse links
        jQuery('#viewImg').slideDown("slow");
        jQuery('#enlargeImgClose').toggle();
        jQuery('#enlargeImg').toggle();
        return false;
    });

    //Close function
    function closeLargerImage() {
        jQuery('#enlargeImgClose').toggle();
        jQuery('#enlargeImg').toggle();
        jQuery('#viewImg').slideUp("slow");
    }
    //Link under the small image
    jQuery('#enlargeImgClose').click(function() { closeLargerImage(); return false; });

    //If it's in a pop up window, hide the expand link
    if (checkForDiv("popContent")) { jQuery('#expandColapseLinks').hide(); return false; }


}

function isIE6Challenge() {
    if (/msie|MSIE 6/.test(navigator.userAgent)) {
        jQuery('#topContent').css({ 'margin-right': '-280px', 'margin-left': '-10px' });
    }
}

function summerChallenge09() {
    var topBanner = "<a href=\"http://ad.doubleclick.net/jump/jillianmichaels/challenge;tile=4;sz=760x100;' + utp + 'ord=[" + seconds + "]?\" target=\"_blank\"><img src=\"http://ad.doubleclick.net/ad/jillianmichaels/challenge;tile=4;sz=760x100;' + utp + ';ord=[" + seconds + "]?\" width=\"760\" height=\"100\" border=\"0\" alt=\"\"></a><br /><br />";
    jQuery('#summerChallengeTopBanner').html(topBanner);

    var sponsorLogoImage = "<a href=\"http://ad.doubleclick.net/jump/jillianmichaels/challenge;tile=5;sz=110x39;' + utp + 'ord=[" + seconds + "]?\" target=\"_blank\"><img src=\"http://ad.doubleclick.net/ad/jillianmichaels/challenge;tile=5;sz=110x39;' + utp + ';ord=[" + seconds + "]?\" width=\"110\" height=\"39\" border=\"0\" alt=\"\"></a>";
    jQuery('#sponsorLogo').html(sponsorLogoImage);
    jQuery('#sponsorLogo img').css("border", "none");

    isIE6Challenge();
}

function fallChallenge09() {
    var topBanner = '<img src="http://images.agoramedia.com/jillianmichaels/fallChallenge2009/fall-challenge-2009-banner.gif" alt="Give Me 20! - Jillian\'s Fall Challenge"/><br/><br/>';

    var bannerDiv = jQuery('#fallChallengeTopBanner');
    bannerDiv.html(topBanner);
    jQuery('#ct_article_introcopy p').css({ 'color': '#F26522' });

    jQuery('#side_modules_container .right_mod_title').eq(0).removeClass().addClass('right_mod_title_Red');
    //.css({"border" : "2px solid red"});


    isIE6Challenge();
}

function losingitChallenge10() {
    var topBanner = '<img src="http://images.agoramedia.com/jillianmichaels/cms/Losing_It_Challenge_Banner_760x120_v2.jpg" alt="Losing It! - Jillian\'s Fall Challenge"/><br/>';

    var bannerDiv = jQuery('#LosingItChallengeTopBanner');
    bannerDiv.html(topBanner);
    jQuery('#ct_article_introcopy p').css({ 'color': '#F26522' });

    jQuery('#side_modules_container .right_mod_title').eq(0).removeClass().addClass('right_mod_title_Red');
    //.css({"border" : "2px solid red"});


    isIE6Challenge();
}

function newYearChallenge10() {
    var topBanner = '<img src="http://images.agoramedia.com/jillianmichaels/cms/challenge_newyears_09_banner_lrg.jpg" alt="Master Your Kitchen - Jillian\'s 2010 New Year Challenge"/><br/><br/>';

    var bannerDiv = jQuery('#newYearChallenge2010TopBanner');
    bannerDiv.html(topBanner);

    jQuery('#side_modules_container .right_mod_title').eq(0).removeClass().addClass('right_mod_title_Red');
    isIE6Challenge();
}

function questionsAccordion() {
    jQuery("#submission_accordion").accordion({
        autoHeight: false, collapsible: false, active: false
    });
    jQuery("#uploadVid").wrapAll("<div class=\"myWrapper\"></div>");
}

function RecipeSearch() {
    jQuery("input[id$=txtRecipeSearch]").keypress(function(e) {
        if (e.which == 13) {
            goRecipeSearch();
            e.returnValue = true;
            e.cancel = true;
            return false;
        }
    });
}

function NutritionSearch() {
    jQuery("input[id$=txtNutritionSearch]").keypress(function(e) {
        if (e.which == 13) {
            goNutritionSearch();
            e.returnValue = true;
            e.cancel = true;
            return false;
        }
    });
}



//Adapted from: http://blog.themeforest.net/tutorials/creating-a-jquery-word-counter/
//This works by applying a class called "count" to an element by passing 1 or 2 arguments within brackets [ ] seperated by a comma.
//Example: 
//class="count[50]"     Maximum
//class="count[50,100]" Minimum & Maximum
//class="count[50,0]"   Minimum
function wordCount() {
    jQuery('#essayError').hide().css("color", "red");
    //Find each element who's class starts with "count" (and apply the function to EACH)
    jQuery("[class^='count[']").each(function() {
        var the_class = jQuery(this).attr('class');
        var minWords = 0;
        var maxWords = 0;
        var wordMsg;
        var $essayErrorMsg = jQuery('#essayError');
        var $btnSubmit = jQuery('input[id$=btnSubmit]');

        //Gets the values in between the brackets that are seperated (split) by a comma
        var countControl = the_class.substring((the_class.indexOf('[')) + 1, the_class.lastIndexOf(']')).split(',');


        if (countControl.length > 1) {
            minWords = countControl[0]; //Gets the FIRST value from the bracket array
            maxWords = countControl[1]; //Gets the SECOND value from the bracket array
        } else {
            maxWords = countControl[0];
        }

        wordMsg = maxWords;

        //AFTER the input box, insert a div with a class of "wordCount" and content of "0 Words"
        jQuery(this).after('<div class="wordCount"><b>0</b> words of ' + wordMsg + '</div>');

        //If you have a minimum number of words required, then add an "error" class to inform the user
        if (minWords > 0) {
            jQuery(this).siblings('.wordCount');
        }

        //Whatever action the user does to get the words in the input, capture it by binding several events
        jQuery(this).bind('keyup click blur focus change paste', function() {

            //The word count relies on the space between chracters; this variable counts everything outside of spaces
            var numWords = jQuery.trim(jQuery(this).val()).replace(/\s+/g, " ").split(' ').length;

            //If the user didn't type anything in yet, then set the count to 0
            if (jQuery(this).val() === '') {
                numWords = 0;
            }

            //This replaces the characters in the div that was inserted earlier.
            //Its being found by the '.wordCount' class. Then, it looks inside whatever is in
            //that div and looks for the 'b' tag. It then replaces whats in the 'b' tag with
            //the current number of words.
            jQuery(this).siblings('.wordCount').children('b').text(numWords);

            //Once the user reaches the min/max number of words, it adds the error class
            //to visually indicate to the user that they went over.

            if (numWords < minWords || (numWords > maxWords && maxWords !== 0)) {

                //The user has committed an error. Its time for punishment
                jQuery(this).siblings('.wordCount').addClass("redText");
                               

            } else {

                //The user can now submit the form.
                jQuery(this).siblings('.wordCount').removeClass("redText");
   
            }

            if (jQuery('.wordCount').hasClass("redText")) {
                $essayErrorMsg.show();
                $btnSubmit.hide(); 
            } else { 
                $essayErrorMsg.hide();
                $btnSubmit.show();
            }


        });


    });
}

jQuery(function() {
//Click to enlarge
if (checkForDiv("largerImage")) { largerImage(); }
if (checkForDiv("summerChallengeTopBanner")) { summerChallenge09(); }
if (checkForDiv("fallChallengeTopBanner")) { fallChallenge09(); }
if (checkForDiv("LosingItChallengeTopBanner")) { losingitChallenge10(); }

if (checkForDiv("newYearChallenge2010TopBanner")) { newYearChallenge10(); }

if (checkForDiv("submission_accordion")) { questionsAccordion(); }
if (checkForDiv("submitEssay") || checkForDiv("challengeEntryForm")) {
    wordCount();
    //Focus on the input box
    jQuery('textarea[id$=txtUserSubmission]').focus();
    
}
});

$(window).ready(function($) {
    $(".iab").mouseover(function() {
        $(".iabnotice").addClass('iabnoticeshow').fadeIn("slow");

    });
    $(".iabnotice .close").click(function() {
        $(".iabnotice").fadeOut("slow");
    });
});
