﻿(function ($) {

    $.fn.contentRating = function (options) {

        var defaults = {}; // defaults are defined in vb
        var config = $.extend(defaults, options);
        this.each(function () {

            var self = this;
            var $self = $(this);
            var $ratingForm = $(".RatingForm", $self);
            var $submitRating = $("a.SubmitRating", $self);
            var $cancelRating = $("a.CancelRating", $self);
            var $deleteRating = $("a.DeleteRating", $self);
            var $ratingCount = $("span.RatingCount", $self);
            var $overallRatingContainer = $("div.OverallRatingContainer", $self);
            var $contentRatingID = $("input[name='ContentRatingID']", $self);
            var $starInput = $("div.StarInput", $self);
            var $formComment = $(".RatingForm textarea", $self);
            var $ratingSpinner = $("p.RatingSpinner", $self);

            populate($starInput);

            // Wire up dataBind on self
            $self
                .bind("dataBind", dataBind)
                .trigger("dataBind")
            $submitRating.die("click").live("click", submitRating);
            $cancelRating.die("click").live("click", cancelRating);
            $deleteRating.die("click").live("click", deleteRating);

            function dataBind(e) {
                $r.showProgress();
                var $contentRatingPlaceholder = $('div.ContentRatingPlaceholder', self);
                var $contentRatingTemplate = $('#ContentRatingTemplate', self);
                var $histogramPlaceholder = $('div.HistogramPlaceholder', self);
                var $histogramTemplate = $('#HistogramTemplate', self);
                $.ajax({
                    url: $r.cleanHref(window.location),
                    type: "POST",
                    data: {
                        containerId: self.id,
                        action: "select"
                    },
                    success: function (msg) {
                        var ratingData = JSON.parse(msg);
                        // Bind using MicroTemplate
                        $histogramPlaceholder.html(parseTemplate($histogramTemplate.html(), { ratingData: ratingData }));
                        $contentRatingPlaceholder.html(parseTemplate($contentRatingTemplate.html(), { ratingData: ratingData }));
                        $self.enableBehavior();
                        $r.hideProgress();
                        $r.enableWatermarks();
                        // Display stats
                        displayStats(ratingData);
                        // Wire up star input on input form
                        populate($starInput);
                        $starInput.stars({ inputType: 'select', cancelShow: false });
                        // Wire up "change review" button
                        $("a.ChangeReviewButton", self).bind("click", function (event) {
                            var $container = $(this).parents(".ContentRating");
                            var ratingID = $container.attr("id");
                            var ratingValue = $container.find("div.DisplayStars", self).attr("ThisRating");
                            var comment = $container.find("div.UserComment p", self).html();
                            $contentRatingID.val(ratingID);
                            $starInput.stars("select", ratingValue);
                            $formComment.val(comment).focus();
                            $ratingForm.show();
                            $deleteRating.show();
                            $cancelRating.show();
                            $container.hide();
                        })
                        // Wire up breakdown toggle
                        var $showBreakdownButton = $("a.ShowBreakdownButton", $self);
                        var $hideBreakdownButton = $("a.HideBreakdownButton", $self);
                        var $ratingHistogram = $("div.RatingHistogram", $self);
                        $showBreakdownButton.bind("click", function (event) {
                            $showBreakdownButton.hide();
                            $hideBreakdownButton.show();
                            $ratingHistogram.slideDown();
                            event.preventDefault();
                        });
                        $hideBreakdownButton.bind("click", function (event) {
                            $showBreakdownButton.show();
                            $hideBreakdownButton.hide();
                            $ratingHistogram.slideUp();
                            event.preventDefault();
                        });
                        // Hide spinner once databinding is complete
                        $ratingSpinner.hide();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $r.showError(XMLHttpRequest, errorThrown);
                        $r.hideProgress();
                        $ratingSpinner.hide();
                    }
                });
            } // dataBind

            function displayStats(ratingData) {
                // Set visibility for overall rating display
                if (ratingData.RatingsCount >= config.minimumRatingsToShow) {
                    $overallRatingContainer.show();
                } else {
                    $overallRatingContainer.hide();
                }
                // Can't rate twice
                if (ratingData.CurrentUserHasReview) {
                    $ratingForm.hide()
                } else {
                    //$ratingForm.show()
                };
            } // displayStats

            function submitRating(e) {
                $r.showProgress();
                var ratingID = $contentRatingID.val() || 0;
                var ui = $starInput.data("stars");
                var rating = ui.options.value;
                var comment = $formComment.val();
                if (comment == $formComment.attr("title")) comment = '';
                if (rating > 0) {
                    $.ajax({
                        url: $r.cleanHref(window.location),
                        type: "POST",
                        data: {
                            containerID: self.id,
                            action: "save",
                            ratingID: ratingID,
                            rating: rating,
                            comment: comment
                        },
                        success: function (msg) {
                            if (!isNaN(msg)) {
                                var newId = msg;
                                $self.trigger("dataBind", [newId]);
                            } else {
                                $r.updateStatus('warning', "Oops - your comment was not saved.")
                                $r.hideProgress();
                            };
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            $r.showError(XMLHttpRequest, errorThrown);
                            $r.hideProgress();
                        }
                    });
                } else {
                    alert("Please select a rating.");
                    $self.trigger("dataBind"); // Easy way to clear progress, waitbuttons
                }
                e.preventDefault();
            } // submitRating

            function cancelRating(e) {
                $self.trigger("dataBind");
            }

            function deleteRating(e) {
                if (confirm("Are you sure you want to permanently delete this review?")) {
                    $r.showProgress();
                    var ratingID = $contentRatingID.val() || 0;
                    if (ratingID > 0) {
                        $.ajax({
                            url: $r.cleanHref(window.location),
                            type: "POST",
                            data: {
                                containerID: self.id,
                                action: "delete",
                                ratingID: ratingID
                            },
                            success: function (msg) {
                                if (!isNaN(msg)) {
                                    $self.trigger("dataBind");
                                    $ratingForm.hide();
                                } else {
                                    $r.updateStatus('warning', "Oops - your comment was not deleted.")
                                    $r.hideProgress();
                                };
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                $r.showError(XMLHttpRequest, errorThrown);
                                $r.hideProgress();
                            }
                        });
                    } else {
                        $self.trigger("dataBind"); // Easy way to clear progress, waitbuttons
                    }
                }
                e.preventDefault();
            } // deleteRating

            // Adds options to select element
            function populate($el) {
                $el.each(function () {
                    var options = config.options.split(',');
                    var $select = $("select", this);
                    $select.find("option").remove(); // remove any existing options
                    $.each(options, function (i) {
                        var newOptionMarkup = String.format("<option value='{0}'>{1}</option>", i + 1, this);
                        $select.append(newOptionMarkup);
                    });
                });
            }; // populate

        }); // each

    }; // $.fn.contentRating 

})(jQuery);


