var sThisUserID;
var bEventInFuture = false;
var bCurrFilterInFuture = false;
var bIMAReg = false;

var sEventID;
var sRootEventID;

var iRecsPerPage = 4;
var iPage = 1;
var iTotalPages = 0;
var iTotalRecs = 0;
var iEventReport_TotalRows = 0;

var sPreviousEventFilter = "";

var objCallBackFunction = null;

var sFriendsList=[];

function LoadEventRaceReportList(inURL, callbackFunction)
{
    gProcessAjaxGet(gURLNoCache(inURL), LoadEventRaceReports);    
    objCallBackFunction = callbackFunction;
}


function LoadEventRaceReports(inData, inError)
{	
	if (gProcessReportError(inError, true, "errormsg"))
		return;
	
	var data = $(inData);
	
	var sWork = "";
	
	var iRecordCount = 0;
	
	data.find("EventReport").each(function() {
		
		var sReportID = $(this).find("EventReportID").text();
		var sReportUserID = $(this).find("EventReportUserID").text();
		var sReportUserName = $(this).find("UserName").text();
		var sReportText = $(this).find("EventReportText").text();
		
		var sGender = $(this).find("Gender").text();
		var sAgeGroup = $(this).find("AgeFactor").text();
		var iAgeGroup = parseInt(sAgeGroup, 10);
		if (isNaN(iAgeGroup))
			iAgeGroup = 0;
		var sFinishTime = $(this).find("EventParticipantFinishTimeNum").text();
		var fFinishTime = parseFloat(sFinishTime);
		sFinishTime = gGetHHMMSSFromFloat(fFinishTime);
		
		var sPhotoID = $(this).find("UserPhotoImageID").text();
		var sPhotoExt = $(this).find("PhotoExtension").text();
		sParticipantPhotoURL = gMakeUserProfileAvatarEx( sReportUserID, sPhotoID, sPhotoExt, ( sGender == "Female" ? false : true ) );
		
		if (sReportText.length > 600)
			sReportText = sReportText.substring(0, 600) + "...";
		
		sReportText = gConvertTextForDisplay(sReportText) + '&nbsp;&nbsp;<a href="javascript: ViewRaceReportDetail(' + sReportID + ');">&#187; more</a>';
		
		
		var sFirstName = $(this).find("FirstName").text();
		var fRatingValue = parseFloat($(this).find("EventUserRatingRaw").text());				

		var sRatings = CreateRating(sFirstName, fRatingValue);
		
		var sRemovedByType = $(this).find("EventReportRemovedByType").text();
		var sReportDeleteDate = $(this).find("EventReportDeleteDate").text();
		if(sRemovedByType.length>0 && sReportDeleteDate.length>0)
        {
            sReportText = "Removed by " + sRemovedByType + '&nbsp;&nbsp;<a href="javascript: ViewRaceReportDetail(' + sReportID + ');">&#187; more</a>';;
        }
			
		sWork += '<div class="RaceReportEventViewReport">';
		sWork += MakeParticipantBlock( sReportUserID, sParticipantPhotoURL, sReportUserName, sGender, iAgeGroup, sFinishTime, 1 );
		sWork += '<div class="RaceReportEventViewReportBody">';
		sWork += '<div>';
		sWork += '<strong><a href="/users/' + sReportUserName.replace(gReplaceNamePattern, "") + '">' + sReportUserName + '</a> says:</strong>';
		sWork += '<br/>' + sReportText + '<br/><br/>'+ sRatings;
		sWork += '</div></div>\r\n';
		sWork += '</div>';
				
		if (iEventReport_TotalRows == 0)
		{
			var sTotalRows = $(this).find("TotalRows").text();
			iEventReport_TotalRows = parseInt(sTotalRows, 10);
			if (isNaN(iEventReport_TotalRows))
				iEventReport_TotalRows = 0;
		}//end if
		
		if (iRecordCount == 0)
		{
			iRecordCount = parseInt(sTotalRows, 10);
			if (isNaN(iRecordCount))
				iRecordCount = -1;
		}//end if
		
		//check if User already wrote report
		//if (gCheckUserId(sReportUserID)==true)
		if (sThisUserID==sReportUserID)
		{
			$("#RaceReport_AddReport").hide();
		}
		
	});//end each
	
	if (bIsIMAUser && sWork.length == 0 && !bCurrFilterInFuture)
		sWork = '<span class="EventNoRecordsFound">Be the first <a href="javascript:gParticipatedWizard(' + sPreviousEventFilter + ');">write a race report</a>.</span>';
	
	$("#EventRaceReports").html(sWork);
	
	SetRating();
	
	// Set up paging ===================================
	if (iRecordCount > -1)
		iTotalRecs = iRecordCount;
		 
	iTotalPages = 0 + parseInt((iTotalRecs / iRecsPerPage), 10);
	
	if ((iTotalRecs % iRecsPerPage) > 0)
		iTotalPages++;	// For those extra records on the last "page".
	
	if (iPage > iTotalPages)
		iPage = 1;
	
	if (iTotalPages > 1)
	{
		gMakePaging("PagingBlock", "GoToPage", iPage, iTotalPages, 10);
	}//end if
	
	
	if (objCallBackFunction != null)
	{
	    objCallBackFunction();
	}
	
}//end LoadEventRaceReports

