﻿var userRated = false;
var numOfStars = 0;

var starIndex = -1;
var selectText = "Please select a rating";
var ratingText = ["1 Star - Didn't like it", "2 Stars - OK", "3 Stars - Good", "4 Stars - Very Good", "5 Stars - Excellent"];


(function ($) {
    $(document).ready(function () {

        numOfStars = Math.round(parseFloat($('.average', this).html()));
                 
        
        /* Handle the sign-in WS call */
        $('#createComment #recipeCommentSignIn a[href="#signin_screen"]').click(doRecipeCommentSignIn);

        $('#createComment a[id$=SubmitRecipeComment]').click(docreateRecipeComment);
        
        if ( isMobile != null && isMobile != true )
            addLoginStateFunction(setupComments);

        // Draw stars w/ no ratings
        $('.rating:not(.userRating)').each(drawStars);
        //$('.rating').each(setExistingRating);

        $('.userRating').each(drawStarsNoRatings);


        // Set the current rating        
        //$('#recipeOverview .star').each(setCurrentRating)

        // Setup hover states for both sets of rating stars
        $('.ratable .star').hover(starHover, starUnhover);
        
        // Set up click for top set of stars 
        // (which focuses and sets the rating on the bottom stars)
        $('#recipeOverview .star').click(overviewStarClick);
        
        $('#createComment .star').click(createRatingStarClick);

    });

})(jQuery);

function setExistingRating()
{
    ratingStars = Math.round(parseFloat($('.average', this).html()));
}

function overviewStarClick()
{
    starIndex = $(this).prevAll().length;
    setUserRating(starIndex);

    $.scrollTo('#createComment');
}

function createRatingStarClick()
{
    starIndex = $(this).prevAll().length;
    setUserRating(starIndex);
}

function setUserRating(starIndex)
{
    $('#createComment .star').removeClass('selected');
    $('#createComment .star').each(function(index, element) {
        if ( index <= starIndex )
            $(element).addClass('selected');
    });

    setRatingText(starIndex);
}

function setRatingText(starIndex)
{
    $('#createComment .ratingDesc').html(ratingText[starIndex]);
}

function starHover()
{
    if (!userRated && !$(this).hasClass('rated'))
    {
        for (i = 0; i < $(this).prevAll().length + 1; i++) 
            $(this).parent().children('.star').eq(i).addClass('hover');
    }

    $('#createComment .ratingDesc').html(ratingText[$(this).prevAll().length]);
}

function starUnhover()
{
    $(this).parent().children('.star').removeClass('hover');

    if ( starIndex > -1 )
        $('#createComment .ratingDesc').html(ratingText[starIndex]);
    else 
        $('#createComment .ratingDesc').html(selectText);
}

function drawStars()
{
    var reviewStars = Math.round(parseFloat($('.average', this).html()));
    var ratingStars = '';
    for (i = 1; i <= 5; i++) {
        var ratingText = (i > 1) ? ' Stars' : ' Star';
        ratingStars += '<span class="star';
        ratingStars += (i <= reviewStars) ? ' red">' : '">';
        ratingStars += (i == reviewStars) ? i + ' ' + ratingText + '</span>' : '</span>';
    }
    $('.average', this).replaceWith(ratingStars);
    $(this).append('<div class="clearboth"></div>');
}

function drawStarsNoRatings()
{
    var reviewStars = Math.round(parseFloat($('.average', this).html()));
    var ratingStars = '';
    for (i = 1; i <= 5; i++) {
        var ratingText = (i > 1) ? ' Stars' : ' Star';
        ratingStars += '<span class="star">';
        ratingStars += (i == reviewStars) ? i + ' ' + ratingText + '</span>' : '</span>';
    }
    $('.average', this).replaceWith(ratingStars);
    $(this).append('<div class="clearboth"></div>');

}

function setCurrentRating(index, element)
{
    if ( index < numOfStars )
        $(element).addClass('red');
}


function doRecipeCommentSignIn()
{
    //initLoginDialog(); //this is called by global #sign_in handler
    postLoginFunction = recipeCommentPostLoginFunction;
    return false;
}

function recipeCommentPostLoginFunction()
{
    $('#createComment .anonymousFields').css('display', 'none');
}

function docreateRecipeComment() {
    clearFormErrors($('#createComment'));
    var cmtType = $('#createComment input[id*=commentTypeValue]').val();
    var requestData = {
            anonymousUserName: $('#createComment #anonymousUserName').val(),
            anonymousUserEmail: $('#createComment #anonymousUserEmail').val(),
            ageVerificationCheckbox: $('#createComment #ageVerificationCheckbox:checked').val(),
            recipeId: recipeId,
            commentType: $('#createComment input[id*=commentTypeValue]').val(),
            commentText: $('#createComment #CommentText').val(),
            rating: starIndex + 1,
            recaptcha_response_field: $('#createComment #recaptcha_response_field').val(),
            recaptcha_challenge_field: $('#createComment #recaptcha_challenge_field').val()
        };
    switch(cmtType) {
        case 'review':
            googleReportEvent('recipe', 'fullrate', window.location.pathname);
            break;
        case 'general':
            googleReportEvent('recipe', 'comment', window.location.pathname);
            break;
        case 'variation':
            googleReportEvent('recipe', 'variation', window.location.pathname);
    }
    onSuccess = createCommentSuccess;
    createRecipeComment(requestData);
    return false;
}

function createRecipeComment(requestData) {
    AjaxCall(requestData);
}

function createRecipeCommentReply(reply, requestData, callingFunction)
{
    if (reply.Success != "true") {

        if ( CaptchaError(reply.Errors) )
            Recaptcha.reload();

        if (IsAuthError(reply)) {
            $('a#login').trigger('click');
            postLoginFunction = partial(callingFunction, requestData);
        } else {
            displayErrors(reply.Errors, $('#createComment'));
        }

    } else {
        googleReportEvent('recipe', 'valid', window.location.pathname);
        
        if (onSuccess != null) {
            onSuccess();
            onSuccess = null;
        }
    }
}

function CaptchaError(errors) {
    var captchaError = false;
    $.each(errors, function(index, error) {
        if (error.Field == "Captcha")
            captchaError = true;
    });

    return captchaError;
}

function createCommentSuccess() {
    $('#createComment').css('display', 'none');
    $('#recipeCommentSubmitted').css('display', 'block');
}


function handleSubmitRatingReply(data) {
    switch (data.status) {
        case 'success':
            userRated = true;
            $('#recipeOverview .star').removeClass('hover red').addClass('rated');
            for (i = 0; i < data.avgrating; i++) {
                $('#recipeOverview .star').eq(i).addClass('red');
            }
            var ratingText = (parseInt(data.numratings) == 1) ? ' Rating' : ' Ratings';
            $('#recipeOverview .count').html(data.numratings)
            $('#recipeOverview .countdesc').html(ratingText);
            break;
    }
}
