
var maleVideoEmbed = '';
var femaleVideoEmbed = '';
var bookmarkURL = getBaseURLExercises() + '/finder';
var bookmarkTitle = '';
var setTimeOutID = null;
var orderByField = 'exerciseName';
var orderByDirection = 'ASC';

/**
 * "Constant" for exercises base URL.
 */
function getBaseURLExercises()
{
    return 'http://www.bodybuilding.com/exercises';
}
function getBaseURLAdminExercises()
{
    return 'http://admin/exercises';
}

/**
 * "Constant" for videos base URL.
 */
function getBaseURLVideos()
{
    return 'http://videos.bodybuilding.com';
}

/**
 * This function finds all the divs with the given name
 * and switches their display protery from block to none
 * or from none to block.
 *
 * This functin should not be called directly.  Call ToggleSexes
 * instead.
 */
function ToggleGenderDivs(sex, visible)
{
    var divs = new Array();

    divs = document.getElementsByTagName('div');

    for (var i=0; i<divs.length;i++)
    {
        if (divs[i].id == sex)
        {
            var div = divs[i];
            div.style.display = visible ? 'block' : 'none';
        }
    }
}

/**
 * Called by the html to toggle the images/videos shown from
 * male to female or from female to male.
 */
function ToggleGender(gender)
{
    var malediv = document.getElementById('maleVideo');
    var femalediv = document.getElementById('femaleVideo');

    if (maleVideoEmbed.length == 0)
    {
        maleVideoEmbed = malediv.innerHTML;
    }

    if (femaleVideoEmbed.length == 0)
    {
        femaleVideoEmbed = femalediv.innerHTML;
    }

    malediv.innerHTML = '';
    femalediv.innerHTML = '';

    ToggleGenderDivs('Male', gender == 'Male');
    ToggleGenderDivs('Female',  gender == 'Female');

    if (gender == 'Female')
    {
        femalediv.innerHTML = femaleVideoEmbed;
    }
    else
    {
        malediv.innerHTML = maleVideoEmbed;
    }
}


/**
 * Show preview of embedded video
 *
 * @param integer videoNum (video number)
 * @param string div (div tag to show embed preview)
 */
function showEmbedPreview(videoNum, div, width, height)
{
    if (width == undefined) { width = 150; }
    if (height == undefined) { height = 110; }
    if (videoNum > 0)
    {
        $.ajax({
            type: 'POST',
            url: 'http://admin/exercises/ajax/checkvalidvideo',
            data: 'videoNum=' + videoNum,
            async: false,
            success: function(validVideo)
                            {
                                if (validVideo == 1)
                                    {
                                     var embedCode = createEmbedCode(videoNum, 'simple', width, height);
                                     document.getElementById(div).innerHTML = embedCode;
                                     /**
                                     changeSubmitButtonState()
                                     */
                                    }
                                else
                                    {
                                      html = '<div style="color:red;text-align:center;">Not a Valid Video<div style="width:150px;height:110px;"></div></div>';
                                      document.getElementById(div).innerHTML = html;
                                      /**
                                      document.mainForm.submit.disabled = true;
                                      */
                                      alert("Video " + videoNum + " is not a valid ID");
                                    }
                            }
             });
    }
    else
    {
        html = '<div style="color:red;text-align:center;"> No Video Selected <div style="width:150px;height:110px;"></div></div>';
        document.getElementById(div).innerHTML = html;
    }
}

/**
 * Create embedded video code
 *
 * @param integer videoNum (video number)
 * @param string player (the player to use - simple, advanced, etc)
 * @param integer width (the widht of the video)
 * @param integer height (the height of the video)
 */
function createEmbedCode(videoNum, player, width, height)
{
    //If a player type isn't set - then use simple
    if (player == '') { player = 'simple'; }
    if (width == '') { width = 300; }
    if (height == '') { height = 220; }

    //Create the subfolder to find the video and thumb
    var subFolder = (Math.floor(videoNum / 2000) * 2) + '000';
    //Create the embed code for the simple player
    if (player == 'simple')
    {
        var embedCode = '<embed src="' + getBaseURLVideos() + '/player.swf" ' +
                        'width="' + width + '" height="' + height + '" allowscriptaccess="always" allowfullscreen="true" ' +
                        'flashvars="height=' + height + '&width=' + width + '&file=' + getBaseURLVideos() + '/flvideo/flv/' + subFolder + '/' +
                        videoNum +
                        '.flv&image=' + getBaseURLVideos() + '/thumb/' + subFolder + '/' +
                        videoNum +
                        '.jpg&displayheight=' + height + '&searchbar=false" pluginspage="http://www.macromedia.com/go/getflashplayer" ' +
                        'type="application/x-shockwave-flash" />';
    }
    return(embedCode);
}


/**
 *change submit button state for exercise admin details page
 *
 */
    function changeSubmitButtonState()
    {
        if ( adminValidateSubmitButtonState() == false)
            document.mainForm.submit.disabled = true;
        else
            document.mainForm.submit.disabled = false;
    }

