//============== COSTANTI =========================//
var pathRss = "http://comment.cubovision.it/getCommentRSS.php";
var prePath = "http://comment.cubovision.it/jsonFunction.php";
var urlAlertGenericError="/common/alert/template_Wlogin_pwdlost.html"; /* //TODO da passare ?msg=ERRORE */

//se uguale a null in caso di successo non compare nessun popup
var urlAlertSuccessInsert = null ;//"/common/alert/template_Wlogin_alert.html";
//=================================================//
//============== NODI HTML ========================//

//=================================================//
//dati riguardanti il contenuto
var cntid = null;
var cntTitle = null;
var cntDescription = null;
var cntLink = null;

var contentFId = -1; //id corrente
var start = null; //indice di paginazione

var currentCommentId = null; //id del commento a cui sis sta rispondendo


//============== RICHIESTE =========================//
/**
 * loadTopic(stringParam)
 * 
 * stringParam è una tringa in formato GET
 * con i seguenti parametri:
 * start: [opzionale] serve per la paginazione
 * f: id forum
 *    oppure
 * cntid: id contenuto usato per recuperare il forum id       
 */ 
function loadTopic(stringParam){
	var pathRequest = prePath+"?method=topic&"+stringParam;	
	searchJSON(pathRequest);
}

//stringParam : f=X&t=Y
function loadPost(stringParam){
	var pathRequest = prePath+"?method=post&"+stringParam;		
	searchJSON(pathRequest);
}
//=================================================//

function loadCommenti(cntIdParam,startParam,cntTitleParam,cntDescriptionParam,cntLinkParam){

	//setto in memoria client i dati riguardanti il contenuto
  cntid = cntIdParam;
	cntTitle = cntTitleParam;
	cntDescription = cntDescriptionParam;
	cntLink = cntLinkParam;
	
	if (startParam!==undefined){
		start = startParam;
	}else if(start === null){
		start = 0;
	}
	
	//$("#social_comm").attr("onclick","return checkLogin();");
	$("#social_comm").click(function(){
      //return checkLogin();
      checkLogin();
      currentCommentId=null;
      $('#add_commento textarea').val('');
      return false;
  });
	
	loadTopic("cntid="+cntid+"&start="+start);
	
} 

/**
 * reloadCommenti
 * 
 * funzione di callback che viene chiamata solo dopo che un inserimento
 * e' andato a buon fine per ricaricare i commenti e le risposte  
 */ 
function reloadCommenti(contenutoFIdParam){

    if(contenutoFIdParam!=961){ //se il forum di ritorno e quello delle stop word non faccio niente
        contentFId = contenutoFIdParam;
        loadTopic("f="+contentFId+"&start="+start);
    }

    //popup finestra per inserimento riuscito con successo
    if(urlAlertSuccessInsert !== null){
         $.fn.colorbox({href:""+urlAlertSuccessInsert});
    }
    
    //chiudo lo spazio in cui si scrivono i commenti
    $('#add_commento').slideToggle("slow"); 
}

//============== RISPOSTE =========================//
function loadTotalPM() {
	var pathRequest = "http://comment.cubovision.it/json_pm.php";
	searchJSON(pathRequest);
}

function forumResponse(jsonObject){
	//alert(jsonObject);//TODO
}

