/**
 * Star rating system , by Riccardo Attilio Galli <riccardo@sideralis.org>
 * 
 * Known to work until jquery 1.4.2
 *
 * Return an object defining the behaviour of clicking the stars
 *
 * STAR_RATING={
 *     on_star_clicked:function(){}, // see inner documentation
 *     on_relevanceButton_clicked:function(){} // see inner documentation
 * }
 */

STAR_RATING=(function($){

var jQuery=$,undefined;

// the following labels should be defined outside of this document using smarty (or change them here if possible)
if (!window.HAVE_ALREADY_VOTED_MSG) var HAVE_ALREADY_VOTED_MSG = "HAVE_ALREADY_VOTED";
if (!window.NOT_ALLOWED_MSG)        var NOT_ALLOWED_MSG = "NOT_ALLOWED";
if (!window.AGREEMENT_STRING)       var AGREEMENT_STRING = "NUM_RATING";

/*
 * Function: on_star_clicked
 *
 * Update the rating for a post or resource
 *
 * Arguments:
 *    ownerName - resource name
 *    ownerId - resource id
 *    value - value of agreement given to the resource
 *    isActive - wheter the user is active or not (e.g. banned )
 *    isRealUser - wheter the user is a real,registered user, or anonymous
 *    letVote - wheter a rating can be sent or not (e.g. because the user has voted before and can't anymore)
 *    btn - the element who fired the click event
 *
 * Note:
 *   user's permissions are however checked again server side
 */
function on_star_clicked(ownerName,ownerId,value,isActive,isRealUser,letVote,btn) {

    var numStarClasses=[
        "nostar","onestar","twostar","threestar","fourstar","fivestar"
    ];


    if (isActive) {
        if (isRealUser) {

            if (letVote) { // we must send the new value to the server

                jQuery.post(
                    "/"+(document.location.href.match(/:\/\/.*?\/(.*?)\//)[1])+"/insertStarRating/"+ownerName+"/"+ownerId,
                    { "ratingValue":value },
                    function(response){
                        if (!response || response['error']) {
                            alert(response['error'] || "errore sconosciuto");
                        } else { // success

                            // update the stars appearance, highlighting the current average value
                            $(".rating_"+ownerName+"_"+ownerId+" .ratingList").each(
                                function(idx,elem) {
                                    elem.setAttribute("class","ratingList "+numStarClasses[Math.round(response["data"]["STATS"]["avg_agr"])]);
                                }
                            );

                            // deactivate the possibility to vote again
                            var tmpElems=$(".rating_"+ownerName+"_"+ownerId+" .ratingList a");
                            for(var i=0,il=tmpElems.length;i<il;i++) {
                                $(tmpElems[i]).unbind("click");
                                tmpElems[i].onclick=function(){return on_star_clicked(ownerName,ownerId,i+1,isActive,isRealUser,false,btn);};
                            }

                            // update the label with the numbers of agreements given
                            $(".rating_"+ownerName+"_"+ownerId+" .agreement_label").each(
                                function(idx,elem){
                                    elem.innerHTML="";
                                    elem.appendChild(document.createTextNode(response["data"]["STATS"]["tot_agr"]+" "+AGREEMENT_STRING));
                                }
                            );

                            alert("Preferenza salvata con successo");
                        }
                    }, // end response function
                    'json'
                );
            }
            else alert(HAVE_ALREADY_VOTED_MSG);

        } else {
            $("#rating_"+ownerName+"_"+ownerId).toggle();

        }
    } else {
        alert(NOT_ALLOWED_MSG);
    }

    return false;
}

/*
 * Function: on_relevanceButton_clicked
 *
 * Update the relevance value for a post or resource
 *
 * Arguments:
 *    ownerName - resource name
 *    ownerId - resource id
 *    value - value of agreement given to the resource
 *    isActive - wheter the user is active or not (e.g. banned )
 *    isRealUser - wheter the user is a real,registered user, or anonymous
 *    btn - the element who fired the click event
 *
 * Note:
 *   user's permissions are however checked again server side
 */
function on_relevanceButton_clicked(ownerName,ownerId,isActive,isRealUser,btn) {

    /* Find the first ancestor with a certain class*/
    function findAncestorByClass(xyz,classname) {
        while ((xyz=xyz.parentNode) && !($(xyz).hasClass(classname)));
        return xyz || null;
    }

    if (isActive) {
        if (isRealUser) {
            jQuery.post(
                "../insertStarRating/"+ownerName+"/"+ownerId,
                { "relevance" : 1 },
                function(response){
                    if (!response || response['error']) {
                        alert(response['error'] || "errore sconosciuto");
                    } else { // success

                        if (!$(btn.parentNode).hasClass("relevanceActive")) {
                            // this should be fired only if we change layout and
                            //   forget to modify accordingly our javascript code
                            alert("Layout has been changed ! check javascript code");
                            return false;
                        }

                        $(".rating_"+ownerName+"_"+ownerId+" .relevanceHolder").each(

                            function(idx,box) {

                                var btnParent=$(".relevanceActive",box)[0];

                                // change the current linked button with one grey and inactive
                                /*
                                   XXX: this is not best practice, because it doesn't follow
                                    changes in the normal rendering of this button
                                   Maybe a single dummy and hidden inactive button to copy
                                    could solve this problem
                                */

                                var imgElem=document.createElement("img");
                                imgElem.src="/img/icons/accept_grey.png";

                                box.insertBefore(imgElem,btnParent);
                                box.removeChild(btnParent);

                                $(".relevanceValue",box)[0].innerHTML=response["data"]["STATS"]["tot_rel"];

                            }

                        );

                    }
                }, // end response function
                'json'
            ); // end jQuery.post
        }
        else {
            $("#rating_"+ownerName+"_"+ownerId).toggle();
        }
    }
    else {
        alert(NOT_ALLOWED_MSG);
    }

    return false;
}

return {
    on_star_clicked:on_star_clicked,
    on_relevanceButton_clicked:on_relevanceButton_clicked
}


})(jQuery);