/**
 *Validate the information needed to save an exercise in exercise admin details page
 *
 */
    function adminValidateSubmitButtonState()
    {
        var active = true;

        if (document.mainForm.summary.value.length == 0)
            {
               active = false;
            }
/*       This wil prabbly be reused later.
         if(active == true)
            {                
                var video=new Array();
                video[0] = document.mainForm.maleLongVideo.value;
                video[1] = document.mainForm.maleShortVideo.value;
                video[2] = document.mainForm.femaleLongVideo.value;
                video[3] = document.mainForm.femaleShortVideo.value;
                for(i=0;i<=3;i++)
                {
                   if (video[i] > 0)
                       {
                        $.ajax({
                            type: 'POST',
                            url: 'http://admin/exercises/ajax/checkvalidvideo',
                            data: 'videoNum=' + video[i],
                            async: false,
                            success: function(validVideo)
                                {
                                     if (validVideo == 0)
                                                {
                                                   active = false;
                                                 }
                                }
                             });                                   
                        if(active == false)
                                 {
                                     alert("Video " + video[i] + " is not a valid ID");
                                     break;
                                 }
                        }

            }
           }
*/
        return active;

    }



/**
 * Reload the original content of a div. This is a work around to get the embedded
 * video to stop playing. Just put the embed code into a div - then, call this
 * fucntion when you need the video to be stopped or reloaded.
 *
 * @param integer div (div of content to be reloaded)
 */
function reloadDiv(div)
{
    var originalHTML = document.getElementById(div).innerHTML;
    document.getElementById(div).innerHTML = '';
    document.getElementById(div).innerHTML = originalHTML;
}

/**
 * Enable or disable certain boxes when the exercise id is changed
 *
 * @param integer exerciseType
 */
function disableChoices(exerciseType)
{
    //Enable all boxes
    document.getElementById('sport').disabled         = false;
    document.getElementById('exerciseForce').disabled = false;
    document.getElementById('stretchType').disabled   = false;
    document.getElementById('location').disabled      = false;

    //Disable boxes related to Cardio
    if (exerciseType == 1)
    {
        document.getElementById('stretchType').disabled   = true;
        document.getElementById('location').disabled      = true;
    }

    //Disable boxes related to Isometric
    if (exerciseType == 2)
    {
        document.getElementById('stretchType').disabled   = true;
    }

    //Disable boxes related to Plyometrics
    if (exerciseType == 3)
    {
        document.getElementById('location').disabled      = true;
    }

    //Disable boxes related to Stretching
    if (exerciseType == 4)
    {
        document.getElementById('stretchType').disabled   = true;
    }
}

/**
 *
 * This method is used by the Exercise Lookup in the Exercise Admin app.
 * It is used to control adding/editing lookup values.
 *
 */
function lookupSelectOnChange(select)
{
    var sel = document.getElementById(select);
//    var val = document.getElementById(select).value;
    var txt = sel.options[sel.selectedIndex].text;
    var objName = select.substring(0,select.indexOf('Select',0));
    var txtName = '';
    var checked = false;

    if (txt.indexOf('(active)',0) != -1)
    {
        txtName = txt.substring(0,txt.indexOf('(active)',0)-1);
        checked = true;
    }
    else
    {
        txtName = txt.substring(0,txt.indexOf('(inactive)',0)-1);
        checked = false;
    }
    document.getElementById(objName+'Check').checked = checked;
    document.getElementById(objName+'Text').value = txtName;
}

/**
 * This method will call the updatedUserRating.php file to update
 * a users rating for a specific rating.
 */
function ratingRadioButtonClick(userID, exerciseID, rating)
{
    var label = document.getElementById('ratingfeedbacklabel');
    label.style.display = 'inline';
    $('#ratingfeedbacklabel').hide().fadeIn(2000).fadeOut(2000);

    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/',
        data: 'ajax=UpdateUserRating&uid=' + userID + '&eid=' + exerciseID + '&r=' + rating,
        success: updateRatingsOnPage(rating, exerciseID)
    });
}

/**
 * This method is used called by ratingRadioButtonClick and calls two ajax
 * methods which will update rating widgets on the Exercise Detail page.
 */
function updateRatingsOnPage(rating,exerciseID)
{
    updateExerciseSmallRating(rating);
    updateExerciseLargeRating(exerciseID);
}

/**
 * This method will update the two small rating widgets on the exerciseDetail page.
 */
function updateExerciseSmallRating(rating)
{
    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/',
        data: 'ajax=CreateRatingWidget&size=small&r=' + rating,
        success: function(html) {
            $('#feedbacksmalllabel').html('Your rating of this exercise:&nbsp;')
            $('#feedbacksmallrating').html(html);
            $('#headersmallrating').html(html);
        },
        async: false
    });
}

/**
 * This method will update the large rating widget.  This is currently used
 * on the Exercise Detail page.
 */
function updateExerciseLargeRating(exerciseID)
{
    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/',
        data: 'ajax=CreateRatingWidget&size=large&eid=' + exerciseID,
        success: function(html) {
            $('#largeratingwidget').html(html);
        }
    });
}

function updateRatingOnLoad(userID,exerciseID)
{
    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/',
        data: 'ajax=GetUserRating&uid=' + userID + '&eid=' + exerciseID,
        success: function(rating) {
            if ((userID != 0) && (rating != 0))
            {
                updateExerciseSmallRating(rating);
            }
        }
    });

}

/**
 * This method is used to validate the selections in the Tips & Reviews
 * feedback section.
 */
