var RATING_IMAGE_PATH = "assets/images/ratings/";

function initializeRatingsControls()
{
    // cache images for rating rollover
    (new Image()).src = RATING_IMAGE_PATH + "user_rating_1.png";
    (new Image()).src = RATING_IMAGE_PATH + "user_rating_2.png";
    (new Image()).src = RATING_IMAGE_PATH + "user_rating_3.png";
    (new Image()).src = RATING_IMAGE_PATH + "user_rating_4.png";
    (new Image()).src = RATING_IMAGE_PATH + "user_rating_5.png";

    var imgElement = document.getElementsByTagName( "img" );
    if ( imgElement )
    {
        for ( var imgIndex = 0; imgIndex < imgElement.length; imgIndex++ )
        {
            if ( imgElement[imgIndex].className == "rating" )
            {
                attachEventToElement ( imgElement[imgIndex], "click", onClick_ratingImg, false );
                attachEventToElement ( imgElement[imgIndex], "mousemove", onMouseMove_ratingImg, false );
                attachEventToElement ( imgElement[imgIndex], "mouseout", onMouseOut_ratingImg, false );
                displayRatingFromElement( imgElement[imgIndex] );
            }
        }
    }
    
    var args = getQueryStringArgs();
    if ( args.Rating && args.PoemId )
    {
        initiateAjaxCall( "ajax_rate_poem.aspx?PoemId=" + args.PoemId + "&Rating=" + escape( args.Rating ), asyncRatePoem );
        if ( document.getElementById( "linkSignout" ) )
        {
            // remove rating argument from signout link to avoid immediate redirect back to signin
            var linkSignout = document.getElementById( "linkSignout" );
            var ratingParameterStartIndex = linkSignout.href.indexOf( "Rating" );
            var parameterAfterRatingStartIndex = linkSignout.href.indexOf( "%26", ratingParameterStartIndex ); // "%26" == escape("&")
            if ( parameterAfterRatingStartIndex == -1 )
            {
                linkSignout.href = linkSignout.href.substring( 0, ratingParameterStartIndex - 3); // -3 to remove "%26" before Rating
            }
            else
            {
                linkSignout.href = linkSignout.href.substring( 0, ratingParameterStartIndex ) + 
                    linkSignout.href.substring( parameterAfterRatingStartIndex );
            }
        }
    }
}

function asyncRatePoem( ajaxText )
{
    var ajaxResults = eval( "(" + ajaxText + ")" );
    
    if ( ajaxResults.error )
    {
        switch ( ajaxResults.error.code )
        {
            case null:
            // catch the cases where rating updated through the query string (and hence not updated through click handler)
            var updatedRatingElement = document.getElementById( "rating_" + ajaxResults.poemId );
            updatedRatingElement.setAttribute( "user-rating", ajaxResults.rating );
            displayRatingFromElement( updatedRatingElement );
            break;
            
            case "not_signed_in":
            if ( document.location.pathname.indexOf( "PoemId=" ) == -1 )
            {
                window.location = document.location.href.substring( 0, document.location.href.lastIndexOf("/") + 1 ) + "signin.aspx?ReturnUrl=" +
                    escape( location.href + ( (location.href.indexOf( "?" ) == -1) ? "?" : "&") + "PoemId=" + ajaxResults.poemId + "&Rating=" + ajaxResults.rating );
            }
            else
            {
                window.location = document.location.href.substring( 0, document.location.href.lastIndexOf("/") + 1 ) + "signin.aspx?ReturnUrl=" +
                    escape( location.href + ( (location.href.indexOf( "?" ) == -1) ? "?" : "&") + "Rating=" + ajaxResults.rating );
            }
            break;
            
            // silent failure for other error cases
        }
    }
}

function onClick_ratingImg( e )
{
    if ( !e ) e = window.event;
    var targetElement = ( e.target ? e.target : e.srcElement );
    
    var newStarCount = xToStars( e.clientX - absLeft(targetElement) );
    targetElement.setAttribute( "user-rating", newStarCount );
    displayRatingFromElement( targetElement );
    
    var poemId = targetElement.id.substr( targetElement.id.indexOf( "_" ) + 1 );
    
    initiateAjaxCall( "ajax_rate_poem.aspx?PoemId=" + poemId + "&Rating=" + newStarCount, asyncRatePoem );
}

function onMouseMove_ratingImg( e )
{
    if ( !e ) e = window.event;
    var targetElement = ( e.target ? e.target : e.srcElement );
    var stars = xToStars( e.clientX - absLeft(targetElement) );
    targetElement.src = RATING_IMAGE_PATH + "user_rating_" + stars + ".png";
    targetElement.title = "click to rate " + stars + " stars";
    targetElement.alt = "click to rate " + stars + " stars";
}

function onMouseOut_ratingImg( e )
{
    if ( !e ) e = window.event;
    var targetElement = ( e.target ? e.target : e.srcElement );
    displayRatingFromElement( targetElement );    
}

function xToStars( x )
{
    var result = Math.floor( ( x ) / 14 ) + 1;
    if ( result < 0 ) result = 0;
    if ( result > 5 ) result = 5;
    return result;
}

function displayRatingFromElement( element )
{
    if ( element )
    {
        var ratingPrefix = "user_";
        var rating = element.getAttribute( "user-rating" );
        if ( rating == 0 ) 
        {
            rating = Math.round( element.getAttribute( "average-rating" ) * 2 ) * 5;
            ratingPrefix = "average_";
        }
        
        if ( rating == 0 )
        {
            element.src = RATING_IMAGE_PATH + "rating_0.png";
            element.alt = "not rated";
            element.title = element.alt;
        }
        else
        {
            element.src = RATING_IMAGE_PATH + ratingPrefix + "rating_" + Math.round( rating ) + ".png";
            element.alt = "rated " + rating + " stars";
            element.title = element.alt;
        }
    }
}
