/*
    Calls the RnR service to get all of the ratings and reviews for an asset
*/

var _constRnRUrl = "http://" + _RESTDomain + "/RnR/RnRHandler.ashx";
var proxyUrl = "/NonAcm/Proxy.ashx";

var _isIE = false;

var _script;

var me;
var _xsl = "";

var urlReferrer = document.location.pathname + document.location.search;
urlReferrer = urlReferrer.replace("&", "|");
var _loginUrl = 'http://' + document.location.host + '/page/Login_to_Active_Com/?referrerUrl=' + urlReferrer;

var _AddReviewCssName = "";

//Check the Browser Type
 if (navigator.appVersion.match(/\bMSIE\b/))
{
    _isIE = true;
}


function rnr()
{
    this.assetId = "";
    this.totalReviewsCount = 0;
    this.reviews = "";
    this.ratings = "";
    this.averageRating = 0;
    this.user = "";
    this.reviewsElementId = "";
    this.enableRating = "";
    this.rating = "";
    this.userId = _currentUserId;
    this.ratingId = "";
    this.localDomain = "";
    this.enableEdit = false;
    this.requireLogin = true;
    this.xml = "";
    this.xsl = "";
    this.maxReviews = "";
    this.watching = "";
    this.returnFocusElementID = "";                 
    this.getRnR = function(isFutureEvent)
                    {
                        me = this;
                        isLoggedIn();
                        var postBodyValue = "";
                        postBodyValue = "<request>";
                        postBodyValue += "<assetId>" + this.assetId + "</assetId>";
                        postBodyValue += "<uId>" + _currentUserId + "</uId>";
                        postBodyValue += "<functionName>GetRnRHtml</functionName>";
                        postBodyValue += "<destinationUrl>" + _constRnRUrl + "</destinationUrl>";
                        postBodyValue += "<maxReviews>" + this.maxReviews + "</maxReviews>";
                        postBodyValue += "<urlReferer>" + encodeURIComponent(location.href) + "</urlReferer>";
                        postBodyValue += "<isFutureEvent>" + isFutureEvent + "</isFutureEvent>";
                        postBodyValue += "</request>";
                        
                        ShowWait(true, this.reviewsElementId);  
                        
                        var requestCall = new Ajax.Request(proxyUrl
                                                            ,
                                                                {
                                                                    method: "POST",
                                                                    contentType: "text/xml",
                                                                    postBody: postBodyValue,
                                                                    onSuccess: function(req)
                                                                                {
                                                                                        document.getElementById(me.reviewsElementId).innerHTML = req.responseText;     
                                                                                },
                                                                         onFailure: function()
                                                                                {
                                                                                    alert('Failed');
                                                                                },
                                                                         onComplete: function()
                                                                                {
                                                                                    //BP 6.4.09
                                                                                    //Hide the show all reviews link if the call is returning all.
                                                                                    if(_rnr.maxReviews == "-1")
                                                                                    {
                                                                                        $("seeAllReviews").setStyle({display: "none"});
                                                                                    }
                                                                                    
                                                                                    ShowWait(false, me.reviewsElementId);
                                                                                }       
                                                             }
                                                 );
                                                                                    
                    
                    };
                    
   this.Add = function()
                {
                    
                     me = this;
                    var postBodyValue = "";
                        postBodyValue = "<request>";
                        postBodyValue += "<assetId>" + this.assetId + "</assetId>";
                        postBodyValue += "<functionName>add</functionName>";
                        postBodyValue += "<review>" + this.reviews + "</review>";
                        postBodyValue += "<rating>" + this.rating + "</rating>";
                        postBodyValue += "<uId>" + this.userId + "</uId>";
                        postBodyValue += "<destinationUrl>" + _constRnRUrl + "</destinationUrl>";
                        postBodyValue += "<watch>" + this.watching + "</watch>";
                        postBodyValue += "<urlReferer>" + encodeURIComponent(location.href) + "</urlReferer>";
                        postBodyValue += "</request>";
                      
                        ShowWait(true,this.reviewsElementId);
                        var requestCall = new Ajax.Request(proxyUrl
                                                            ,
                                                                {
                                                                    method: "POST",
                                                                    contentType: "text/xml",
                                                                    postBody: postBodyValue,
                                                                    onSuccess: function(req)
                                                                                {
                                                                                    //Success
                                                                                    me.getRnR();
                                                                                    toggleAdd("goAwayDiv");
                                                                                    setAlreadyReviewed("True");
                                                                                },
                                                                    onFailure: function(req)
                                                                                {
                                                                                    alert("We were unable to save you rating and review at this time.\nPlease try again later.");
                                                                                },
                                                                    onComplete: function(req)
                                                                                {
                                                                                    //alert("Completed.");
                                                                                    ShowWait(false, me.reviewsElementId);
                                                                                }
                                                                 }
                                                            );
                };
    this.Delete = function(messageID, ausID, assetID, ratingId)
                {
                    
                    if (confirm("Are you sure you want to delete your rating and review?"))
                    {
                     
                     this.assetID = assetID;
                     this.userID = ausID;
                     me = this;
                     
                        var postBodyValue = "";
                        postBodyValue = "<request>";
                        postBodyValue += "<assetId>" + assetID + "</assetId>";
                        postBodyValue += "<functionName>delete</functionName>";
                        postBodyValue += "<messageID>" + messageID + "</messageID>";
                        postBodyValue += "<ausID>" + ausID + "</ausID>";
                        postBodyValue += "<ratingID>" + ratingId + "</ratingID>";
                        postBodyValue += "<destinationUrl>" + _constRnRUrl + "</destinationUrl>";
                        postBodyValue += "</request>";
                      
                        ShowWait(true,this.reviewsElementId);
                        var requestCall = new Ajax.Request(proxyUrl
                                                            ,
                                                                {
                                                                    method: "POST",
                                                                    contentType: "text/xml",
                                                                    postBody: postBodyValue,
                                                                    onSuccess: function(req)
                                                                                {
                                                                                    //Success
                                                                                    me.getRnR();
                                                                                    toggleAdd("");
                                                                                    setAlreadyReviewed("False");
                                                                                },
                                                                    onFailure: function(req)
                                                                                {
                                                                                    alert("We were unable to delete you rating and review at this time.\nPlease try again later.");
                                                                                },
                                                                    onComplete: function(req)
                                                                                {
                                                                                    //alert("Completed.");
                                                                                    ShowWait(false, me.reviewsElementId);
                                                                                }
                                                                 }
                                                            );
                   }
                };
                    
    me = this;
}

                                                                
function review()
{
    this.reviewId = "";
    this.body = "";
    this.communityId = 0;
    this.creationDate = "";
    this.forumThreadId = 0;
    this.imageCount = 0;
    this.moderationValue = 0;
    this.modificationDate = "";
    this.parentMessageId = 0;
    this.subject = "";
}

