/**
 * Parameter
 */
RemotePlappadu.channel        = null;
RemotePlappadu.user           = 270;
RemotePlappadu.postingCount   = 5;
RemotePlappadu.postingReloadInterval = 0;
RemotePlappadu.remoteKey      = null;
RemotePlappadu.postings       = null;
RemotePlappadu.resultIFrameId = "id_iframe_plappadu_content";
RemotePlappadu.plappaduUrl    = "http://www.plappadu.com";
RemotePlappadu.jsonLoader     = null;
RemotePlappadu.elemente       = Array();
RemotePlappadu.doneOnce       = false;
RemotePlappadu.tid            = null;

//RemotePlappadu.prototype = new Object();

/**
 * Konstruktor:
 * Initialisiert diesen Remote Plappadu Klasse
 * Hier können auch alle nötigen Scripte nachgeladen werden
 *
 */
function RemotePlappadu() {
}

/**
 * Initialisierung der Werte wie channel und remoteKey
 * 
 */
RemotePlappadu.init = function (channelName, key, createChannelStyle, user, elemente) {
  RemotePlappadutid        = null;
  RemotePlappadu.elemente  = elemente;
	RemotePlappadu.channel   = channelName;
	RemotePlappadu.remoteKey = key;

  if (createChannelStyle == true) {
	  RemotePlappadu.createStyleTag();
	}
  userString = "";
  if((user != null) && (user != "")) {
    userString = "&user="+user;
    RemotePlappadu.user = user;
//    alert(RemotePlappadu.user);
  }
	// lade die Postings als js nach
	var req  = RemotePlappadu.plappaduUrl + "/rss/feed.php?channel="+RemotePlappadu.channel+"&format=json&callback=RemotePlappadu.showPostingsCallback"+userString; 
  if(RemotePlappadu.jsonLoader === null) {
    RemotePlappadu.jsonLoader = new JSONscriptRequest(req); 
  }
}

RemotePlappadu.showUser = function(id) {
  var d = document.getElementById(id+"postings");
  var neu = document.createElement("div");
  d.parentNode.insertBefore(neu, d);
  neu.id = id+"postings_user";
  htmlString = "<img src='http://www.fanzeile.de/images/1/1/2/270.48x48.jpg' />";
  htmlString += "<span>Nachrichten über sport1.de: </span>";
  neu.innerHTML = htmlString;
}

/**
 * Zeigt die Postings in der 'fremden' Seite (an der aktuellen Stelle) an.
 * Erstelle hier einen <div> Bereich, der erst gefüllt wird,
 * wenn die Postings nachgeladen wurden (callback).
 * 
 * @param count Anzahl der Postings
 * @param Interval, für das neuladen der Postings
 * @public
 */
RemotePlappadu.showPostings = function(count, reload, scipTimeout, id) {
  // div für die Postings
//  var id = RemotePlappadu.elemente[i];
  if((count == null) || (count == undefined) || (count == "undefined") || (count == "null")) { count = 4; }
  if((reload == undefined) || (reload == null) || (reload == "undefined")) { reload = 20; }
  if((scipTimeout == undefined) || (scipTimeout == null) || (scipTimeout == "undefined")) { scipTimeout = false; }
  id = "middle_"; 
  if(id == null) { 
    for(i = 0; i < RemotePlappadu.elemente.length; i++) {
      var id = RemotePlappadu.elemente[i];
      if((id != undefined) && (id != "undefined")) {
        var postingsDiv = document.getElementById(id+"postings");
        if (postingsDiv == null) {
          var postingsTop = document.getElementById(id+"postings_top");
          if (postingsTop == null) {
            document.write("<a href='http://www.fanzeile.de'><div id=\""+id+"postings_top\"></div></a>");
          }
/*
          if(RemotePlappadu.user != null) {
            htmlString = "<div id=\""+id+"postings_user\">";
            htmlString += "<img src='http://www.fanzeile.de/images/1/1/2/116.48x48.jpg?t=1212442609777' />";
            htmlString += "<span>Der EM-Fan f&uuml;r Sie vor Ort bei jedem Spiel</span>";
            htmlString += "</div>";
            document.write(htmlString);
          }
*/
          document.write("<div id=\""+id+"postings\"></div>");
          document.write("<div id=\""+id+"postingsMore\"></div>");
          document.write("<div id=\""+id+"postings_bottom\"></div>");
        }
      }
    }
    id = null;
  } else {
    var postingsDiv = document.getElementById(id+"postings");
    if (postingsDiv == null) {
      var postingsTop = document.getElementById(id+"postings_top");
      if (postingsTop == null) {
        document.write("<a href='http://www.fanzeile.de'><div id=\""+id+"postings_top\"></div></a>");
      }
/*
      if(RemotePlappadu.user != null) {
        htmlString = "<div id=\""+id+"postings_user\">";
        htmlString += "<img src='http://www.fanzeile.de/images/1/1/2/116.48x48.jpg?t=1212442609777' />";
        htmlString += "<span>Der EM-Fan f&uuml;r Sie vor Ort bei jedem Spiel</span>";
        htmlString += "</div>";
        document.write(htmlString);
      }
*/
      document.write("<div id=\""+id+"postings\"></div>");
      document.write("<div id=\""+id+"postingsMore\"></div>");
      document.write("<div id=\""+id+"postings_bottom\"></div>");
    }
  }
  if (count != null) {
    RemotePlappadu.postingCount = count;
  }
  if (reload != null && reload > 0) {
    if (reload < 3) {reload = 3;}
    RemotePlappadu.postingReloadInterval = reload * 1000;

  }
  // ein javascript Tag erstellen und in die Seite Packen.
  // darin ist die Callbackfunktion, die dann alle Postings neu anzeigt.
  RemotePlappadu.jsonLoader.buildScriptTag(); 
  RemotePlappadu.jsonLoader.addScriptTag();
  // setze einen Timeout, damit die Postings aktuell bleiben.
  if ((RemotePlappadu.postingReloadInterval > 0)) { // && ( scipTimeout == null || scipTimeout != true)) && id !== null) {
    RemotePlappadutid = window.setTimeout("RemotePlappadu.showPostings("+count+", "+reload+","+scipTimeout+", '"+id+"')", RemotePlappadu.postingReloadInterval);
  }
}