function validateFeedback(userID, exerciseID)
{
    var cbReview = document.getElementById('feedbacktypereview').checked;
    var cbTip = document.getElementById('feedbacktypetip').checked;
    var fbText = document.getElementById('feedbacktext').value;
    var rbRating = document.getElementsByName('rating');
    var error = true;
    var feedbackType = '';

    if (cbReview)
    {
        feedbackType = 'Review';
    }
    if (cbTip)
    {
        feedbackType = 'Tip';
    }

    for (var i=0;i<rbRating.length; i++)
    {

        if (rbRating.item(i).checked == true)
        {
            error = false;
        }
    }

    if (error == true)
    {
        alert('Please rate this exercise before Submitting a Review or Tip.');
    }

    if (error == false)
    {
        if (fbText.length == 0)
        {
            alert('Please enter a Review or Tip before posting.');
            error = true;
        }
        else if ((cbReview == false) && (cbTip == false))
        {
            alert('Please select either Tip or Review as the comment type.');
            error = true;
        }
    }

    if (error == false)
    {
        $.ajax({
            type: 'POST',
            url: getBaseURLExercises() + '/',
            data: 'ajax=FilterFeedback&feedback=' + fbText,
            success: function(filtered) {
                fbText = filtered;
                postFeedback(userID, exerciseID, fbText, feedbackType);
            }
        });
    }
}

/**
 * This method is called by validateFeedback and is used to post
 * feedback on an exercise.
 */
function postFeedback(userID, exerciseID, feedback, feedbackType)
{
    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/',
        data: 'ajax=PostFeedback&uid=' + userID + '&eid=' + exerciseID + '&fb=' + feedback + '&type=' + feedbackType,
        success: function(feedbackID) {
            getFeedbackItem(feedbackID, feedbackType);
        }
    });
}

/**
 * Method called from postFeedback and returns feedbackItem for a geiven feedbackID.
 */
function getFeedbackItem(feedbackID, feedbackType)
{
    if (feedbackID != -1)
    {
        $.ajax({
            type: 'POST',
            url: getBaseURLExercises() + '/',
            data: 'ajax=GetFeedbackItem&feedID=' + feedbackID,
            success: function(data) {
                RemoveDefaultTipReviewMessage(feedbackType);
                displayFeedbackItem(data, feedbackType);
            }
        });
    }
    else
    {
        alert("Please wait at least 30 seconds before submitting another review or tip.");
    }
}

/**
 * This method will update the All tab in the exercise detail page.  As well
 * as adding the comment to the other appropriate tab (Review or Tip)
 */
function displayFeedbackItem(feedbackData, feedbackType)
{
    var altDiv = '';
    var allDiv = document.getElementById('allTabCommentDiv');
    var content = allDiv.innerHTML;
    var newContent = feedbackData + content;

    //  Update the All tab
    allDiv.innerHTML = newContent;

    if (feedbackType == 'Tip')
    {
        altDiv = document.getElementById('tipTabCommentDiv');
        newContent = feedbackData.replace('Tip:','');
    }
    else
    {
        altDiv = document.getElementById('reviewTabCommentDiv');
        newContent = feedbackData.replace('Review:','');
    }

    //  Update the Review/Tip tab
    content = altDiv.innerHTML;
    newContent = newContent + content;
    altDiv.innerHTML = newContent + content;

    //  Clear the comment from the textarea and switch to the all tab.
    $('#feedbacktext').val('');
    ToggleFeedbackTabs('allTab');
    $('#feedbackContainer').show();
}

/**
 * This method is call by the All/Review/Tips tabs on the detail page.
 * It will toggle the tabs on and off and call another method to
 * load/show the appropriate feedback items.
 */
function ToggleFeedbackTabs(id)
{
//  Hide all the active tabs.
    $('#allTabActive').hide();
    $('#reviewTabActive').hide();
    $('#tipTabActive').hide();

    //  Hide all the comment divs
    $('#allTabCommentDiv').hide();
    $('#reviewTabCommentDiv').hide();
    $('#tipTabCommentDiv').hide();

    //  Show all the Inactive Tabs
    $('#allTabInactive').show();
    $('#reviewTabInactive').show();
    $('#tipTabInactive').show();

    var activeTab = id + 'Active';
    var activeCommentDiv = id + 'CommentDiv';
    var inactiveTab = id + 'Inactive';

    $('#' + activeTab).show();
    $('#' + inactiveTab).hide();
    $('#' + activeCommentDiv).show();
}

/**
 * This method will remove the default message ask the user to write a Review/Tip
 * if there aren't any.  If the process gets to this point then either a Tip or
 * a Review was written.  We remove the All tabs message, if there is one and then
 * remove the tab specific message, if there is one.
 *
 */
function RemoveDefaultTipReviewMessage(feedbackType)
{
    var allDefault = document.getElementById('allDefault');
    var reviewDefault = document.getElementById('reviewDefault');
    var tipDefault = document.getElementById('tipDefault');

    if (allDefault != null)
    {
        allDefault.innerHTML = '';
    }

    if (feedbackType == 'Review')
    {
        if (reviewDefault != null)
        {
            reviewDefault.innerHTML = '';
        }
    }

    if (feedbackType == 'Tip')
    {
        if (tipDefault != null)
        {
            tipDefault.innerHTML = '';
        }
    }
}


/**
 * toggleMoreLessFeedback
 */
function toggleMoreLessFeedback(feedbackId, tabType)
{
    shortId = '#short' + feedbackId + tabType;
    longId = '#long' + feedbackId + tabType;

    $(shortId).toggle();
    $(longId).toggle();
}

function getSliderValues()
{
    var params = '';
    var min = $('#ratingRange_min').html();
    var max = $('#ratingRange_max').html();
    params = 'ratings='+min+','+max;
    return params;
}