function rating()
{
    this.ratingScore = 0;
}

function user()
{
    this.userId = "";
    this.email = "";
    this.emailVisible = "";
    this.name = "";
    this.nameVisible = "";
    this.username = "";
}


function createRatingsUI(score)
{
    //Returns the correct CSS class to display the correct Ratings UI
     var newCssClass = "ratingsBar ";
        
        if ((score >= .5) & (score < 1))
        {
            newCssClass += "halfStarRating";
        }
        else if ((score >= 1) & (score < 1.5))
        {
            newCssClass += "oneStarRating";
        }
        else if ((score >= 1.5) & (score < 2))
        {
            newCssClass += "oneHalfStarRating";
        }
        else if ((score >= 2) & (score < 2.5))
        {
            newCssClass += "twoStarRating";
        }
        else if ((score >= 2.5) & (score < 3))
        {
            newCssClass += "twoHalfStarRating";
        }
        else if ((score >= 3) & (score < 3.5))
        {
            newCssClass += "threeStarRating";
        }
        else if ((score >= 3.5) & (score < 4))
        {
            newCssClass += "threeHalfStarRating";
        }
        else if ((score >= 4) & (score < 4.5))
        {
            newCssClass += "fourStarRating";
        }
        else if ((score >= 4.5) & (score < 5))
        {
            newCssClass += "fourHalfStarRating";
        }
        else if ((score >= 5))
        {
            newCssClass += "fiveStarRating";
        }
        else if ((score == 0))
        {
            newCssClass += "zeroStarRating";
        }
    
    return newCssClass
}

function loadRating(id, rating)
{
    if((rating == null) || (rating == ""))
    {
        rating = 0;
    }
    
    if ((id != null) && (id != "") && ($("divRating_" + id) != null))
    {
	    $("divRating_" + id).className = createRatingsUI(rating);   
	}
}
function setAverageRating(average, total)
{
	if ($("avgRating") != null)
	{
		$("avgRating").className = createRatingsUI(average);
		$("totalRatings").innerHTML = "Based on " + total + " ratings";
	}
}
function setTotalReviews(total)
{
	if ($("totalReviewsCount") != null)
	{
		$("totalReviewsCount").innerHTML = "(" + total + ")";
	}
}