/**
 * Erstellt das Formular zum versenden eines Postings.
 * @public
 */
RemotePlappadu.showPostingForm = function(useCaptcha, id) {
  var postingsTop = document.getElementById(id+"postings_top");
  if (postingsTop == null) {
    document.write("<a href='http://www.fanzeile.de'><div id=\""+id+"postings_top\"></div></a>");
  }
  var formHtml ="<div id=\""+id+"pp_postingForm\">";
  formHtml += " <form onSubmit=\"RemotePlappadu.submitPostingForm(this, '"+id+"'); return false;\"  id=\""+id+"postingForm\" >";
  formHtml += "  <div class=\"pp_postingFormInput\">";
  formHtml += "   <input type=\"hidden\" name=\"channel\" value=\""+RemotePlappadu.channel+"\"/>";
  formHtml += "   <input type=\"hidden\" name=\"remoteKey\" value=\""+RemotePlappadu.remoteKey+"\"/>";
  //formHtml += "   <input type=\"text\" name=\"text2post\" class=\"pp_textInput\" />";
  formHtml += "   <label for=\""+id+"text2post\">Einfach mitreden! (max. 130 Zeichen)</label>";
  formHtml += "   <textarea name=\""+id+"text2post\" id=\""+id+"text2post\" class=\"pp_textInput\" /></textarea>";
  formHtml += "  </div>";
  formHtml += "  <div class=\""+id+"pp_postingFormButton\">";
  formHtml += "   <button type=\"submit\" name=\"send\" value=\"senden\" class=\"pp_postingButton\">senden</button>";
  formHtml += "  </div>";
  formHtml += " </form>";
  formHtml += "</div>";

  document.write(formHtml);
  // erstelle noch ein Iframe für die SubmitErgebnis und lade Scripte
  RemotePlappadu.createResultIFrame(id);
}


/**
 * Wird beim onsubmit des posting Formulars aufgerufen und schickt das 
 * neue Posting nach plappadu.
 *
 * @private
 */
RemotePlappadu.submitPostingForm = function(formElement, id) {
  var url = RemotePlappadu.plappaduUrl+"/json/ajax_insertPostingReturnHtml.php?channel="+encodeURIComponent(RemotePlappadu.channel)+"&remoteKey="+encodeURIComponent(RemotePlappadu.remoteKey)+"&text2post="+encodeURIComponent(document.getElementById(id+"text2post").value);
  var scriptNode = document.getElementById(id+RemotePlappadu.resultIFrameId);
  if (scriptNode != null) {
    scriptNode.src = url;
  }

/*
  // Ergebnisse bitte ins IFrame
  formElement.target = RemotePlappadu.resultIFrameId;
  //formElement.action = RemotePlappadu.plappaduUrl+"/json/ajax_insertPostingReturnHtml.php?channel="+RemotePlappadu.channel+"&remoteKey="+RemotePlappadu.remoteKey+"&text2post="+formElement.text2post.value;
  formElement.action = RemotePlappadu.plappaduUrl+"/json/ajax_insertPostingReturnHtml.php";
  formElement.method = "get";
  formElement.submit();
*/
  document.getElementById(id+"text2post").value = "";
  // dann die Anzeige noch aktualisiren (wenn das Submit durch sein dürfte)
  setTimeout("RemotePlappadu.showPostings(null, null, true)", 400);
}