/**
 * setSliderValues
 */
function setSliderValues(min, max) {
    $('#ratingSlider').slider('values', 0, min);
    $('#ratingSlider').slider('values', 1, max);
    $('#ratingRange_min').html(min);
    $('#ratingRange_max').html(max);
}

/**
 * This function will determine the name of the bookmark.  It needs to check the
 * first column of <TD>s so it's dividing the count by 2 and looking at the
 * remainder.  If the first column of checkboxes don't contain enough checkboxes
 * it then moves on to the second column of checkboxes.
 */
function getBookmarkTitle()
{
    var h = 0;
    var bookmarkText = '';
    bookmarkTitle = '';

    checkboxes = $("input[id*='filter_muscleID']");
    for (var j=0;j<2;j++)
    {
        if (h < 2)
        {
            for (var i=0;i<checkboxes.length;i++)
            {
                if ((i % 2) == j)
                {
                    if (checkboxes[i].checked == true)
                    {
                        if (h < 2)
                        {
                            var id = checkboxes[i].id;
                            var labelID = id.replace('filter_','label_');
                            var item = $('#' + labelID);
                            var label = item.html();

                            if (bookmarkText.length != 0)
                            {
                                bookmarkText = bookmarkText + '-' + label;
                            }
                            else
                            {
                                bookmarkText = label;
                            }
                            h = h + 1;
                        }
                    }
                }
            }
        }
    }
    //  Do some SEO to the name
    bookmarkText = bookmarkText.replace(" ","-");
    return bookmarkText;
}


/**
 * This function will create a parameter list of all the checkboxes
 * which are  checked.  This will be stored in the database and
 * assigned a bookmarkID.
 *
 * This method is called from the postBookmark method
 *
 */
function getAllCheckboxes()
{
    var params = '';
    var currentParam = '';
    var checkboxes = document.getElementById('Filters').getElementsByTagName('input');
    bookmarkTitle = '';
    var filterNames = new Array();

    for (var i = 0; i < checkboxes.length; i++)
    {
        if (checkboxes[i].type == 'checkbox')
        {
            var value = checkboxes[i].value;
            if (value == 'NA')
            {
                value = 'N/A';
            }
            var id = checkboxes[i].id;
            var name = id.substring( id.indexOf('_')+1, id.lastIndexOf('_')  );

            filterNames[i] = name;

            if (checkboxes[i].checked == true)
            {
                if (currentParam != name)
                {
                    currentParam = name;
                    if (params.length > 0)
                    {
                        params = params + ';';
                    }
                    params = params + currentParam + '=';
                }

                params = params + value + ',';
            }
        }
    }
    //  replace all instances of ',;' with ';'
    params = params.replace(/,;/g,';');

    //  remove the last ','
    params = params.substr(0,params.length-1);

    //  save off the title of the bookmark
    bookmarkTitle = getBookmarkTitle();

    for (var i=0;i<filterNames.length;i++)
    {
        var fName = filterNames[i];
        if (params.indexOf(fName) == -1)
        {
            params = params + ";" + fName + "=-1";
        }
    }

    return(params);
}

/**
 * This method is called by the bookmark button on the exercise-finder page.
 * It will call getAllCheckboxes to determine the parameter list to store,
 * store the params in the database and return the bookmarkID.
 */
function postBookmark()
{
    var params = getAllCheckboxes();
    /*  We aren't using the slider cuurently so this is commented out
    params += ';' + getSliderValues();
    */
   
    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/',
        data: 'ajax=PostBookmark&params=' + params,
        success: function(bookmarkID) {
            bookmarkURL = getBaseURLExercises() + '/finder/saved/id/' + bookmarkID + '/main-muscle/' + bookmarkTitle.toLowerCase();
            bookmarkTitle = 'Bodybuilding.com: Exercise Finder - ' + bookmarkTitle;
        },
        async: false
    });
}

function rateReview(feedbackID, userID, rating, feedbackType)
{
    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/',
        data: 'ajax=PostFeedbackRating&fbID=' + feedbackID + '&uID=' + userID + '&r=' + rating,
        success: function(bookmarkID) {
            updateFeedbackRatingLabel(feedbackID,rating, feedbackType);
            updateFeedbackRatingTotals(feedbackID,rating);
        },
        async: false
    });

}

function updateFeedbackRatingLabel(feedbackID, rating, feedbackType)
{
    var divAll = document.getElementById('feedbackRatingLabel' + feedbackID + 'all');
    var divReview = document.getElementById('feedbackRatingLabel' + feedbackID + 'review');
    var divTip = document.getElementById('feedbackRatingLabel' + feedbackID + 'tip');
    var text = 'You found this ' + feedbackType;

    if (rating == 0)
    {
        text = text + ' unhelpful.';
    }
    else
    {
        text = text + ' helpful.';
    }

    //  Update the ALL rating label
    if (divAll != null)
    {
        divAll.innerHTML = text;
    }

    //  Update the REVIEW rating label
    if (divReview != null)
    {
        divReview.innerHTML = text;
    }

    //  Update the TIP rating label
    if (divTip != null)
    {
        divTip.innerHTML = text;
    }
}


