var requests = [];
var serverOnline = true;

function callIt(url, callBackFunction, errorCB) {
  // append timestamp to avoid browser caching   
  var noCache = (url.indexOf("?") == -1 ? "?" : "&amp;amp;") + (new Date().getTime()); var id = requests.length;
  requests[id] = new Object();
  var theRequest = requests[id];
  theRequest.callBack = callBackFunction;
  theRequest.errorCB = errorCB;
  var script = document.createElement("script");
  script.setAttribute("src", url + noCache + "&ebo_call_id="+id);
  script.setAttribute("charset", "utf-8");
  script.setAttribute("type", "text/javascript");
  theRequest.scriptElement = script;
  document.body.appendChild(script); //insert the script and implicitly execute it.
  setTimeout(function() { try { document.body.removeChild(script); serverOnline = false; errorCB({"timeOut":true}); } catch (e) { } }, 2000);    //remove script after 2 seconds.
}
 
function handleReply(id, jsonData) 
  {
  if (parseInt(id)<0)
    {
    showComments(jsonData);
    }
  else
    {
    serverOnline = true; //set it again, in case a time-out was premature.
    document.body.removeChild(requests[id].scriptElement);
    requests[id].callBack(jsonData);
    }
  }

function handleError(id, jsonData) {
  document.body.removeChild(requests[id].scriptElement);
  requests[id].errorCB(jsonData.Error);
}

function getUrlBase() {
  return 'http://' + commentsIP + ':80/Gallery/';
}
function getJSONUrlBase() {
  return getUrlBase() + 'JavascriptServlet';
}

function encodeParameter(strText) {
  if (strText == undefined)
    return "";
//  var txt = strText.replace(/\\/g, "\\\\").replace(/\"/g, "\\\"").replace(/\r\n/g, "\\n").replace(/\n/g, "\\n");
  var txt = strText.replace(/\\/g, "\\\\").replace(/\r\n/g, "\\n").replace(/\n/g, "\\n");
  txt = txt.replace(/\u20AC/g, "&euro;");
  txt = encodeURIComponent(txt); //escape() crashes on euro sign on the server !
  return txt;
}
//class Comments
function Comments(section, subSection) {
  this.section = section;
  this.subSection = subSection;
  this.adminMode = false;
  this.errorCB = null;
  var comments = this;
  this.getComments = function(getCommentsCB) {
  if (serverOnline) 
    {
    var req = getJSONUrlBase() + '?action=getComments&subSection=' + subSection + "&section=" + section;
    callIt(req, getCommentsCB, comments.errorCB);
    }
  else
    {
    //add the static comments file
    var script = document.createElement("script");
    script.setAttribute("src", "comments/"+section+"_"+subSection.replace(/\/|\./g, "_")+".js");
    script.setAttribute("charset", "utf-8");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("id", "commentsFile");
    document.body.appendChild(script); //insert the script and implicitly execute it.
    }
  }

  this.addComment = function(strAuthor, strText, strWebsite, addCommentCB) {
    var req = getJSONUrlBase() + '?action=addComment&author=' + strAuthor + "&text=" + encodeParameter(strText) + "&website=" + strWebsite + "&subSection=" + subSection + "&section=" + section;
    callIt(req, addCommentCB, comments.errorCB);
  }

  this.deleteComment = function(strAuthor, strDate, deleteCommentCB) {
  var req = getJSONUrlBase() + '?action=deleteComment&author=' + strAuthor + "&date=" + strDate + "&subSection=" + subSection + "&section=" + section;
  callIt(req, deleteCommentCB, comments.errorCB);
  }

  this.setAdminMode = function(password, setAdminCB) {
    var req = getJSONUrlBase() + '?action=setAdminMode&password='+password;
    callIt(req, function(jsonData) { adminMode = eval(jsonData.adminMode); setAdminCB(); }, comments.errorCB);
  }

  this.getAdminMode = function(getAdminCB) {
    var req = getJSONUrlBase() + '?action=setAdminMode&password=' + password;
    callIt(req, function(jsonData) { adminMode = eval(jsonData.adminMode); getAdminCB(); }, comments.errorCB);
  }
}