/**
 * Wird aufgerufen, wenn das js mit den Postings geladen ist.
 * Schreibt dann die Postings in das entsprechende <div>
 *
 * @private
 */
RemotePlappadu.showPostingsCallback = function(jsonPostings) {

  // Postings merken
  RemotePlappadu.postings = jsonPostings;
  // dann anzeigen
  for(i = 0; i < RemotePlappadu.elemente.length; i++) {
    RemotePlappadu.displayPostings(RemotePlappadu.elemente[i]);
  }
  if(RemotePlappadu.elemente.length == 0) {
    RemotePlappadu.displayPostings();
  }
  // und den scriptTag dann wieder löschen
  RemotePlappadu.jsonLoader.removeScriptTag();
}

/**
 * Zeigt die gewünschten Postings an, die durch die callback-Funktion
 * showPostingsCallback() in die Variable RemotePlappadu.postings
 * geladen wurden.
 * @private
 */
RemotePlappadu.displayPostings = function(id) {
  if(id === null) { id = ""; }
  var postingsDiv = document.getElementById(id+"postings");
  if(postingsDiv != null) {
    while (postingsDiv.hasChildNodes()) {
      try {
        postingsDiv.removeChild(postingsDiv.firstChild);
      } catch(e) {}
    }

    for (var i = 0; i < RemotePlappadu.postings.postings.length && i < RemotePlappadu.postingCount; i++) {
      if(RemotePlappadu.postings.postings[i] != null) {

        var html = "<div class=\"pp_postingElement\" style='width:100%;overflow:hidden'>";
        html    += "  <div class=\"pp_nick\">";
        html    += RemotePlappadu.postings.postings[i].nickname;
        html    += ": </div>";
        html    += "  <div class=\"pp_content\" style='width:100%;overflow:hidden'>";
        html    += RemotePlappadu.postings.postings[i].content;
        html    += "  </div>";
        html    += "  <div class=\"pp_created\">(";
        var createdDate = new Date (RemotePlappadu.postings.postings[i].created);
        var delayedDate = RemotePlappadu.getDelay(RemotePlappadu.postings.postings[i].created);
//        delayedDate = delayedDate.replace(/^\s*(S)\s*$/, '$1');
        delayedDate = delayedDate.replace (/^\s+/, '').replace (/\s+$/, '');
        html    += delayedDate + " via " + RemotePlappadu.postings.postings[i].createdVia;
        html    += ") </div>";
        html    += "</div>";

        postingsDiv.innerHTML += html;
      }
    }
  }
}


RemotePlappadu.displayButtonBottom = function(url, linkLabel, id) {
  var postingsBottom = document.getElementById(id+"postings_bottom");
  if (postingsBottom != null) {
    postingsBottom.innerHTML = "<a href='"+url+"' target='_blank'>"+linkLabel+"</a>";
  }
}

RemotePlappadu.displayButtonMore = function(url, linkLabel, id) {
  var postingsMore = document.getElementById(id+"postingsMore");
  if (postingsMore != null) {
    postingsMore.innerHTML = "<a href='"+url+"' target='_blank'>"+linkLabel+"</a>";
  }
}


/**
 * Erstellt nur ein unsichtbars Frame als Ziel des Postingformulars
 */
RemotePlappadu.createResultIFrame = function (id) {
  if(id === null) { id = ""; }
  var scriptNode = document.getElementById(RemotePlappadu.resultIFrameId);
  if (scriptNode == null) {
    var myFrame = "<iframe name=\""+id+RemotePlappadu.resultIFrameId+"\" id=\""+id+RemotePlappadu.resultIFrameId+"\" src=\""+RemotePlappadu.plappaduUrl+"/json/ajax_insertPostingReturnHtml.php\" width=\"0\" height=\"0\" style=\"display: none;\"></iframe>";
    var formDiv = document.getElementById(id+"postingForm");
    if(formDiv !== null) {
      formDiv.innerHTML = formDiv.innerHTML + myFrame;
    }
  }
}

/**
 * Erstellt einen css tag im Head mit den Channel spezifischen Styles
 */