function updateFeedbackRatingTotals(feedbackID, rating, helpful, total)
{
    var helpfulAll = document.getElementById('helpful' + feedbackID + 'all');
    var helpfulReview = document.getElementById('helpful' + feedbackID + 'review');
    var helpfulTip = document.getElementById('helpful' + feedbackID + 'tip');

    var totalAll = document.getElementById('total' + feedbackID + 'all');
    var totalReview = document.getElementById('total' + feedbackID + 'review');
    var totalTip = document.getElementById('total' + feedbackID + 'tip');

    if (rating != -1)
    {
        //TODO: fix.
        //this is incompatible with the permalink view.
        var helpfulcount = helpfulAll.innerHTML;
        var totalcount = totalAll.innerHTML;

        //  multiple by 1 to make sure javascript treats these values as integers not strings
        helpfulcount *= 1;
        totalcount *= 1;
        totalcount++;

        if (rating == 1)
        {
            helpfulcount = helpfulcount + 1;
        }
    }

    if (rating == -1)
    {
        helpfulcount = helpful;
        totalcount = total;
    }

    //  update the ALL tab
    if (helpfulAll != null)
    {
        helpfulAll.innerHTML = helpfulcount;
        totalAll.innerHTML = totalcount;
    }

    //  update the REVIEW tab
    if (helpfulReview != null)
    {
        helpfulReview.innerHTML = helpfulcount;
        totalReview.innerHTML = totalcount;
    }

    //  update the TIP tab
    if (helpfulTip != null)
    {
        helpfulTip.innerHTML = helpfulcount;
        totalTip.innerHTML = totalcount;
    }
}

function chart(id, data) {
    var chartDiv = $('#thebbstatchart');

    $.ajax({
	 type: "GET",
	 url: "http://www.bodybuilding.com/exercises/chart/index/id/" + id + "/data/" + data,
	 success: function (msg){
	     chartDiv.html(msg);
	     anchor = $('#thebbstatchart a');
	     anchor.click( function() {showSWFPanel(this); return false;})
	     anchor.click();
	 }
    });
}

function initBWT() {
    if (typeof(initStats) == 'function') initStats();
}


function UpdateFeedbackRatings()
{
   getAllFeedbackRatings('review');
   getAllFeedbackRatings('tip');
}

function getAllFeedbackRatings(type)
{
    var feedbackIDs = '';
    //  Get all the feedback items in the REVIEW tab
    var reviews = document.getElementById(type + 'TabCommentDiv').getElementsByTagName('label');
    var count = reviews.length / 2;
    for (var i = 0; i < reviews.length; i++)
    {
        var id = reviews[i].id;
        if (id.indexOf('helpful') == 0)
        {
            var reviewStart = id.indexOf(type);
            var feedbackID = id.substring(7,reviewStart);
            feedbackIDs = feedbackIDs + feedbackID + ','
        }
    }

    feedbackIDs = feedbackIDs.substring(0,feedbackIDs.length-1);

    // Get a JSON of the feedbackItems ratings and update the screen
    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/',
        data: 'ajax=GetFeedbackRating&opt=FeedbackRating&fbIDs=' + feedbackIDs,
        dataType: "json",
        success: function(data) {
            for (i=0;i<count;i++)
            {
                var feedbackID = data[i].feedbackID;
                var helpful = data[i].positiveRatings;
                var total = data[i].totalRatings;

                updateFeedbackRatingTotals(feedbackID,-1,helpful,total);
            }
        },
        async: false
    });

    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/',
        data: 'ajax=GetFeedbackRating&opt=FeedbackLabel&fbIDs=' + feedbackIDs,
        dataType: "json",
        success: function(data) {
            for (i=0;i<data.length;i++)
            {
                var feedbackID = data[i].feedbackID;
                var rating = data[i].helpful;
                var feedbackType = data[i].feedbackType

                updateFeedbackRatingLabel(feedbackID,rating,feedbackType);
            }
        },
        async: false
    });
}

function setFeedbackItemInactive(feedbackType, feedbackItemID, exerciseID, userID) {

   if (confirm("Are you sure you want to delete this " + feedbackType + "?")) {
        $.ajax({
             type: "POST",
             url: getBaseURLExercises() + '/',
             data: "ajax=RemoveFeedbackItem&type=" + feedbackType + 
                 "&id=" + feedbackItemID +
                 "&exercise_id=" + exerciseID +
                 "&user_id=" + userID,
             success: removeItem
        });
    }

    function removeItem(data) {
        if (data == -1)
            alert("There was problem removing this " . feedbackType);
        else {
            // remove the feedback item from the page
            $("div[id^='commentContent" + feedbackItemID + "']").remove();
            $("div[id^='greySeperator" + feedbackItemID + "']").remove();
        }
    }
}

/**
* Based on the paramName and paramValues passed in the finder
* will check/uncheck the checkbox.  It's assumed that the values
* in the paramValues are those checkboxes which need to be checked.
*/
function updateFinderCheckbox(paramName, paramValues)
{
    checkboxes = $("input[id*='filter_" + paramName + "_']");

    //set all checkboxes within the specified filter to unchecked
    $(checkboxes).attr("checked", false);

    //run through and only check the ones that are inside the paramValues array
    for(i = 0; i < paramValues.length; i++) {
        $(checkboxes).filter("[value=" + paramValues[i] + "]").attr("checked", true);
    }
}

/**
 * This method will taken the bookmarkID passed into it, get the params from
 * the database and then pass those results to the updateFinderCheckbox method.
 */
