var ratingVersion = "1.0"
var tpRatingsService = "http://ratings.community.theplatform.com/rating/";
var tpTotalRatingsService = "http://totalratings.community.theplatform.com/totalrating/";
var myRating = 0;

var favoriteURIs = new Array();
var favoritesCtx = "favorites";
var hasFavoriteList = false;
var favoriteListURI;
var favoriteURIs;
var tpFavoritesCategoryName = "Favorites";
var currentCategory;

var playlistsCtx = "playlist";

var commentSchema = "1.0";

if (window.addEventListener){
	window.addEventListener("load", initCT, true);
} else if (window.attachEvent){
	window.attachEvent("onload", initCT );
}

function initCT(){
	Utellit_loadFavorites();
}

/**************************
	SECURITY HANDLER
**************************/
function Utellit_canPerformAction(contentID, action) {
	//alert("Utellit_canPerformAction: " + contentID + ", " + action);
	if(checkPermissions()){
		return 1;
	} else {
		return 0;
	}
}

/**************************
	RESPONSE HANDLER
**************************/
function Utellit_handleASResponse(methodName,response){
	var myJSONText = JSON.stringify(response, function (key, value) {
   		return value;
	});
	handleResponse(methodName,myJSONText);
	//alert(myJSONText);		
}

function checkPermissions(){
	var reason = canPerformWithReason("community");
	if(reason && (reason != "") && (reason!="undefined") ){
		if(reason == "S"){
			location.href="/signIn.do?referer="+location.href;
		} else if (reason=="E") {
			location.href="/fragments/security/emailNotConfirmed.jsp";
		} else if (reason=="P") {
			location.href="/fragments/security/profileNotApproved.jsp";
		}
	} else {
		return true;
	}
}

/**************************
	TAGS
**************************/
function Utellit_addTag(tag, contentID){
	if(checkPermissions()){
		tpCommunityManager.addTag(getObjectURI(contentID,"media"),tag,"1.0",tpTagDataServicePrefix,null);
	}
}

/**************************
	RATING
**************************/
function Utellit_getAggregateRating(contentID){
	//alert("call Utellit_getAggregateRating");
	tpCommunityManager.getTotalRating(getObjectURI(contentID,"media"),ratingVersion,tpTotalRatingsService, handleGetTotalRating);
}
function handleGetTotalRating(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {
		Utellit_handleASResponse("Utellit_getAggregateRating",response);
	}
}

function Utellit_setRating(contentID, rating){
	//alert("Call add rating for video " + contentID);
	if(checkPermissions()){
		tpCommunityManager.addRating(getObjectURI(contentID,"media"),rating,ratingVersion,tpRatingsService, handleAddRateResponse);
	}
}
function handleAddRateResponse(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {
		Utellit_handleASResponse("Utellit_setRating",response);
	}
}

function Utellit_hasAlreadyRated(contentID) {
	Utellit_getRating(contentID);
}

function Utellit_getRating(contentID){
	//alert("Call get rating for video " + contentID);
	tpCommunityManager.getRating(getObjectURI(contentID,"media"),ratingVersion,tpRatingsService, handleGetRateResponse);
}
function handleGetRateResponse(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {
		Utellit_handleASResponse("Utellit_getRating",response);
	}
}
/**************************
	COMMENTS
**************************/
function Utellit_getComments(contentID,indexStart,indexEnd){
	//alert("call Utellit_getComments");
	var objectURI = getObjectURI(contentID,"media");
	tpCommunityManager.getComments(objectURI,commentSchema,tpCommentsDataServicePrefix,handleGetCommentsResponse,indexStart,indexEnd);
}
function handleGetCommentsResponse(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {
		if(typeof response.items != "undefined") {
			var totalCommentCount = response.items.length;
			//alert("total comments " + totalCommentCount);
		}
	}
}