function MakeParticipantBlock( inID, inPhotoURL, inName, inGender, inAgeFactor, inFinishTime, inEndBlock )
{
	var sRow = "";


	sRow = sRow + '<div id="ParticipantPhotoBlockCompact" style="vertical-align:top;"';	
	
	// This helps ensure the layout's relatively clean by introducing a block that's not a float:left
	if (inEndBlock == 0)
		sRow = sRow + ' class="End"';
	
	sRow = sRow + '><ul><li>';
		
	sRow = sRow + '<a href="/users/' + inName.replace(gReplaceNamePattern, "") + '">';
	sRow = sRow + '<img src="' + inPhotoURL + '" width="72" height="60"/></a><br/>';
	//sRow = sRow + inName + "</a><br/>";
	
	if (inGender == "1" || inGender == "Male")
		sRow = sRow + "Male";
	else
		sRow = sRow + "Female";
	
	var sRange = "";
	
	if (inAgeFactor < 4)
		sRange = "19 and under";
	else if (inAgeFactor > 14)
		sRange = "70+";
	else
		sRange = "" + (inAgeFactor * 5) + "-" + (((inAgeFactor+1) * 5) - 1);
		
	sRow = sRow + ", " + sRange + "<br/>";
	
	if (bEventInFuture)
		sRow = sRow + "Est. Finish Time ";
	else
		sRow = sRow + "Finish Time ";
	
	sRow = sRow + inFinishTime;

	if (sThisUserID != inID && IsFriend(inID, sFriendsList)==false)
	//if (sThisUserID != inID && inID.length>0)
	{
	    sRow = sRow + '<br/><a href="/account/MyFriendsSearch.aspx?fFriendID=' + inID
		    + '&fFriendName=' + inName + '">Add as friend</a>';
	}
	
	sRow= sRow + '</li></ul></div>';

	return sRow;

}//end MakeParticipantBlock

function CreateRating(inFirstName, inRatingValue)
{
    if (isNaN(inRatingValue))
		inRatingValue = 0.0;
	
	var sRatings = "<div class='RaceReport_RatingSection'><div class='RaceReport_RatingOwner'>" + inFirstName + " rated this event:</div>";
	
	
	sRatings += '<div  class="RaceReport_RatingStars"><span class="StarRating">'			
	for(var i=1; i < 6; i++)
	{
		sRatings += '<input type="radio"' + (inRatingValue >= (i * 1.0) ? ' checked="checked" ' : '' ) + '/>';
	}//end for
	
	sRatings += "</span></div></div>";
	
	return sRatings;
}


function SetRating()
{
    $(".StarRating").stars({
		disabled: true
	});
	
//	$(".ui-stars-star").addClass("ui-starssmall-star").removeClass("ui-stars-star");
//	$(".ui-stars-cancel").addClass("ui-starssmall-cancel").removeClass("ui-stars-cancel");
//	
//	$(".ui-stars-cancel-disabled").addClass("ui-starssmall-cancel-disabled").removeClass("ui-stars-cancel-disabled");
//	$(".ui-stars-star-disabled").addClass("ui-starssmall-star-disabled").removeClass("ui-stars-star-disabled");
//	$(".ui-stars-star-hover").addClass("ui-starssmall-star-hover").removeClass("ui-stars-star-hover");
//	$(".ui-stars-cancel-hover").addClass("ui-starssmall-cancel-hover").removeClass("ui-stars-cancel-hover");
//	$(".ui-stars-star-on").addClass("ui-starssmall-star-on").removeClass("ui-stars-star-on");
}