function saveRnR()
{
	//var r = new rnr();	
	var txt = $("reviewText").value;
	//txt = txt.replace("'","&apos;");
	
	if ((txt == "") | (txt == "Enter review here."))
	{
	    alert("Please enter your review.");
	    
	}
	else if (($("hidRatingScore").value == "") | ($("hidRatingScore").value == "0"))
	{
	    alert("Please enter your rating.");
	    
	}
	else
	{
	    _rnr.assetId = $("hidAssetId").value;
	    _rnr.reviews = txt;
	    _rnr.rating = $("hidRatingScore").value;
	    _rnr.userId = _currentUserId;
	    _rnr.watching = $("chkWatch").value;
	    _rnr.Add();
	}
	
}

   
function setRating(score)
{
    var newCssClass;
    
    switch (score)
    {
        case 1:
            {
               newCssClass = "oneStarRating";
                break;
            }
        case 2:
            {
                newCssClass = "twoStarRating";
                break;
            }
        case 3:
            {
                newCssClass = "threeStarRating";
                break;
            }
        case 4:
            {
                newCssClass = "fourStarRating";
                break;
            }
        case 5:
            {
                newCssClass = "fiveStarRating";
                break;
            }
    }
    
    $("hidRatingScore").value = score;
    
	var selectedCss = $(newCssClass).className + " currentRating";
	
	clearStars(newCssClass, selectedCss);
}
function clearStars(id, css)
{
    //Reset all of the stars
    $("oneStarRating").className = "oneStar noStars";
    $("twoStarRating").className = "twoStar noStars";
    $("threeStarRating").className = "threeStar noStars";
	$("fourStarRating").className = "fourStar noStars";
	$("fiveStarRating").className = "fiveStar noStars";
	
	//Apply the selected css
	$(id).className = css;
}


function clearText(ctl)
{
    var defaultText = "Enter your review here (no HTML, please).";

    if (ctl.value == defaultText)
    {
        ctl.value = "";
    }
    else if(ctl.value == "")
    {
        ctl.value = defaultText;
    }
}


function toggleAdd(x)
{
    //set the css of the add review ui
    $("divAddReview").className = x; //Input UI
	
	  //Set focus to an element upon completion if necessary
    if ((me.returnFocusElementID != "") & (x == ""))
    {
        document.getElementById(me.returnFocusElementID).focus();
        me.returnFocusElementID = "";
    }
}

function setAlreadyReviewed(hasReviewed)
{
//set the css of the add review ui
    var lnkText = "Write a Review";
    var cssName = "";
    var title = "Write a Review";
    
    if (hasReviewed == "true")
    {
        cssName = "reviewed";
        lnkText = "Already Reviewed";
        title = "You have already reviewed this event";
        
    }
    
    $("writeReview").className = cssName; //Write A Review link in the action box  
    $("lnkReview").innerHTML = lnkText;
	$("lnkReview").title = title;
	
}

function ShowWait(blnShow, ctl)
{
    
    var assetsList = $(ctl);
    var progressBar = $("divProgressBar");
    
    
    
    if (progressBar && assetsList)
    {
        // Position the progress bar relative to the list
        // Left is the offset, plus half the width of the table, minus half the width of the image
        var offset = assetsList.cumulativeOffset();
             
            
        if (blnShow) 
        {
            
            
            var left = assetsList.offsetLeft + 20;
            var top = assetsList.offsetTop; //IE
            
            //Get the top position of the waiting animation
            if (!_isIE)
            {
                top = assetsList.top; //FF
            }
            
            
            $(progressBar).setStyle
            (
                {
                    position: "relative", top: top + "px", left: left + "px"
                }
            );
            
            progressBar.show();   
            new Effect.Opacity(assetsList, { from: 1.0, to: 0.3, duration: 0 });
        }
        else 
        {
            progressBar.hide();    
            new Effect.Opacity(assetsList, { from: .3, to: 1.0, duration: 0 });
        }
    }
}

function showAllReviews(isFuture)
{
    _rnr.maxReviews = "-1";
    _rnr.getRnR(isFuture);
}