function deletePortfolios(deletePortfoliosCB) {
  var req = getJSONUrlBase() + "?action=deletePortfolios";
  callIt(req, deletePortfoliosCB, null);
}

function savePortfolio(portfolio, savePortfolioCB) {
  var req = getJSONUrlBase() + "?action=savePortfolio" + "&name=" + portfolio.name + "&title=" + portfolio.title + "&dscr=" + encodeParameter(portfolio.dscr) + "&independentRows=" + portfolio.independentRows + "&path=" + portfolio.path.name + "&maxColumns=" + portfolio.maxColumns + "&basePath=" + portfolio.basePath;
  callIt(req, savePortfolioCB, null);
}

function savePicture(portfolio, picture, savePortfolioCB) {
  var req = getJSONUrlBase() + "?action=savePicture" + "&portfolio=" + portfolio.name + "&title=" + picture.title + "&url=" + picture.url + "&urlThumb=" + picture.urlThumb + "&urlLarge=" + picture.urlLarge + "&dscr=" + encodeParameter(picture.dscr) + "&info=" + picture.date + "&lineBreak=" + picture.lineBreak + "&lineBreakText=" + encodeParameter(picture.lineBreakText);
  callIt(req, savePortfolioCB, null);
}



//Page and form related functions

function showComments(jsonData) {
  hideAddBox();
  var strHtml = "";
  adminMode = eval(jsonData.data.adminMode);
  var com = jsonData.data.comments.comments;
  for (i in com) {
    var date = new Date();
    date.setTime(com[i].date);
    var strDate = date.toLocaleDateString();
    strHtml += "<li><p>";
    if (com[i].website)
      strHtml += "<a href='" + com[i].website + "'>" + com[i].author + "</a>";
    else
      strHtml += com[i].author;
    var txt = com[i].text.replace(/\n/g, "<br/>");
    strHtml += " (" + strDate + "):";
    if (adminMode == true)
      strHtml += "<button onclick=\"deleteComment('" + com[i].author + "', '" + com[i].date + "');\">X</button>";
    strHtml += "</p>" + txt + "</li>";
  }
  if(strHtml!='' || document.getElementById("commentslist").innerHTML!='') //only set list to empty if it is not empty, to avoid screen flickering.
    document.getElementById("commentslist").innerHTML = strHtml;
}

function refreshComments() {
  comments.getComments(showComments);
}

function setAdminMode() {
  var strList = document.getElementById("comments").innerHTML;
  document.getElementById("comments").innerHTML = "<p id='logon'>pwd:<input id='pwd' type='password' size='8'/> <button onclick='submitAdminMode();'>Submit</button></p>";
  document.getElementById("comments").innerHTML += strList;
  }
function submitAdminMode()
{
  var pwd = document.getElementById("pwd").value;
  comments.setAdminMode(pwd, refreshComments);
  document.getElementById("comments").removeChild(document.getElementById("logon"));
}

function deleteComment(strAuthor, strDate) {
  comments.deleteComment(strAuthor, strDate, showComments);
}

function submitComment() {
  var strAuthor = document.getElementById("author").value;
  var strText = document.getElementById("text").value;
  var strWebsite = document.getElementById("website").value;
  if(strText.length > 500)
    {
    alert("Your comment exceeds the limit of 500 characters.");
    return;
    }
  comments.addComment(strAuthor, strText, strWebsite, showComments);
}

function showAddBox() {
  document.getElementById("comment").style.display = "block";
    document.getElementById("showButton").style.visibility="hidden";
//  document.getElementById("showButton").style.display = "none";
}

function hideAddBox() {
  document.getElementById("comment").style.display = "none";
  if(serverOnline==true)
    document.getElementById("showButton").style.visibility="visible";
    //document.getElementById("showButton").style.display = "inline";
  document.getElementById("author").value = "";
  document.getElementById("text").value = "";
  document.getElementById("website").value = "";
}