function updateFinderFromBookmark(bookmarkID)
{
    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/',
        data: 'ajax=GetBookmark&bookmarkID=' + bookmarkID,
        success: function(data) {
            var mainArray = data.split(";");
            for (var i=0;i<mainArray.length;i++)
            {
                var paramName = mainArray[i].substring(0,mainArray[i].indexOf("="));
                var paramValues = mainArray[i].substring(mainArray[i].indexOf("=")+1, mainArray[i].length);
                paramValues = paramValues.split(",");
                if (paramName == 'ratings') 
                {
                    /*  We aren't currently using the slider so this line is commented out
                    setSliderValues(paramValues[0],paramValues[1]);
                    */
                }
                updateFinderCheckbox(paramName,paramValues);
            }
        },
        async: false
    });
}

/**
 * This method will taken the filter and chebox ID passed into it, get the params from
 * the database and then pass those results to the updateFinderCheckbox method.
 */
function updateFinderFromSingleFilter(filterName, checkboxID)
{
    var ids = [checkboxID];
    updateFinderCheckbox(filterName, ids);
}


/**
 * This method will filter comments and pass on the comment to an ajax posting
 * method.
 */
function validateComment(userID, exerciseID, feedbackID)
{
    var fbText = document.getElementById('feedbacktext').value;
    var error = false;
    var feedbackType = 'Comment';

    if (fbText.length == 0)
    {
        alert('Please enter a Comment before posting.');
        error = true;
    }

    if (error == false)
    {
        $.ajax({
            type: 'POST',
            url: getBaseURLExercises() + '/',
            data: 'ajax=FilterFeedback&feedback=' + fbText,
            success: function(filtered) {
                fbText = filtered;
                postComment(userID, exerciseID, fbText, feedbackType, feedbackID);
            }
        });
    }
}

/**
 * This method will post the comment and return the feedbackID of the comment.
 */
function postComment(userID, exerciseID, feedback, feedbackType, feedbackID)
{
    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/',
        data: 'ajax=PostComment&uid=' + userID + '&eid=' + exerciseID + '&fb=' + feedback + '&type=' + feedbackType + '&fbID=' + feedbackID,
        success: function(feedbackID) {

            var pager = document.getElementById('pager');
            if (pager != null)
            {
                if (typeof pagerCurrentPage != 'undefined')
                {
                    pageNumber = (pagerCurrentPage * 1);
                    if (pageNumber > 1)
                    {
                        window.location = pagerIndexPage;
                    }
                    else
                    {
                        getCommentItem(feedbackID, feedbackType);
                    }
                }
            }
            else
            {
                getCommentItem(feedbackID, feedbackType);
            }
        }
    });
}

/**
 *  This method will get the "data" for the comment.  Or tell the user they
 *  have to wait 30 seconds before posting again.
 */
function getCommentItem(feedbackID, feedbackType)
{
    if (feedbackID != -1)
    {
        $.ajax({
            type: 'POST',
            url: getBaseURLExercises() + '/',
            data: 'ajax=GetFeedbackItem&feedID=' + feedbackID,
            success: function(data) {
                displayCommentItem(data);
            }
        });
    }
    else
    {
        alert("Please wait at least 30 seconds before submitting another comment.");
    }
}

/**
 * This method will update the All tab in the exercise detail page.  As well
 * as adding the comment to the other appropriate tab (Review or Tip)
 */
function displayCommentItem(feedbackData)
{
    var counter = document.getElementById('commentCounter');
    var count = counter.innerHTML;
    count = (count * 1) + 1;
    counter.innerHTML = count;

    var div = document.getElementById('commentsContainer');
    var content = div.innerHTML;
    var newContent = feedbackData + content;

    div.innerHTML = newContent;

    //  Clear the comment from the textarea and switch to the all tab.
    $('#feedbacktext').val('');

    // get the comments count description right next to the comments count
    commentsDesc = $('#commentDesc').text();

    if (count == 1)
    {
        // if the comments count is one then remove the s in "Comments "
        commentsDesc = commentsDesc.replace(/Comments /, "Comment ");
    }
    else
    {
        // # comments is <> 1, add the s in "Comment "
        commentsDesc = commentsDesc.replace(/Comment /, "Comments ");
    }

    // rebuild the comments description
    $('#commentDesc').text(commentsDesc);
}

/**
 * This method will change the checked state on a finder checkbox when the
 * associated label is pressed.
 */
function finderLabelOnClick(id)
{
    $('#' + id).attr('checked',!$('#' + id).attr('checked'));
    finderFiltersChanged(true);
}


function finderFiltersChanged(resetPager)
{
    showLoadingIcon();

    if (resetPager === undefined)
    {
        resetPager = false;
    }
    clearTimeout(setTimeOutID);
    setTimeOutID = setTimeout(function(){refreshFinderResultSet(resetPager);}, 350);
}

