
	function isAlreadyVotedComment(id) {
	    cookcomvoted = getCookie(CommentClient.commentConfig.nameCookieVoted);
	    if(cookcomvoted=='' | cookcomvoted == undefined) { return false; } 
	    else { return cookieContainId(cookcomvoted, id); }
	 }
  

	function cookieContainId(cookieval, id) {
	    vals = cookieval.split(",");
		for(ival=0; ival<vals.length; ival++)	  {
		    val = vals[ival];
		    if(val == id) {
	        	return true;
	      	}
		}    
	    return false;
	}


	function callback_sendvote_comment(jsonResp) {
        if(jsonResp.isError==false) {
        	lidcommario = CommentClient.lastVoteCall.commentarioId;
        	lidcomm = CommentClient.lastVoteCall.commentoId;
            CommentClient.commentViewer.showVoteMessage(lidcommario, lidcomm, "Grazie per aver votato !");
      	} else {
      		CommentClient.commentViewer.showErrorMessage(jsonResp.code, jsonResp.message);
      	}
      	
      	// create id commento
      	idcom = CommentClient.lastVoteCall.commentarioId + "" + CommentClient.lastVoteCall.commentoId;
      	// read the cookie containing the ids already voted
      	cookcomvoted = getCookie(CommentClient.commentConfig.nameCookieVoted);
      	// if the cookie doesn't exist create it 
      	if(cookcomvoted=='' | cookcomvoted == undefined) {
        	createCookie(CommentClient.commentConfig.nameCookieVoted, idcom);
        	// if the cookie exist add the new id 
      	} else {
        	if(!cookieContainId(cookcomvoted, idcom)) {
          		newval = cookcomvoted + ',' + idcom;
          		createCookie(CommentClient.commentConfig.nameCookieVoted, newval);
        	}   
      	} 
    }
      	
      	
    function callback_ui(jsonResp) {
        if(jsonResp.isError==false) {
            for(j=0; j<jsonResp.users.length; j++) {
      	    	CommentClient.usersInfo[CommentClient.usersInfo.length] = jsonResp.users[j];
      	    }
      	}
      	CommentClient.commentViewer.showUserInfo(CommentClient);
	} 


	function callback(jsonResp) {
        // IF RESPONSE IS ERROR SHOW MESSAGE
        if(jsonResp.isError!=false) {
      		if(CommentClient.commentViewer!=null) {
    			CommentClient.commentViewer.showErrorMessage(jsonResp.code, jsonResp.message);
    		}
    	// IF SERVICE DIDN'T RAISE EXCEPTION	
	    } else {
	    	
	    	// NOTIFY COMMUNITY (IF NECESSARY) IF A NEW PROFILE OR CHANNEL COMMENT HAS BEEN ADDED
	    	if(CommentClient.islastcallsave) {
	        	request = "http://community.yalp.alice.it/services/";
	        	if(CommentClient.typeCommentario==CommentClient.PROFILE_TYPE) {
	        		request = request + "NotificaCommentoProfilo?";
	        	}
	        	if(CommentClient.typeCommentario==CommentClient.CHANNEL_TYPE) {
	        		request = request + "NotificaCommentoCanale?";
	        	}
	        	yalpnck = getCookie("YALP-NCK");
	        	nicks = yalpnck.split(":");
	        	if( (nicks!=null) && (nicks.length > 0) ) {
	        		request = request + "nickname="+nicks[0]+"&";
					request = request + "idcommentario="+CommentClient.getIdCommentario();
					aObj = new JSONscriptRequest(request);
					aObj.buildScriptTag();
				 	aObj.addScriptTag();
	        	}	
	        }
	    
	    	// CLEAR COMMENTS AND FILTERED COMMENTS
	    	CommentClient.comments = new Array();
	    	CommentClient.commentsFiltered = new Array();
	    
	    	// GET NUM TOTAL COMMENTI / START AND END INDEX BASED ON THE CALL
        	CommentClient.numTotalComments = jsonResp.numTotal;
        	
        	// FOR EACH DOWNLOADED COMMENT 
        	for(i=0; i<jsonResp.numTotal; i++){
        	    comment = jsonResp.comments[i];
        	    // GET NICK OF COMMENT
        	    unick = comment.userNick;
        	    if( (unick==null) || (unick=='') || (unick=='null') ) {
                	unick = comment.userName;
              	}
              	// CHECK IF THE USER INFO HAS ALREADY BEEN DOWNLOADED
        	    existing = false;
        	    for(z=0; z<CommentClient.usersInfo.length; z++) {
        	    	if(CommentClient.usersInfo[z].nick == unick) {
        	    		existing = true;
        	    		break;
        	    	}
        	    }
        	    // CHECK IF THE USER INFO HAS ALREADY BEEN REQUESTED
        	    requested = false;
        	    if(!existing) {
	        	    for(z=0; z<CommentClient.userNickToRequest.length; z++) {
	        	    	if(CommentClient.userNickToRequest[z] == unick) {
	        	    		requested = true;
	        	    		break;
	        	    	}
	        	    }
	        	}
	        	// IF USER INFO DOESN'T EXIST OR HASN'T BEEN ADDED TO DOWNLOAD LIST THEN ADD IT !
        	    if( !existing && !requested ) {
        	    	CommentClient.userNickToRequest[CommentClient.userNickToRequest.length] = unick;
        	    }
				// ADD COMMENT TO CLIENT
        		CommentClient.comments[i] = comment;
        	}
			
			// CALCULATED FILTERED COMMENTS
			countFiltered = 0;
	        for(ind=0; ind<CommentClient.comments.length; ind++) {
	        	comn = CommentClient.comments[ind];
	        	if(  !comn.spam  && (comn.vote>-4) ) {
	        		CommentClient.commentsFiltered[countFiltered] = comn;
	        		countFiltered ++;
	        	}
	        }
	        CommentClient.numFilteredComments = countFiltered;
	        	        
	        // SHOW COMMENTS
	        CommentClient.commentViewer.showComments(CommentClient);
      	}   
	} 


	function doCall_SendVote_Comment(idcommentario, idcommento, voto) {
		request = CommentClient.commentConfig.urlGetComments;
        request = request + "?MESSAGE=RECORD_VOTE"; 
        request = request + "&ID_COMMENTARIO=" + idcommentario; 
        request = request + "&ID_COMMENTO=" + idcommento;   
        request = request + "&VOTE=" + voto;      
        request = request + "&OUTPUT=json"; 
        request = request + "&CALLBACK=callback_sendvote_comment"; 
		aObj = new JSONscriptRequest(request);
		aObj.buildScriptTag();
	 	aObj.addScriptTag();
	}

	
	function doCall_SetSpam(cc, idcommentario, idcommento) {
		CommentClient.userNickToRequest = new Array();
		CommentClient.islastcallsave = false;
		request = cc.commentConfig.urlGetComments;
        request = request + "?MESSAGE=SIGN_AS_SPAM"; 
        request = request + "&ID_COMMENTARIO=" + idcommentario; 
        request = request + "&ID_COMMENTO=" + idcommento;          
        request = request + "&OUTPUT=json"; 
        request = request + "&CALLBACK=callback"; 
		aObj = new JSONscriptRequest(request);
		aObj.buildScriptTag();
	 	aObj.addScriptTag();
	}


	function doCall_GetComments(cc) {        
        CommentClient.userNickToRequest = new Array();
		CommentClient.islastcallsave = false;
        request = cc.commentConfig.urlGetComments;
        request = request + "?MESSAGE=GET_COMMENTS"; 
        request = request + "&ID_COMMENTARIO=" + cc.idCommentario; 
        request = request + "&OUTPUT=json"; 
        request = request + "&CALLBACK=callback"; 
		aObj = new JSONscriptRequest(request);
		aObj.buildScriptTag();
	 	aObj.addScriptTag();
	}
	
	function doCall_SaveComment(title, body, cc) {           
        if(cc.commentConfig.maxLengthComment>0) {
          if(body.length > cc.commentConfig.maxLengthComment) {
            cc.commentViewer.showErrorSizeComment();
            return;
          }
        }
        CommentClient.userNickToRequest = new Array();
		CommentClient.islastcallsave = true;
        request = cc.commentConfig.urlSaveComment;
        request = request + "?MESSAGE=SAVE_COMMENT"; 
        request = request + "&ID_COMMENTARIO=" + cc.idCommentario; 
        request = request + "&COMMENT_TITLE=" + escape(title); 
        body = encodeURI(body);
        body = body.replace(/&/g, "%26");
        body = body.replace(/#/g, "%23");
        body = body.replace(/\+/g, "%2B");
        request = request + "&COMMENT_BODY=" + body; 
        request = request + "&OUTPUT=json"; 
        request = request + "&CALLBACK=callback"; 
        typetoset = CommentClient.getTypeCommentario();
        if( (typetoset!=CommentClient.GENERAL_TYPE) && (typetoset!=CommentClient.PROFILE_TYPE) && (typetoset!=CommentClient.CHANNEL_TYPE)  ) {
        	typetoset = CommentClient.GENERAL_TYPE;
        }
        request = request + "&TYPE="+typetoset; 
		aObj = new JSONscriptRequest(request);
		aObj.buildScriptTag();
	 	aObj.addScriptTag();
	}
	
	
	function doCall_DeleteComments(commIds, cc) {     
		CommentClient.userNickToRequest = new Array(); 
		CommentClient.islastcallsave = false;
        request = cc.commentConfig.urlDeleteComment;
        request = request + "?MESSAGE=DELETE_COMMENTS"; 
        for(i=0; i<commIds.length; i++) {
        	request = request + "&ID_COMMENTO=" + commIds[i];  
        }
        request = request + "&ID_COMMENTARIO=" + cc.idCommentario;  
        request = request + "&OUTPUT=json"; 
        request = request + "&CALLBACK=callback"; 
		aObj = new JSONscriptRequest(request);
		aObj.buildScriptTag();
	 	aObj.addScriptTag();
	}


	function doCall_GetUserInfo(cc) {
	    if(CommentClient.userNickToRequest.length!=0) {
	    	request = cc.commentConfig.urlGetUserInfo;
        	request = request + "?MESSAGE=GET_USERS_INFO"; 
            for(j=0; j<CommentClient.userNickToRequest.length; j++) {
            	request = request + "&USER_NICK=" + CommentClient.userNickToRequest[j]; 
            }
	        request = request + "&OUTPUT=json"; 
	        request = request + "&CALLBACK=callback_ui";
	        CommentClient.userNickToRequest = new Array(); 
            aObj = new JSONscriptRequest(request);
			aObj.buildScriptTag();
		 	aObj.addScriptTag();
		}
	}

	
	function CommentLastSaveCall() {
		this.title = "";
		this.body = "";
	}
   
    function CommentLastDeleteCall() {
    	this.commentIds = null;
    }
    
    function CommentLastVoteCall() {
    	this.commentarioId = null;
		this.commentoId = null;
		this.voto = null;
    }
    
    function CommentLastSpamCall() {
   		this.commentarioId = null;
		this.commentoId = null;
    }
		

    
    
    function CommentClientFunct(){
		
		this.commentViewer = new CommentViewer();
		this.commentConfig = CommentConfig;
		this.idCommentario = 0;
		this.comments = new Array();
		this.commentsFiltered = new Array();
		this.usersInfo = new Array();
		this.userNickToRequest = null;
		this.numTotalComments = 0;
		this.numFilteredComments = 0;
		this.lastSaveCall = null;
		this.lastDeleteCall = null;
		this.lastVoteCall = null;
		this.lastSpamCall = null;
		this.nameForComments = '';
		this.filterComment = true;
		this.islastcallsave = false;
		
		this.GENERAL_TYPE = 0;
		this.PROFILE_TYPE = 1;
		this.CHANNEL_TYPE = 2;
		
		this.typeCommentario = this.GENERAL_TYPE;
		
		// setter and getter idCommentario
		this.setIdCommentario = function(idComm) {
			this.idCommentario = idComm;
		}
	    this.getIdCommentario = function() {
			return this.idCommentario;
		}
        
        // setter and getter typeCommentario
        this.setTypeCommentario = function(type) {
        	this.typeCommentario = type;
        }
     	this.getTypeCommentario = function(type) {
     		return this.typeCommentario;
     	}
     	
     	// setter and getter filterComment
        this.setFilterComment = function(filter) {
        	this.filterComment = filter;
        }
     	this.getFilterComment = function() {
     		return this.filterComment;
     	}
     	
     
	     // setter and getter typeCommentario
	     this.setNameForComments = function(name) {
	        this.nameForComments = name;
	     }
	     this.getNameForComments = function() {
	        return this.nameForComments;
	     }
     
		this.getPageComments = function(pageIndex, pageSize) {
			this.commentViewer.showLoadingMessage();
			// for retro-compatibility reasons the method is still used 
			// but internally it call the other method that download all comments  
			// doCall_GetComments(this, pageIndex, pageSize, true);
			doCall_GetComments(this);
		}
		

		this.getAllComments = function() {
			this.commentViewer.showLoadingMessage();
			doCall_GetComments(this);
		}
		
		
		this.getUserInfo = function() {
			doCall_GetUserInfo(this);
		}
		
		this.saveComment = function(title, body) {
			if(body.blank()) {
				this.commentViewer.showEmptyCommentErrorMessage();
				return;
			}
			if(body == "Inserisci commento") {
				this.commentViewer.showEmptyCommentErrorMessage();
				return;
			}
			this.commentViewer.showCheckLoginMessage();
			this.lastSaveCall = new CommentLastSaveCall();
			this.lastSaveCall.title = title;
			this.lastSaveCall.body = body;
			AAClient.isAuthenticated('CommentClient.authenticatedCallback()', 'CommentClient.notauthenticatedCallback()');
		}
		
		
		
		this.deleteComments = function(commIds) {
			this.commentViewer.showCheckLoginMessage();
			this.lastDeleteCall = new CommentLastDeleteCall();
			this.lastDeleteCall.commentIds = commIds;
			AAClient.isAuthenticated('CommentClient.authenticatedForDeleteCallback()', 'CommentClient.notauthenticatedCallback()');
		}
		
		this.authenticatedCallback = function() {
      		this.commentViewer.closeCheckLoginMessage();
			this.commentViewer.showLoadingMessage();
			doCall_SaveComment(this.lastSaveCall.title, this.lastSaveCall.body, this);
		}
		
		this.authenticatedForDeleteCallback = function() {
      		this.commentViewer.closeCheckLoginMessage();
			this.commentViewer.showLoadingMessage();
			doCall_DeleteComments(this.lastDeleteCall.commentIds, this);
		}
		
		this.authenticatedForVoteCallback = function() {
      		this.commentViewer.closeCheckLoginMessage();
			doCall_SendVote_Comment(this.lastVoteCall.commentarioId, this.lastVoteCall.commentoId, this.lastVoteCall.voto);
		}
		
		this.authenticatedForSpamCallback = function() {
      		this.commentViewer.closeCheckLoginMessage();
      		this.commentViewer.showLoadingMessage();
      		doCall_SetSpam(this, this.lastSpamCall.commentarioId, this.lastSpamCall.commentoId);
		}
		
		this.notauthenticatedCallback = function() {
      		this.commentViewer.closeCheckLoginMessage();
			this.commentViewer.showMustBeAuthenticatedMessage();
		}
	
		this.vote = function(idcommentario, idcommento, voto) {
			idcom = idcommentario + "" + idcommento;
			if(isAlreadyVotedComment(idcom)) {
				CommentClient.commentViewer.showVoteMessage(idcommentario, idcommento, "Hai gi&agrave; votato !");
				return;
			}
			this.commentViewer.showCheckLoginMessage();
			this.lastVoteCall = new CommentLastVoteCall();
			this.lastVoteCall.commentarioId = idcommentario;
			this.lastVoteCall.commentoId = idcommento;
			this.lastVoteCall.voto = voto;
			AAClient.isAuthenticated('CommentClient.authenticatedForVoteCallback()', 'CommentClient.notauthenticatedCallback()');
		}
		
		this.setSpam = function(idcommentario, idcommento) {
			this.commentViewer.showCheckLoginMessage();
			this.lastSpamCall = new CommentLastSpamCall();
			this.lastSpamCall.commentarioId = idcommentario;
			this.lastSpamCall.commentoId = idcommento;
			AAClient.isAuthenticated('CommentClient.authenticatedForSpamCallback()', 'CommentClient.notauthenticatedCallback()');
		}

	}
	
	CommentClient = new CommentClientFunct();


       					