using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using APNSoft.WebControls;

public partial class Rating_RateArticle : System.Web.UI.Page
{

    //Declarations
    public int Votes = 0; //The number of votes
    private int TotalRatingSum = 0; //Total rating sum


    protected void Page_Load(object sender, EventArgs e)
    {

        //Get the Votes from session
        object _Votes = Session["Votes"];
        if (_Votes != null) Votes = (int)_Votes;

        //Get the TotalRatingSum from session
        object _TotalRatingSum = Session["TotalRatingSum"];
        if (_TotalRatingSum != null) TotalRatingSum = (int)_TotalRatingSum;

        //Display default value
        myRating.SetValue(GetAverageRating());

        //Apply event-handling method
        myRating.OnSegmentClick += new APNSoft.WebControls.RatingEventHandler(myRating_OnSegmentClick);
    }


    //Calculates average rating
    public double GetAverageRating()
    {
        double _Result = 0;

        if (Votes > 0)
        {
            _Result = Math.Round((double)TotalRatingSum / (double)Votes, 2);
        }

        return _Result;
    }


    //The event-handling method
    void myRating_OnSegmentClick(object sender, APNSoft.WebControls.RatingEventArgs e)
    {

        //Get component instance
        APNSoftRating myRating = (APNSoftRating)sender;

        //Get clicked Segment
        RatingSegment mySegment = e.RatingSegment;

        //Add the vote
        Votes++;
        Session["Votes"] = Votes; //Save in session

        //Add vote value
        TotalRatingSum = TotalRatingSum + mySegment.value;
        Session["TotalRatingSum"] = TotalRatingSum; //Save in session

        //Return new values to the client (via Parameter)
        e.Parameter = Votes.ToString() + "_" + GetAverageRating();
    }

}