function showLoadingIcon()
{
    var innerHeight;

    // get reference to the loading icon
    var loadingIcon = $("#loadingIcon");
    var maskDiv = $("#maskDiv");

    // set default top, left and view top coordinate values
    var left = 400;
    var top = 400;
    var viewTop = 0;

    // get the current position of the finder results div
    var finderResults = $('#finderResults');
    var resultsTop = finderResults.offset().top;
    var resultsLeft = finderResults.offset().left;
    var resultsWidth = finderResults.width();
    var resultsHeight = finderResults.height();
    var resultsBottom = resultsTop * 1 + resultsHeight * 1;

    // get the loading icon image height and width
    var imageWidth = loadingIcon.width();
    var imageHeight = loadingIcon.height();

    // get the top coordinate of the user's view
    if(document.body && document.body.scrollTop) {
        // DOM compliant
        viewTop = document.body.scrollTop;   
    } else if(document.documentElement && document.documentElement.scrollTop) {
        viewTop = document.documentElement.scrollTop;
    }

    // get the innerHeight of the user's window, depending on browser
    if (window.innerHeight) {
        innerHeight = window.innerHeight * 1;
    } else if (document.documentElement.clientHeight) {
        innerHeight = document.documentElement.clientHeight * 1;
    } else if (document.body.clientWidth) {
        innerHeight = document.body.clientHeight;
    }

    // get the bottom coordinate of the user's view'
    var viewBottom = viewTop * 1 + innerHeight * 1;

    // figure out the top coordinate for the loading icon, based on where the
    // user's current view is'
    if ((viewTop < resultsTop) && (viewBottom > resultsTop))
        top = resultsTop + (viewBottom - resultsTop)/2 - imageHeight/2;
    else if ((viewTop >= resultsTop) && (viewBottom <= resultsBottom))
        top = viewTop + (viewBottom - viewTop)/2 - imageHeight/2;
    else if ((viewTop < resultsBottom) && (viewBottom > resultsBottom))
        top = resultsBottom - (resultsBottom - viewTop)/2 - imageHeight/2;

    // calculate the left coordinate for the loading icon
    left = resultsLeft + resultsWidth/2 - imageWidth/2;

    // create mask
    maskDiv.css("z-index", 99);
    maskDiv.css("position", "absolute");
    maskDiv.css("top", resultsTop + "px");
    maskDiv.css("left", resultsLeft + "px");
    maskDiv.css("width", (resultsWidth + 1) + "px");
    maskDiv.css("height", (resultsHeight + 1) + "px");
    maskDiv.css("background-color", "black");
    maskDiv.css("filter", "alpha(opacity=50)");
	maskDiv.css("-moz-opacity", "0.5");
	maskDiv.css("-khtml-opacity", "0.5");
	maskDiv.css("opacity", "0.5");
    maskDiv.css("clear", "both");

    // set position
    loadingIcon.css("z-index", 100);
    loadingIcon.css("position", "absolute");
    loadingIcon.css("top", top + "px");
    loadingIcon.css("left", left + "px");
    loadingIcon.css("clear", "both");

    // turn it on
    maskDiv.css("display", "block");
    loadingIcon.css("display", "block");
}

/**
 * filterSliderMoved
 */
function filterSliderMoved()
{
    finderFiltersChanged(true);
}

/**
 * filterCheckboxClicked
 */
function filterCheckboxClicked() {
    // Update Select/Deselect All link.
    elemName = this.name;
    filtername = elemName.split('_')[1];
    $('#Filters').selectionFilter.setSelectDeselectAll(filtername);

    // Update the filtersChanged.
    finderFiltersChanged(true);
}