function Utellit_setComment(contentID, comment){
	if(checkPermissions()){
		Utellit_setCommentWithCallback(contentID, comment, handleSetCommentResponse);
	}
}

function Utellit_setCommentWithCallback(contentID, comment, callback){
	//alert("call Utellit_setComment");
	var objectURI = getObjectURI(contentID,"media");
	tpCommunityManager.addComment(objectURI,uu,comment,null,commentSchema,tpCommentsDataServicePrefix,callback);
}

function handleSetCommentResponse(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {
		//TODO any notification to AS ? (response.ID, response.approved)
		//alert("comment added");
	}
}

function Utellit_deleteComment(commentURI){
	tpCommunityManager.addComment(commentURI,commentSchema,tpCommentsDataServicePrefix,handleDeleteCommentResponse);
}
function handleDeleteCommentResponse(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {
	}	
}

function Utellit_hasAlreadyCommented(contentID){
	//alert("call Utellit_hasAlreadyCommented");
	var objectURI = getObjectURI(contentID,"media");
	tpCommunityManager.getUserCommentsAboutContent(uuSelfID,objectURI,commentSchema,tpCommentsDataServicePrefix,handleHasAlreadyCommentedResponse);
}
function handleHasAlreadyCommentedResponse(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {
		//TODO set response to AS callback
		if(typeof response.items != "undefined") {
			var totalCommentCount = response.items.length;
			var message = "total comments " + totalCommentCount;
			for(i=0;i<response.items.length;i++){
				message = message + "\n comment [approved,content] " + response.items[i].approved + "," + response.items[i].text;
			}
			//alert(message);
		} else {
			//alert("total comments 0");
		}	
	}	
}


/**************************
	PLAYLISTS
**************************/
function Utellit_createPlaylist(contentID, playlistName, featured) {
	if(checkPermissions()){
		//alert("call Utellit_createPlaylist,  featured " + featured);
		var objectURI = getObjectURI(contentID,"media");
		var description = "";
		if(featured){
			description = "featured";
			//alert("add to playlist with token " + tpCommunityManager.getToken());
			TPCommunityService.clearFeaturedStatus(tpCommunityManager.getToken(), {callback : function(status) { 
				tpCommunityManager.addUserPlaylist( playlistName, description, playlistsCtx, [objectURI],"1.0", tpUserListsDataServicePrefix, handlePlaylistListResponse)
			} } );		
		} else {
			tpCommunityManager.addUserPlaylist( playlistName, description, playlistsCtx, [objectURI],"1.0", tpUserListsDataServicePrefix, handlePlaylistListResponse)
		}
	}
}


function handlePlaylistListResponse(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {	
		Utellit_handleASResponse("Utellit_createPlaylist",response);
	}
}

function Utellit_getPlaylists(){
	//alert("get playlists");
	tpCommunityManager.getUserListWithSpecifiedFields("ID,itemIDs,name,addedByUserID",playlistsCtx, "1.0", tpUserListsDataServicePrefix, receivePlaylists);
}
function receivePlaylists(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {
		Utellit_handleASResponse("Utellit_getPlaylists",response);
	}
}

function Utellit_removePlaylist(playlistURI){
	Utellit_removePlaylistWithCallback(playlistURI,null);
}
function Utellit_removePlaylistWithCallback(playlistURI,callback){
	tpCommunityManager.deleteUserList( playlistURI, "1.0", tpUserListsDataServicePrefix, callback);
}

var pl_tmp_contentID;
var pl_tmp_playlistURI;
var pl_tmp_removeFromPlaylistWithCallback;

