var communityBaseURL = "http://community.cubovision.it/community/";

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

/**
 * 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
	//alert("code: "+jsonObject.status.code+"\n message: "+jsonObject.status.message);
	if(jsonObject.status.code == -1){ //codice -1 errore utente non autenticato
		alert("POPUP - autentica");
		$.fn.colorbox({href:""+urlAlertLogin});
	}else{ //errore generico
		alert("POPUP - errore generico (code="+jsonObject.status.code+"&mess="+jsonObject.status.message+")");
		$.fn.colorbox({href:""+urlAlertGenericError+"?code="+jsonObject.status.code+"&mess="+jsonObject.status.message});
	}
}

function sendInPageMessage(nick) {
  var title = encodeURIComponent($('#msgtitle').val());
  var msg = encodeURIComponent($('#msgcontent').val());

  if (title == "") {
    $('#msgtitle').focus();
  } else if (msg == "") {
    $('#msgcontent').focus();
  } else {
    var url = "http://comment.cubovision.it/cv_send_pm.php?subject="+title;
    url += "&message=" + msg;
    url += "&mailto=" + encodeURIComponent(nick);
    url += "&type=inpage";
    
    callJSON(url);
  }
}

function inpageMsgCallback(response) {
  $.fn.colorbox.close();
  
  if (response.status == '0') {
    showFeedback("Messaggio inviato.");
  } else {
    showFeedback("Errore nell'inviare il messaggio!");
  }
}

function initSendInPageMessage() {
  if (checkLogin()) {
    $.fn.colorbox({href:"/common/alert/template_invia_msg.html"});
  }
  
  return false;
}

function loadNoticiesCount() { //aggiorna i messaggi e richiama showPrivateMessage
  var url = "http://community.cubovision.it/community/noticejson?";
  callJSON(url);
}

function showNoticies(response){
	$('#notice').html(response.notice);
}

function loadMessagesCount(folder) { //aggiorna i messaggi e richiama showPrivateMessage
  var url = "http://comment.cubovision.it/json_pm.php?folder="+folder;
  callJSON(url);
}

function showPrivateMessage(jsonObject){
	$('#inmsg').html(response.inbox);
	$('#outmsg').html(response.sentbox);
	if (response.folder == 'Inviati') {
		$('#currentFolder').html(response.folder + " (" + response.sentbox + ")");
	} else {
		$('#currentFolder').html(response.folder + " (" + response.inbox + ")");
	}
}

function loadRequestsCount() {
  var url = communityBaseURL + "mycubo/" + "contaamici?koCall=koCall&okCall=showFriendsCountCall";
  callJSON(url);
}

function requestFriendship(idProfileTo) {
  if (checkLogin()) {
    var url = communityBaseURL + "mycubo/" + "richiediamicizia?koCall=koCall&okCall=okReqFriendCall";
    url += "&idProfileTo=" + idProfileTo;
    
    callJSON(url);
  } 
  return false;
}

function okReqFriendCall(result) {
  if (result.status == "2") {
    showFeedback("Amicizia esistente.");
  } else {
    showFeedback("Richiesta di amicizia inviata");
  }
}

function loadLastProduct() {
  var url = "http://buy.cubovision.it/lastProduct/Product?limit=3";
  
  callJSON(url);
}

function showLastProduct(response) {
//alert("SHOW");
  var templateHtml="";
  templateHtml += "<li>";
	templateHtml += "	<a href=\"{url}\" title=\"{title}\">";
 	templateHtml += "	<img id=\"{id}\" alt=\"\" src=\"http://images1.cubovision.it/common/placeholder/ph_90x50.jpg\" />";
 	templateHtml += "{title}";
 	templateHtml += "	</a>";
 	templateHtml += "	<span>{category}</span>";
 	templateHtml += "</li>";

  if (response.length > 0) {
    var responseHtml = "";
    
    for (var i=0; i<response.length; i++) {
      var tempHtml = templateHtml;
      tempHtml = tempHtml.replace(/{id}/g, "lastproduct_"+i);
      tempHtml = tempHtml.replace(/{url}/g, response[i].urlView);
      tempHtml = tempHtml.replace(/{title}/g, response[i].name);
      tempHtml = tempHtml.replace(/{category}/g, response[i].dept);
      //tempHtml = tempHtml.replace(/{scadenza}/g, response[i].stopDate);
      
      //responseHtml += tempHtml;
      $('#lastProduct').append(tempHtml);
      srcByRicercaCnt(response[i].name, "lastproduct_"+i);
    }
    
    $('#msgAcquisti').html("Hai tempo fino al " + response[0].stopDate + " per completare la visione di:");
    //$('#lastProduct').html(responseHtml);
  } else {
	  $('#msgAcquisti').html("<span>Non ci sono video disponibili</span>");
  }
}

function loadLastRecivedReqs() {
  var url = communityBaseURL + "mycubo/richiestericevute?respType=json&orderBy=data&orderDir=desc&callback=showLastRecivedReqs&limit=3&status=waiting";
  
  callJSON(url);
}

function showLastRecivedReqs(response) {
  var templateHtml = "";
  templateHtml += "<li>";
  templateHtml += "  <a href=\"/community/profilo?nick={mittenteNickname}\" title=\"{mittenteNickname}\">";
  templateHtml += "    <span class=\"cornice\"></span>";
  templateHtml += "    <img src=\"http://multimedia.community.alice.it/contenutiyalp/{mittenteNickname},i00.jpg\" alt=\"\" />";
  templateHtml += "	    	{mittenteNickname}";
  templateHtml += "  </a>";
  templateHtml += "  <p>Amici {friends}</p>";
  templateHtml += "  <span class=\"voto\" style=\"{voteStar}\">Voto attuale {voteCounter}/5 stelle</span>";
  templateHtml += "</li>";
  
  var responseHtml = "";
  for (var i=0; i<response.length; i++) {
    var tempHtml = templateHtml;
    
    tempHtml = tempHtml.replace(/{mittenteNickname}/g, response[i].mittenteNickname);
    tempHtml = tempHtml.replace(/{friends}/g, response[i].profile.calcAmici);
    tempHtml = tempHtml.replace(/{voteCounter}/g, response[i].profile.voteCounter);
    
    if (response[i].profile.voteCounter==0) {
      tempHtml = tempHtml.replace(/{voteStar}/g, "background-position: -166px -114px");
  	} 
  	if (response[i].profile.voteCounter==1) {
  		tempHtml = tempHtml.replace(/{voteStar}/g, "background-position: -166px -125px");
  	} 
  	if (response[i].profile.voteCounter==2) {
  		tempHtml = tempHtml.replace(/{voteStar}/g, "background-position: -166px -136px");
  	}
  	if (response[i].profile.voteCounter==3) {
  		tempHtml = tempHtml.replace(/{voteStar}/g, "background-position: -166px -147px");
  	}
  	if (response[i].profile.voteCounter==4) {
  		tempHtml = tempHtml.replace(/{voteStar}/g, "background-position: -166px -158px");
  	}
  	if (response[i].profile.voteCounter==5) {
  		tempHtml = tempHtml.replace(/{voteStar}/g, "background-position: -166px -169px");
  	}
  	
    responseHtml += tempHtml;
  }
  if (response.length<=0) {
    $('#recreqtext').html("Nessuna richiesta.");
  } else {
    $('#recreqtextcount').html(response.length);
  }
  
  $('#recreq').html(responseHtml);
}

function setStatusMsg() {
  if (!isLogged()) {
    viewLogin();
  } else {
    var msg = $('#mymsg').val();
    var url = communityBaseURL + "mycubo/" + "cambiamessaggio?msg="+msg;
    
    callJSON(url);    
  }
  
  return false;
}

function changeMsgCall(result) {
  if (result.status == "1") {
    showFeedback("Errore nell'aggiornamento del messaggio di stato");
  } else {
    showFeedback("Messaggio di stato aggiornato");
  }
}

function showFriendsCountCall(response) {
  $('#numfriends').html("("+response.friends+")");
  $('#inreqs').html(response.inReq);
  $('#outreqs').html(response.outReq);
  $('#notice').html(response.inReq);
}

function showPrivateMessage(response) {
  $('#inmsg').html(response.inbox);
  $('#outmsg').html(response.sentbox);
  $('#headMsgCount').html(response.inbox);
}