function refreshFinderResultSet(resetPager)
{
    if (resetPager === undefined)
    {
        resetPager = false;
    }
    if (resetPager)
    {
        pagerCurrentPage = 0;
    }
    var pageNumber = getCurrentPageNumber();
    var params = getAllCheckboxes();
    // TODO: Keep in case business want to bring this back.
    //params += ";" + getSliderValues();
    
    refreshFiltersApplied();
    showLoadingIcon();
    setSortArrow();

    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/ajax/getfinderdata/',
        data: 'params=' + params + '&orderByField=' + orderByField + '&orderByDirection=' + orderByDirection + '&page=' + pageNumber,
        dataType: "json",
        success: function(data) {

            var exerciseTotal = data['total'];
            var htmlCode = data['htmlCode'];
            var pagerCode = data['pager'];
            $('#pagerDiv').html(pagerCode);

            var filterCountsArray = new Array();
            filterCountsArray = data['filterCounts'];

            $('#SearchResults').html(htmlCode);
            $('#count').html(exerciseTotal);


            //  Reset (almost) all the counts to 0 or blank.
            checkboxes = $("input[id*='filter_']:not(input[id='filter_includeUnrated_0'])");
            for (var j=0;j<checkboxes.length;j++)
            {
                var id = checkboxes[j].id;
                id = id.replace('filter','countlabel');

                if (checkboxes[j].checked)
                {
                    $('#' + id).html('0');
                }
                else
                {
                    $('#' + id).html('');
                }
            }

            for (var i=0;i<filterCountsArray.length;i++)
            {

                var filters = new Array();
                filters = filterCountsArray[i];

                if (filters.length > 0)
                {
                    var filterParam = filters[0]['fieldName'];

                    filterParam = filterParam.replace(/`/g,'');

                    for (var j=0;j<filters.length;j++)
                    {
                        var filterValue = filters[j]['idValue'];
                        var filterNum = filters[j]['num'];

                        if (filterValue == 'N/A')
                        {
                            filterValue = 'NA';
                        }

                        $('#countlabel_' + filterParam + '_' + filterValue).html(filterNum);
                    }

                }
            }
        },
        async: false
    });

    $("#loadingIcon").css("display", "none");
    $("#maskDiv").css("display", "none");
}

function refreshFiltersApplied()
{
    $('#filtersApplied').filtersApplied(filtersAppliedData);
}

function SortExercises(sortBy)
{
    if (sortBy == orderByField){
        if(orderByDirection == 'ASC'){
            orderByDirection = 'DESC';
        }else{
           orderByDirection = 'ASC'
        }
    }else{
        orderByField = sortBy;
        if (orderByField == 'ratings')
         {
           orderByDirection = 'DESC'
         }else{
           orderByDirection = 'ASC';
         }
       
    }

    refreshFinderResultSet(true);

}

function setSortArrow(){
      if (orderByDirection == 'ASC'){
        switch (orderByField)
        {
            case 'exerciseName':
                document.getElementById('exerciseNameASC').style.display = "";
                document.getElementById('muscleNameASC').style.display = "none";
                document.getElementById('equipmentNameASC').style.display = "none";
                document.getElementById('ratingsASC').style.display = "none";
                break;
            case 'muscleName':
                document.getElementById('muscleNameASC').style.display = "";
                document.getElementById('exerciseNameASC').style.display = "none";
                document.getElementById('equipmentNameASC').style.display = "none";
                document.getElementById('ratingsASC').style.display = "none";
                break;
            case 'equipmentName':
                document.getElementById('muscleNameASC').style.display = "none";
                document.getElementById('exerciseNameASC').style.display = "none";
                document.getElementById('equipmentNameASC').style.display = "";
                document.getElementById('ratingsASC').style.display = "none";
                break;
            case 'ratings':
                document.getElementById('muscleNameASC').style.display = "none";
                document.getElementById('exerciseNameASC').style.display = "none";
                document.getElementById('equipmentNameASC').style.display = "none";
                document.getElementById('ratingsASC').style.display = "";
                break;
        }
        document.getElementById('exerciseNameDESC').style.display = "none";
        document.getElementById('equipmentNameDESC').style.display = "none";
        document.getElementById('ratingsDESC').style.display = "none";
        document.getElementById('muscleNameDESC').style.display = "none";
    }else{
         switch (orderByField)
        {
            case 'exerciseName':
                document.getElementById('exerciseNameDESC').style.display = "";
                document.getElementById('muscleNameDESC').style.display = "none";
                document.getElementById('equipmentNameDESC').style.display = "none";
                document.getElementById('ratingsDESC').style.display = "none";
                break;
            case 'muscleName':
                document.getElementById('muscleNameDESC').style.display = "";
                document.getElementById('exerciseNameDESC').style.display = "none";
                document.getElementById('equipmentNameDESC').style.display = "none";
                document.getElementById('ratingsDESC').style.display = "none";
                break;
            case 'equipmentName':
                document.getElementById('muscleNameDESC').style.display = "none";
                document.getElementById('exerciseNameDESC').style.display = "none";
                document.getElementById('equipmentNameDESC').style.display = "";
                document.getElementById('ratingsDESC').style.display = "none";
                break;
            case 'ratings':
                document.getElementById('muscleNameDESC').style.display = "none";
                document.getElementById('exerciseNameDESC').style.display = "none";
                document.getElementById('equipmentNameDESC').style.display = "none";
                document.getElementById('ratingsDESC').style.display = "";
                break;
        }
        document.getElementById('exerciseNameASC').style.display = "none";
        document.getElementById('equipmentNameASC').style.display = "none";
        document.getElementById('ratingsASC').style.display = "none";
        document.getElementById('muscleNameASC').style.display = "none";


    }


}

window.onload = initBWT;

/**
 * this method will take the value passed in by the pager and update the
 * pagerCurrentPage to what it "should" be.
 */
function updateFinderPageNumber(newPage)
{
    pagerCurrentPage = newPage;
    refreshFinderResultSet(false);
    scroll(0,0);
}


/**
 * Return the current pager page number
 */
function getCurrentPageNumber()
{
    if (pagerCurrentPage === undefined)
    {
        pagerCurrentPage = 0;
    }

    return pagerCurrentPage;
}

/**
 *  This function is used on the List all Exercises by muscle and alpha
 *  page = either 'Muscle' or 'Alpha'
 *  sortBy = either 'exerciseName' or 'ratingAverage'
 *  param = either the MuscleID or the letter
 */
function ListAllSort(page,sortBy,param)
{
    // hide the arrows
    $('#exerciseNameASC').hide();
    $('#exerciseNameDESC').hide();
    $('#ratingAverageASC').hide();
    $('#ratingAverageDESC').hide();

    //  Determine which direction we need to go
    if (sortBy == orderByField)
    {
        if(orderByDirection == 'ASC')
        {
            orderByDirection = 'DESC';
        }
        else
        {
           orderByDirection = 'ASC'
        }
    }
    else
    {
        orderByField = sortBy;
        if (orderByField == 'ratingAverage')
        {
            orderByDirection = 'DESC'
        }
        else
        {
            orderByDirection = 'ASC';
        }
    }

    //  Show the appropriate arrow image
    $('#' + sortBy + orderByDirection).show();

    //  Determin which ajax file needs to be called
    if (page == 'Muscle')
    {
        ajaxPage='getexercisesbymuscle';
    }
    if (page == 'Alpha')
    {
        ajaxPage='getexercisesbyletter';
    }

    $.ajax({
        type: 'POST',
        url: getBaseURLExercises() + '/ajax/' + ajaxPage,
        data: 'sortField=' + sortBy + '&orderByDirection=' + orderByDirection + '&param=' + param,
        dataType: 'json',
        success: function(html) {
            $('#listResults').empty();
            $('#listResults').append(html.htmlCode);
        }
    });

}
