﻿
function Terra_RatingsProxy(asmxUrl) {
    this.rate = function(itemUrl, ratingValue, rate_cb) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: asmxUrl + "/Rate",
            data: '{ "itemUrl":"' + itemUrl + '", "ratingValue":"' + ratingValue + '" }',
            dataType: "json",
            success: rate_cb
        });
    }
    this.getRatingResults = function(itemUrl, rate_cb) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: asmxUrl + "/GetRatingsResults",
            data: '{ "itemUrl":"' + itemUrl + '"}',
            dataType: "json",
            success: rate_cb
        });
    }
}

var rp = new Terra_RatingsProxy("/Terra.Portal.AjaxServices/Ratings/RatingsService.asmx");

$(document).ready(function() {
    if ($get('vot3').style.display != "none") {
        $('#Rating1').rating(Rated);
    }
    InitializeRatingStats();
});


/***************************************************************************/

//Sets the properties of the controls
function SetRatingsValues(result) {
    var el = $("#RatingAvg")[0];
    el.src = result.AvgImageUrl;
    el.alt = result.RatingAverage;
    el.title = result.RatingAverage;

    var arrayNumRatings = new Array(result.NumRatings1, result.NumRatings2, result.NumRatings3, result.NumRatings4, result.NumRatings5);
    SetRatingStats(arrayNumRatings);
}

//Query the current rating stats and updates the controls
function InitializeRatingStats() {
    //Terra.Portal.AjaxServices.RatingsService.GetRatingsResults(itemUrl, OnQueryResultsComplete, OnRatingsFailedCallback);    
    rp.getRatingResults(itemUrl, OnQueryResultsComplete);

}

function OnQueryResultsComplete(result) {
    SetRatingsValues(result.d);
}

//Updates the control using ajax. used from foto and video gallery
function UpdateRatingsAndComments(urlFotoVideo) {
    existeTerra = window.Terra ? window.Terra : false;
    if (existeTerra != false) {
        //Updates ratings
        itemUrl = urlFotoVideo; //itemUrl must be defined. the control defines it on server side
        InitializeRatingStats();

        //Updates NumeroComentarios
        Terra.Portal.AjaxServices.CommentsService.GetInfoNumComentarios(urlFotoVideo, OnUpdateNumComentarios, OnUpdateNumComentariosError);
    }
}


function OnUpdateNumComentarios(infoNumComentarios) {
    $get("NumComentarios").innerText = infoNumComentarios.numComentarios;
    $get("UrlNumComentarios").href = infoNumComentarios.urlComentarios;
}

function OnUpdateNumComentariosError(error) {
    $get("NumComentarios").innerText = 0;
    $get("UrlNumComentarios").href = "javascript:void(0)";
}

/*********
Post rating control
*********/

//Handler of rated event of the control
function Rated(val) {
    //This is the current rating value that must be used in the AjaxService Call
    //Terra.Portal.AjaxServices.RatingsService.Rate(itemUrl, eventArguments.get_Rating(), OnRated, OnRatingsFailedCallback);

    //Disable the control for other rates
    //source._readOnly = true;
    //alert(val);
    rp.rate(itemUrl, val, OnRated);
}

//After web service process the rate
function OnRated(result) {
    //Result is the new rating average. Refresh control with this value
    SetRatingsValues(result.d);
}

//When web service call returns and error
function OnRatingsFailedCallback_TODO(error) {

    var stackTrace = error.get_stackTrace();
    var message = error.get_message();
    var statusCode = error.get_statusCode();
    var exceptionType = error.get_exceptionType();
    var timedout = error.get_timedOut();

    // Display the error.    
    strError =
        "Stack Trace: " + stackTrace + "<br/>" +
        "Service Error: " + message + "<br/>" +
        "Status Code: " + statusCode + "<br/>" +
        "Exception Type: " + exceptionType + "<br/>" +
        "Timedout: " + timedout;

    // alert(strError);
}



/*********
Rating average + rating stats methods
*********/

function ShowHideRatings() {

    $("#pnlRatings").slideToggle();


    var btnStats = $("#btnStats")[0];
    if (btnStats.src.indexOf("icoCalendarioArtDesp.gif")>0)
    {
        btnStats.src = "/images/icoVotacionesDesp.gif";    
    }
    else
    {
        btnStats.src = "/images/icoCalendarioArtDesp.gif";    
    }
    
}


function SetRatingStats(numRatingsArray) {
    //Set the number of votes
    var totalRatings = 0;
    var i = 0;
    for (i = 1; i <= 5; i++) {
        $("#numRatings" + i).text(numRatingsArray[i - 1]);
        totalRatings = totalRatings + numRatingsArray[i - 1];
    }

    //Set the percentage for each rating value
    var percentageRatings = new Array(5);
    for (i = 0; i < 5; i++) {
        if (totalRatings == 0) {
            percentageRatings[i] = 0;
        }
        else {
            percentageRatings[i] = numRatingsArray[i] * 100 / totalRatings;
        }
    }
    
    SetRatingGauges(percentageRatings);
}

//Set the percentage gauges of each rating value (1 to 5) 61 max width
function SetRatingGauges(valueArray) {   
    var i = 5;   
    for (i = 5; i > 0; i--) {
        var fullWidth = Math.round(61 * valueArray[i - 1]/100);

        if (fullWidth == 0)
            fullWidth = 1;        

        $("#gaugeFull" + i).width(fullWidth);
    }
}
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();