function ViewRaceReportDetail(inReportID, inPrev)
{
	var sURL = "/events/EventReportDetail.aspx?fRID=" + inReportID;
	if (sEventID!=null && sEventID.length>0)
		sURL += "&fEID="+sEventID;
	//var sPrev="<%=IMASecurity.GetCleanLong(Request["fRID"])%>";
	//debugger;
	if (inPrev!=null && inPrev!="0")
	{
		sURL += '&fPrev='+inPrev;
	}
	else
	{
		var id=$("#EventDateFilters a.active").attr("id");
		if (id!=null && id!='All')
			sURL += '&fPrev='+id;
	}
	
	document.location.href = gURLNoCache(sURL);
	
}//end ViewRaceReportDetail


function SetNavigationTabs(){
    var sHTML = '<li><a href="/events/EventOverview.aspx?fEID='+sRootEventID+'">Overview</a></li>';
    sHTML += '<li><a href="/events/EventDetails.aspx?fEID='+sRootEventID+'">Event Details</a></li>';
    sHTML += '<li><a href="/events/EventParticipants.aspx?fEID='+sRootEventID+'">Participants</a></li>';
    sHTML += '<li id="RaceResultsSubNav" style="display: none;"><a href="/events/EventRaceResults.aspx?fEID='+sRootEventID+'">Race Results</a></li>';
    sHTML += '<li><a class="TabOn" href="/events/EventRaceReports.aspx?fEID='+sRootEventID+'">Race Reports</a></li>';
    sHTML += '<li><a href="/events/EventMedia.aspx?fEID='+sRootEventID+'">Photos</a></li>';
    $("#EventNavigationTabs").html(sHTML);
}

function LoadUserFriends(inData, inError)
{
	if (gProcessReportError(inError, true, "errormsg"))
		return;
	
	var data = $(inData);
	var iCounter = 0;
	
	data.find("Friend").each(function() 
	{
		sFriendsList[iCounter++] = $(this).find("UserID").text();
	});//end each
}//end LoadUserFriends

function IsFriend(inID, InFriendsID)
{
	var x;
	for (x in InFriendsID)
	{
		if (inID==InFriendsID[x])
			return true;
	}
	return false;
}

function RemoveReport(ReportID)
{
    if(!confirm("Are you sure you want to remove this race report?"))
    {
        return;
        
    }//end if 
    
    var sURL = gURLNoCache("/events/EventService.asmx/DeleteReport");
    var data = { ReportID : ReportID }
    
    gDoAjaxJSON(sURL, $.toJSON(data), RemoveReportCallback, null);    

}//end RemoveReport

function RemoveReportCallback(response)
{
    var responseInfo = $.evalJSON(response.d);
    if(responseInfo.Success)
    {
    	gProcessAjaxGetSync(gURLNoCache("/data/events/EventGetReports.aspx?fRRID=" + sReportID + "&fPrev=" + sPrev), LoadReportData, true);
    
    }//end if
    else
    {
        alert(responseInfo.Message);
        
    }//end else

}//end RemoveReportCallback

function RestoreReport(ReportID)
{
    if(!confirm("Are you sure you want to restore this race report?"))
    {
        return;
        
    }//end if 
    
    var sURL = gURLNoCache("/events/EventService.asmx/RestoreReport");
    var data = { ReportID : ReportID }
    
    gDoAjaxJSON(sURL, $.toJSON(data), RestoreReportCallback, null);    

}//end RestoreReport

function RestoreReportCallback(response)
{
    var responseInfo = $.evalJSON(response.d);
    if(responseInfo.Success)
    {
    	gProcessAjaxGetSync(gURLNoCache("/data/events/EventGetReports.aspx?fRRID=" + sReportID + "&fPrev=" + sPrev), LoadReportData, true);
    
    }//end if
    else
    {
        alert(responseInfo.Message);
        
    }//end else

}//end RestoreReportCallback