function topicResponse(jsonObject){

	var statusCode = jsonObject.status.code;
	          //alert("topicResponse - code: "+jsonObject.status.code+"/n message: "+jsonObject.status.message);
	if(statusCode !== 0){
		errorResponse(jsonObject);
		return;
	}else{
		//mando alla view il numero di commenti trovati
		var numCommentiNode = document.getElementById("numCommenti");
	
    if(jsonObject.response===undefined){
       $("#commenti_com > .c_isc_rss").hide();
    }else{
		//if(jsonObject.response!=undefined){
		//imposto nella vista il numero di commenti
  		
  		var numTopic = 0;
  		
  		if(jsonObject.response.total_topics == undefined){
          numCommentiNode.innerHTML = "";
      }else{
          numCommentiNode.innerHTML = jsonObject.response.total_topics;
          numTopic = jsonObject.response.total_topics;
  		    numTopic = numTopic.substring(10);
  		    numTopic = numTopic.substring(0,numTopic.length-1);
      }
      
  		$("#social_comm b").html(numTopic);
  		
  		//tengo in memoria il forum id
  		contentFId = jsonObject.response.forum_id;
  		
  		//recupero la lista di topic
  		var topics = jsonObject.response.topics;
  		
  		var arrayPostDaCaricare=new Array();
  
  		var commenti_ele = document.getElementById("commenti_ele");
  		commenti_ele.innerHTML = "";  
  		
  		for(var i=0; i<topics.length; i++){
  			var elem = topics[i];
  			
  			var li = document.createElement("li");
  			li.setAttribute("id","comment_"+jsonObject.response.forum_id+"_"+elem.topic_id);
  			
  			var a = document.createElement("a");
  			a.setAttribute("href","#");
  			a.setAttribute("title","\""+elem.author+"\"");
  			a.setAttribute("class","ut_com");
  			a.setAttribute("className","ut_com");
  			
  			li.appendChild(a);
  			
  			var span = document.createElement("span");
  			span.setAttribute("class","foto");
  			span.setAttribute("className","foto");   //attributo class per IE
  			a.appendChild(span);
  			
  			var img = document.createElement("img");
  			img.setAttribute("src","http://multimedia.community.alice.it/contenutiyalp/"+elem.author+",i00.jpg");
  			img.setAttribute("alt","Placeholder");//TODO
  			img.setAttribute("width","80");//TODO
  			img.setAttribute("height","80");//TODO
  			a.appendChild(img);
  			
  			//var txtNode = document.createTextNode(elem.title);
  			var txtNode = document.createTextNode(elem.author);
  			a.appendChild(txtNode);
  			
  			var p = document.createElement("p");
  			//txtNode = document.createTextNode(elem.posts[0].message);
  			
        //var testo = unescape(elem.title);
        var testo = elem.title;
  			 
  			//txtNode = document.createTextNode(testo); 
        //p.appendChild(txtNode);
        
        p.innerHTML =  testo;
  			li.appendChild(p);
  			
  			span = document.createElement("span");
  			a = document.createElement("a");
  			a.setAttribute("href","#");
  			a.setAttribute("class","mpci");
  			a.setAttribute("className","mpci");  //attributo class per IE
  			//a.innerHTML= 'Mi piaci (<b>33</b>)'; 
  			span.appendChild(a);
  			
  			span2 = document.createElement("span");
  		//	span2.appendChild(document.createTextNode("|"));
  			span.appendChild(span2);
  			
  			a = document.createElement("a");
  			//a.setAttribute("href","#");
  			//a.setAttribute("href","javascript:openCommentArea('reply',"+elem.topic_id+")"); 
  			//a.setAttribute("onclick","currentCommentId = "+elem.topic_id+";");
  			//a.setAttribute("onClick","currentCommentId = "+elem.topic_id+";$('#add_commento textarea').html('Nome Utente@:');$('#add_commento').slideToggle('slow');return false;");
  			//a.setAttribute("href","javascript:function(){alert('xxx')};");
  			
  			//$(a).click(function(){$('#add_commento textarea').html('Nome Utente@:');$('#add_commento').slideToggle("slow");currentCommentId = elem.topic_id;return false;})
  			//$(a).click(function(){openRisp(elem.topic_id);return false;});
  			//a.setAttribute("onclick","function(){openRisp("+elem.topic_id+");return false;}");
  			a.setAttribute("href","javascript:openRisp("+elem.topic_id+",'"+elem.author+"')");
        //$('.rspd').click(function(){$('#add_commento textarea').html('Nome Utente@:');$('#add_commento').slideToggle("slow");return false;})
  			
  			a.setAttribute("class","rspd");
  			a.setAttribute("className","rspd"); //attributo class per IE
  			
  			a.innerHTML= 'Rispondi';
  			span.appendChild(a);
  			li.appendChild(span);
  			
  			commenti_ele.appendChild(li); 
  			
  			if(elem.replies > 0){
  				arrayPostDaCaricare.push("f="+jsonObject.response.forum_id+"&t="+elem.topic_id);
  			}
  		}
  		
  		//creo il codice HTML PER LA PAGINAZIONE
  		createPaginator(jsonObject.response.num_page,jsonObject.response.on_page, jsonObject.response.per_page);
  		
  		//crea link RSS feed
  		//$("#commenti_com > .c_isc_rss").attr("href",pathRss+"?f="+jsonObject.response.forum_id+"&view=rss");
  		$("#commenti_com > .c_isc_rss").attr("href",pathRss+"?f="+jsonObject.response.forum_id);
  	  $("#commenti_com > .c_isc_rss").attr("target","_blank");
  	  $("#commenti_com > .c_isc_rss").show();
  		
  		for(var j=0; j<arrayPostDaCaricare.length; j++){
  			loadPost(arrayPostDaCaricare[j]);
  		} 
		}
	}
}

function openRisp(idComment,userName){
      if (!checkLogin()){
				  return;
			}else{
           if(userName!==undefined && userName!=null){
                $('#add_commento textarea').val(userName+'@:');
           }else{
                $('#add_commento textarea').val('');
           }
              
           $('#add_commento').slideToggle("slow"); 
           currentCommentId = idComment;  
      }      
}

var canInsert = true; //se e' settata a false non possono essere inseriti altri commenti o post
/**
 * funzione chiamata all'inserimento di un commento o di una risposta a un commento
 */ 