function Utellit_addToPlaylist(contentID, playlistURI){
	if(checkPermissions()){
		//alert("add to playlist ... " + playlistURI + " " + contentID)
		pl_tmp_playlistURI = playlistURI;
		pl_tmp_contentID = getObjectURI(contentID,"media");
		tpCommunityManager.getUserListWithSpecifiedFields("ID,itemIDs,name",playlistsCtx, "1.0", tpUserListsDataServicePrefix, handleAddToPlaylist);
	}
}
function handleAddToPlaylist(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {	
		if(response.items){
			for(i=0;i<response.items.length;i++){
				//alert("update playlist, check " + response.items[i].ID + " against " + pl_tmp_playlistURI);
				if(response.items[i].ID==pl_tmp_playlistURI){
					itemIDs = [pl_tmp_contentID].concat(response.items[i].itemIDs);
					//alert("update playlist " + response.items[i].ID + " set item ids " + itemIDs);
					Utellit_updatePlaylist(response.items[i].ID,response.items[i].name,itemIDs);
				}
			}
		}
	}	
}


function Utellit_removeFromPlaylist(playlistURI, contentID){
	Utellit_removeFromPlaylistWithCallback(playlistURI, contentID, Utellit_handleRemoveFromPlaylist);
}

function Utellit_removeFromPlaylistWithCallback(playlistURI, contentID, callback){
	pl_tmp_playlistURI = playlistURI;
	pl_tmp_contentID = getObjectURI(contentID,"media");
	pl_tmp_removeFromPlaylistWithCallback = callback;
	tpCommunityManager.getUserListWithSpecifiedFields("ID,itemIDs,name",playlistsCtx, "1.0", tpUserListsDataServicePrefix, Utellit_handleRemoveFromPlaylist);
}

function Utellit_handleRemoveFromPlaylist(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {	
		//alert("response items ... " + response.items);
		if(response.items){
			for(i=0;i<response.items.length;i++){
				if(response.items[i].ID==pl_tmp_playlistURI){
					itemIDs = jQuery.grep(response.items[i].itemIDs, function (a) { return a.indexOf(pl_tmp_contentID) == -1; });					
					//alert("update playlist " + response.items[i].ID + " set item ids " + itemIDs);
					Utellit_updatePlaylist(response.items[i].ID,response.items[i].name,itemIDs);
				}
			}
		}
	}
}

function Utellit_updatePlaylist(playlistURI, name, itemIDs){
	var backCallback = handleUpdatePlaylist;
	if(pl_tmp_removeFromPlaylistWithCallback != null){
		backCallback = pl_tmp_removeFromPlaylistWithCallback;
		pl_tmp_removeFromPlaylistWithCallback = null;
	}
	tpCommunityManager.updateUserList( playlistURI, name,playlistsCtx, itemIDs, "1.0", tpUserListsDataServicePrefix, backCallback)
}
function handleUpdatePlaylist(response){
}

/**************************
	FAVORITES
**************************/
function Utellit_setAsFavorite(contentID){
	if(checkPermissions()){
		//alert("call Utellit_setAsFavorite with contentID " + contentID);
		if( (contentID!="undefined") && (contentID!="") && (!Utellit_isFavorite(contentID)) ) {
			var objectURI = getObjectURI(contentID,"media");
			favoriteURIs = [ objectURI ].concat( favoriteURIs );
			// update persistence.
			if ( hasFavoriteList ) {
				tpCommunityManager.updateUserList( favoriteListURI, tpFavoritesCategoryName,favoritesCtx, favoriteURIs, "1.0", tpUserListsDataServicePrefix, handleFavoriteListResponse)
			} else {
				tpCommunityManager.addUserList( tpFavoritesCategoryName, favoritesCtx, favoriteURIs,"1.0", tpUserListsDataServicePrefix, handleFavoriteListResponse)
			}
		} else {
			//alert("already in favorites");
		}
	}
}
function handleFavoriteListResponse(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {	
		Utellit_handleASResponse("Utellit_setAsFavorite",response);
	}
}

function Utellit_isFavorite(contentID){
	//alert("call Utellit_isFavorite");
	var objectURI = getObjectURI(contentID,"media");
	var inFavorites = getFavoritesAsURIs( objectURI ).length != 0;
	return inFavorites;
}

