﻿;(function($) {
    var varType = "POST";
    var varUrl;
    var varData;
    var varContentType = "application/json; charset=utf-8";
    var varDataType = "json";
    var varSuccess;
    var varProcessData = true;
    var varSuppressCallback = false;
    var varAck = "";
    var varPageID = -1;

    function CallService() {
        $.ajax({
            type: varType, //GET or POST or PUT or DELETE verb
            url: varUrl, // Location of the service
            data: varData, //Data sent to server
            contentType: varContentType, // content type sent to server
            dataType: varDataType, //Expected data format from server
            processdata: varProcessData, //True or False
            success: varSuccess,
            error: ServiceFailed// When Service call fails
        });
    }

    function ServiceSucceeded(result) {
    }

    function ServiceFailed(result) {
        // alert("Failure: " + result);
    }

    $.fn.Votes = function() { };

    $.fn.Votes.Ack = function(strAck) {
        varAck = strAck;
    }

    $.fn.Votes.GetScore = function(iPageID) {
        varSuccess = GetScoreSucceeded;
        varUrl = "/vsvc/GetScore";
        varData = '{"iPageID" : ' + iPageID + '}';
        CallService();
    }

    function GetScoreSucceeded(result) {
        varSuppressCallback = false;   // temporarily suppress callback while we set value directly
        var $result = result['GetScoreResult']; // object
        var $fscore = $result['Score'];
        var $votes = $result['Votes'];
        $('.rating').rating('select', Math.round($fscore).toString());
        varSuppressCallback = true;   // restore callback function
        
        var strSummary = $('.styleRateSummaryTemplate').text();
        strSummary = strSummary.replace(/%s%/, $fscore.toFixed(1));
        strSummary = strSummary.replace(/%v%/, $votes.toString());
        $('.styleRateSummary').text(strSummary);
    }

    $.fn.Votes.Vote = function(iSiteID, iPageID, strURL, dScore) {
        if (!varSuppressCallback)
            return;

        varPageID = iPageID;    // useful later.

        // get UID from cookie
        var strUID = $.cookie('VUID');
        if (!strUID)
            strUID = "-1";
        varSuccess = VoteSucceeded;
        varUrl = "/vsvc/Vote";
        varData = '{"iUID" : ' + strUID + ', "iSiteID" : ' + iSiteID + ', "iPageID" : ' + iPageID + ', "strURL" : "' + strURL + '", "dScore" : ' + dScore + '}';
        CallService();
    }

    function VoteSucceeded(result) {
        // stick new UID in cookie
        $.cookie('VUID', result['VoteResult'].toString(), { expires: 365, path: '/' }); // year-round cookie!
        // acknowledge the vote
        if (varAck.length > 0)
            alert(varAck);
        // show new result
        $.fn.Votes.GetScore(varPageID);
    }


})(jQuery);