function insertComment(){
                 
	if (!isLogged()){ 
    viewLogin();
		  
	}else if(canInsert){
       //alert("INIZIO INSERIMENTO");
    	//recupero il comento dalla text area
    	var commentoText = $('#add_commento textarea').val();
    	commentoText = escape(commentoText);
    	
    	$('#add_commento textarea').val("");//svuoto testo box
    	
    	if(currentCommentId !== null){ //se è presente il currentCommentId si sta rispondendo a un commento 
    	     typeComment = 'reply';  
    	     pathRequest = prePath+'?method=insert&mode='+typeComment+'&title=RE-'+contentFId+'-'+currentCommentId+'&message='+commentoText+'&f='+contentFId+'&t='+currentCommentId;
    		   pathRequest += '&cnttitle='+cntTitle;
        	 pathRequest += '&cntlink='+cntLink;
           //alert(pathRequest);
           searchJSON(pathRequest);
    	}else{//nuovo commento
    	     typeComment = 'post';
           if(contentFId == -1){//se forum id == -1 allora il forum non è ancora creato 
    			     //creo il forum e il primo topic
					     pathRequest = prePath+'?method=insert&mode=forum&cntid='+getCntId()+'&title='+commentoText;
        			 pathRequest += '&cnttitle='+cntTitle;
        			 pathRequest += '&cntdesc='+cntDescription;
        			 pathRequest += '&cntlink='+cntLink;
        			 
        			 // alert(pathRequest);
        			 searchJSON(pathRequest);
    		    }else{
        			 pathRequest = prePath+'?method=insert&mode='+typeComment+'&title='+commentoText+'&f='+contentFId;
        			 
               // alert(pathRequest);
               searchJSON(pathRequest);                                                                         
        		}  		
      }
      
       canInsert = false;
       setTimeout(function search(){canInsert = true;}, 1000);
       
  }else{
    //alert("STOP INSERIMENTI");
  }    
}

/**
 * Genera il codice html dei post
 * 
 * @param jsonObject: oggetto json contenente i dati dei post 
 */
function postResponse(jsonObject){
	var idNode =  "comment_"+jsonObject.response.forum_id+"_"+jsonObject.response.topic_id;
	
	var nodeLiHtml = document.getElementById(idNode);
	
	for(var i=1; i<jsonObject.response.posts.length; i++){
		post = jsonObject.response.posts[i];
		
		var nRispostaSpan = document.createElement("span");
		nRispostaSpan.setAttribute("class","rsp");
		nRispostaSpan.setAttribute("className","rsp");
		
			
		var htmlCode = '<a href="#" title="'+post.author+'" class="ut_com">';
		htmlCode += '<span class="foto"></span>';
		//htmlCode += '<img src="http://images1.cubovision.it/common/placeholder/ph_50x50.jpg" alt="Placeholder"/>';
		htmlCode += '<img src="http://multimedia.community.alice.it/contenutiyalp/'+post.author+',i00.jpg" width="50" height="50" alt="Placeholder"/>';
		htmlCode += post.author;
		htmlCode += '</a>';
		//htmlCode += '<p>'+unescape(post.message)+'</p>';
		htmlCode += '<p>'+post.message+'</p>';
		
		nRispostaSpan.innerHTML = htmlCode;
		
		nodeLiHtml.appendChild(nRispostaSpan);	
	}
}

function testJSON(jsonObject){
	//alert(jsonObject.test);
}

/**
 * funzione che viene chiamata anche con chiamate JSON 
 * per gestire i messaggi di errore lato server
 * 
 * @param jsonObject: risposta lato server
 */
function errorResponse(jsonObject){//TODO
	
	 if(jsonObject.status.code == -1){ //codice -1 errore utente non autenticato
      
       viewLogin();
   }else{ //errore generico
	     //$.fn.colorbox({href:""+urlAlertGenericError+"?code="+jsonObject.status.code+"&mess="+jsonObject.status.message});
	 }
}

/**
 * Crea il codice HTML per la paginazione
 * 
 * @param totalPage: numero di pagine totali
 * @param onPage: numero della pagina corrente
 * @param per_page: numero di topic per pagina
 */
function createPaginator(totalPage, onPage, per_page){
	var nodeParent = document.getElementById("commenti_pag");

	var htmlCode = '';
	if(onPage != 1){
		htmlCode += '<a href="javascript:loadTopic(\'f='+contentFId+'&start='+((onPage-2)*per_page)+'\');" title="Precedente">Precedente</a>';
	}
	htmlCode += '<div class="pager">';
	for(var i=1; i<=totalPage; i++){
		if(i == onPage){
			htmlCode += '<span>'+i+'</span>';
		}else{
			htmlCode += '<a href="javascript:loadTopic(\'f='+contentFId+'&start='+((i-1)*per_page)+'\');">'+i+'</a>';
		}
	}
	htmlCode += '</div>';
	if(onPage != totalPage && totalPage>1){
		htmlCode += '<a href="javascript:loadTopic(\'f='+contentFId+'&start='+((onPage)*per_page)+'\');" title="Successiva">Successiva</a>';
	}
	
	nodeParent.innerHTML = htmlCode;
}


//=================================================//

//============== METODI COMMON=====================//	
/**
 * Metodo che effetua la chiamata asincrona
 * 
 * * @param pathRequest: url a cui effetiuare la chiamata asincrona
 */
var searchJSON = function(pathRequest) {
	aObj = new JSONscriptRequest(pathRequest);
	aObj.buildScriptTag();
	aObj.addScriptTag();  
};