RemotePlappadu.createStyleTag = function () {

    // Create the script tag
    var styleNode = document.createElement("link");

    // Add style object attributes
    styleNode.setAttribute("type", "text/css");
    styleNode.setAttribute("rel", "stylesheet");
    styleNode.setAttribute("href", RemotePlappadu.plappaduUrl+"/css/remoteChannel.css.php?channel="+RemotePlappadu.channel);
    
    document.getElementsByTagName("head")[0].appendChild(styleNode);
}

/**
 * Helper
 */

RemotePlappadu.getDelay = function ($timestamp) {
  var $date = new Date(parseInt($timestamp));
  var $now = new Date().getTime();
  var $postingDate1 = ($date.getDate() < 10 ? "0"+$date.getDate() : $date.getDate() ) + "." + ($date.getMonth() < 9 ? "0"+($date.getMonth()+1) : ($date.getMonth()+1) )  + "." + ($date.getYear() + 1900);
  var $postingDate2 = ($date.getHours() < 10 ? "0"+$date.getHours() : $date.getHours() ) + ":" + ($date.getMinutes() < 10 ? "0"+$date.getMinutes() : $date.getMinutes() ) + ":" + ($date.getSeconds() < 10 ? "0"+$date.getSeconds() : $date.getSeconds());
  //var $secsAgo     = parseInt(($now - $timestamp + $iServerClientDelay) / 1000);
  var $secsAgo     = parseInt(($now - $timestamp ) / 1000);
  if ($secsAgo < 1) {
    $secsAgo = 1;
  }
  var $minsAgo     = parseInt($secsAgo / 60);
  var $hoursAgo    = parseInt($minsAgo / 60);
  var $daysAgo     = parseInt($hoursAgo / 24);
  if ($secsAgo > 60) {
    if ($minsAgo > 60) {
      if ($hoursAgo > 24) {
        return " am " + $postingDate1 + " um " + $postingDate2 + " Uhr";
      }
      return " vor mehr als " + $hoursAgo + (($hoursAgo > 1) ? " Stunden" : " Stunde");
    }
    return " vor mehr als " + $minsAgo + (($minsAgo > 1) ? " Minuten" : " Minute");
  }
  return " vor " + $secsAgo + (($secsAgo) > 1 ? " Sekunden" : " Sekunde");
}



/* ************************************************************ */

// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl;
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");

    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
    this.scriptObj.setAttribute("src", this.fullUrl+"&count="+RemotePlappadu.postingCount + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}

// removeScriptTag method
//
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);
}


/* **************************************************************** */

/***
 * 
function ResourceLoader() {
}
 */


/**
 * Erzeut einen HTTP-Request fuer Ajax-Abfragen
 * @return Liefert ein Cross-Browser XMLHttpRequest zurueck
 * @type XMLHttpRequest
 * @private
ResourceLoader.createRequest = function() {
  // Request erzeugen
  var request = false; 

  if (window.XMLHttpRequest) {
    request = new XMLHttpRequest(); // Mozilla, Safari, Opera
  } else if (window.ActiveXObject) {
    try {
      request = new ActiveXObject('Msxml2.XMLHTTP'); // IE 5
    } catch (e) {
      try {
        request = new ActiveXObject('Microsoft.XMLHTTP'); // IE 6
      } catch (e) {}
    }
  }

  // überprüfen, ob Request erzeugt wurde
  if (!request) {
    alert("Kann keine XMLHTTP-Instanz erzeugen");
  }
  return request;
}
 */

/*

try {
alert("start");
  //var url = RemotePlappadu.plappaduUrl+"/json/ajax_insertPosting.php?channel="+RemotePlappadu.channel+"&remoteKey="+RemotePlappadu.remoteKey+"&text2post="+formElement.text2post.value;
  var url = RemotePlappadu.plappaduUrl+"/json/ajax_insertPosting.php";
  var req = ResourceLoader.createRequest();
alert("req : " + req);
//  req.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
//alert("header");
  req.onreadystatechange = RemotePlappadu.submitPostingFormCallback;
alert("readyChange.. ");
  req.open('post', url, true);
alert("open ");
  var aParams = new Array();
  var sParam = encodeURIComponent("channel") +"="+encodeURIComponent(RemotePlappadu.channel);
  aParams.push(sParam);
  sParam = encodeURIComponent("remoteKey") +"="+encodeURIComponent(RemotePlappadu.remoteKey);
  aParams.push(sParam);
  sParam = encodeURIComponent("text2post") +"="+encodeURIComponent(formElement.text2post.value);
  aParams.push(sParam);
  var formBody = aParams.join("&");

  RemotePlappadu.lastRequest = req;

alert("send ? " + formBody);
  req.send(formBodys);

*/