function Utellit_removeFromFavorites(contentID){
	Utellit_removeFromFavoritesWithCallback(contentID,handleFavoriteListResponse);
}

function Utellit_removeFromFavoritesWithCallback(contentID,callback){
	//alert("call Utellit_removeFavorite " + contentID);
	var objectURI = getObjectURI(contentID,"media");
	favoriteURIs = jQuery.grep(favoriteURIs, function (a) { return a.indexOf(objectURI) == -1; });
	// update persistence.
	if ( hasFavoriteList ) {
		if( !(favoriteURIs) || (favoriteURIs=="") || (favoriteURIs=="undefined") ){
			tpCommunityManager.deleteUserList( favoriteListURI, "1.0", tpUserListsDataServicePrefix, callback);
			favoriteURIs = new Array();
			hasFavoriteList = false;
		} else {
			tpCommunityManager.updateUserList( favoriteListURI, tpFavoritesCategoryName,favoritesCtx, favoriteURIs, "1.0", tpUserListsDataServicePrefix, callback)
		}			
	}
}

function Utellit_loadFavorites(){
	tpCommunityManager.getUserList(favoritesCtx, "1.0", tpUserListsDataServicePrefix, receiveFavoritesList);
}
function receiveFavoritesList(response){
	if(tpCommunityManager.isException(response)){
		handleException(response);
	} else {	
		if ( (response) && (response.items.length > 0) ) {
			hasFavoriteList = true;
			favoriteListURI = response.items[0].ID;
			favoriteURIs = response.items[0].itemIDs;
		} else {
			hasFavoriteList = false;
			favoriteURIs = new Array();
		}
		
		//alert("Has favorites " + hasFavoriteList + " uri " + favoriteURIs);
		//alert("Has favorites " + hasFavoriteList + " uri " + favoriteURIs + " id " + response.items[0].ID);
		if ( currentCategory == tpFavoritesCategoryName ) {
			updateReleaseModel();
		}
	}
}

function updateReleaseModel() {
	var IDArray = getFavoritesAsMediaIDs();
	var query = "query=ContentIDs|";
	if ( IDArray.length > 0 ) {
		for ( var i = 0; i < IDArray.length; i++) {
			query = query + IDArray[i].substring(IDArray[i].lastIndexOf("/")+1) + ",";
		}
		// Remove the extra comma at the end.
		query = query.substring(0, query.length - 1);
	} else {
		query = query + "0";
	}
	tpController.refreshReleaseModel("", "", null, null, null, [query]);
}


/*
* Return back an  array of object URIs. Returns all the URIs if the filterPrefix param is null.
*/
function getFavoritesAsURIs( filterPrefix ) {
	if ( filterPrefix != null && favoriteURIs && favoriteURIs.length > 0) {
		var returnArray = jQuery.grep(favoriteURIs, function (a) { return a.indexOf(filterPrefix) == 0; });
		return returnArray;
	} 
	return favoriteURIs;
}
/*
* Return back an  array of content IDs for Media objects in the currently loaded favorites list.
*/
function getFavoritesAsMediaIDs() {
	return getFavoritesAsURIs( tpMediaDataServicePrefix + tpMediaDataServicePath );
}
	
function handleException(response){
	var errorType = response.type;
	var errorMessage = response.message;
	//TODO call ActionScript error handler
	//so far alert exception
	alert("Exception occured : " + errorType + " " + errorMessage);	
}

function handleCategoryChange(evt) {
	var oldCategory = currentCategory;
	currentCategory = evt.data;
	//alert("category changed ... " + currentCategory);
	if (currentCategory == tpFavoritesCategoryName ) {
		updateReleaseModel();
	}
}

function getObjectURI(contentID,type){
	if(type=="media"){
		return tpMediaDataServicePrefix + tpMediaDataServicePath + "/" + contentID;
	}
	return contentID;
}

