// ==UserScript==
// @name           Affinitiz Tracer
// @namespace      fr.emse
// @description    Posts comments and publications from affinitiz to Gregory Dyke's interactiontracer
// @include        http://affinitiz.com/space/eco-droit/content/*
// ==/UserScript==

function Log(time,hashtable,callback) {
  var url = "http://interactiontracer.appspot.com/trace?";
  url += "jsonp="+callback;
  url += "&time="+time;
  url += "&key_application=affinitiz";
  url += "&key_session=iquentin";
  for (var key in hashtable) {
    url += "&"+encodeURIComponent(key)+"="+encodeURIComponent(hashtable[key]);
  }
  var GM_JQ = document.createElement('script');
  GM_JQ.src = url;
  GM_JQ.type = 'text/javascript';
  document.getElementsByTagName('head')[0].appendChild(GM_JQ);
  GM_log("sentlog");
 
}

function PostLog(time,hashtable,callback) {
var url = "http://interactiontracer.appspot.com/trace"
var data = "";
  data += "time="+time;
  data += "&key_application=affinitiz";
  data += "&key_session=test";
  for (var key in hashtable) {
    data += "&"+encodeURIComponent(key)+"="+encodeURIComponent(hashtable[key]);
  }
GM_xmlhttpRequest({
    method: "POST",
    url: url,
    headers:{'Content-type':'application/x-www-form-urlencoded'},
    data:data,
      onload: function(xhr) {unsafeWindow[callback](xhr.responseText); }
  });


}

String.prototype.htmlEntities = function () {
   return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};

String.prototype.stripTags = function () {
   return this.replace(/<([^>]+)>/g,'');
};

String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g,"");
};

var totalreceived = 0;

unsafeWindow["received"] = function() {
  totalreceived++;
  GM_log("received "+totalreceived+" "+comments.length);
  document.getElementById("progressdone").setAttribute("style","width:"+(10+(totalreceived*90/(comments.length+1)))+"px;"+progressstyle);
  if (totalreceived > comments.length) {
    document.getElementById("sendoff").innerHTML="envoyé";
  }
}

function sendOff() {
  PostLog(time,{"anchor": url, "author":author, "title": title, "message":contents.htmlEntities(), "type": type,
	"tags":tags, "places":places, "readcount":readcount, "visibility":visibility},"received");
  
  for (var i in comments) {
    var c = comments[i];
    PostLog(c.time, {"anchor": c.id, "author":c.author, "title": c.title, "message":c.message.htmlEntities(), "type": "comment", "parentid":c.parent},"received");
  }
};


var url = /(_[^#]*)(#.*)?$/.exec(window.location)[1];
var post = document.getElementById("content");
var title = post.getElementsByTagName("H2")[0].firstChild.data;

var authorlink = post.getElementsByTagName("UL")[0].getElementsByTagName("A")[0];
var author = authorlink.firstChild.data;

var datetext = authorlink.nextSibling.data;
var da = /(\d\d).(\d\d).(\d\d) - (\d\d):(\d\d)/.exec(datetext);

var date = new Date(parseInt("20"+da[3],10),
		    parseInt(da[2],10)-1,
		    parseInt(da[1],10),
		    parseInt(da[4],10),
		    parseInt(da[5],10)
		    );
var time = date.getTime();


var header = post.getElementsByTagName("DIV")[0].getElementsByTagName("DIV")[0];
var body = header.nextSibling.nextSibling;

var data = null;
var contents = "";
if (body.getElementsByTagName("DIV")[0]) {
  if (body.getElementsByTagName("DIV")[0].getAttribute("class")=="description") {
    contents=body.getElementsByTagName("DIV")[0].innerHTML;
    data = body.getElementsByTagName("DIV")[0].nextSibling.nextSibling;
  } else {
    data = body.getElementsByTagName("DIV")[0];
  }
} 

  var type = "Publication";
  if (data && data.getElementsByTagName("DIV")[0]) {
    type = /content(.*)/.exec(data.getElementsByTagName("DIV")[0].getAttribute("id"))[1];
  }


var footer = body.nextSibling.nextSibling;

var ul = footer.getElementsByTagName("UL")[0];

var lis = ul.getElementsByTagName("LI");

var taglinks = lis[1].getElementsByTagName("A");
var placelinks = lis[0].getElementsByTagName("A");

var tags = ""; 
for (var i in taglinks) {
  if (i>0) tags += ", ";
  var a = taglinks[i];
  tags += a.firstChild.data;
 }

var places = ""; 
for (var i in placelinks) {
  if (i>0) places += ", ";
  var a = placelinks[i];
  places += a.firstChild.data;
 }

var readcount = /Lu (.*) fois/.exec(lis[(tags=="")?1:2].firstChild.data)[1];
var visibility = (lis[lis.length-1].getAttribute("class")=="warningBox") ? "private":"public";



function Comment(author,time, anchor, parent, title, message) {
  this.author = author;
  this.time = time;
  this.id = anchor;
  this.parent = parent;
  this.title = title;
  this.message = message;
}

var comments = [];

var commentdivs = document.getElementById("contentComments");
var commentsinfo = "";
var comment = null;
if (commentdivs) comment = commentdivs.getElementsByTagName("DIV")[0];

if (comment && comment.getAttribute("class") == "tree") {
  comment = commentdivs.getElementsByTagName("DIV")[1];
}
var parentids = [url];
while (comment && comment.tagName=="DIV" && comment.getAttribute("class") && comment.getAttribute("class").substring(0,4)=="item") {
  
  var cdepth = 1;
  
  var canchor = url+"#"+comment.getAttribute("id");
  
  var cheader = comment.getElementsByTagName("DIV")[0];
  var padding = cheader.getElementsByTagName("DIV")[0].getAttribute("style");
  if (padding && padding!="") {
    cdepth = 1+(parseInt(/(..)px/.exec(padding)[1],10)/15);
  }
  parentids[cdepth]=canchor;
  var cparent = parentids[cdepth-1];

  var ctitle = comment.getElementsByTagName("H2")[0].firstChild.data;

  var authorlink = comment.getElementsByTagName("UL")[0].getElementsByTagName("A")[0];
  if (authorlink == null) {
    authorlink = comment.getElementsByTagName("UL")[0].getElementsByTagName("I")[0];
  }
  var cauthor = authorlink.firstChild.data;

  var datetext = authorlink.nextSibling.data;
  var da = /(\d\d).(\d\d).(\d\d) - (\d\d):(\d\d)/.exec(datetext);

  var cdate = new Date(parseInt("20"+da[3],10),
		    parseInt(da[2],10)-1,
		    parseInt(da[1],10),
		    parseInt(da[4],10),
		    parseInt(da[5],10)
		    );
  var ctime = cdate.getTime();

  var cbody = cheader.nextSibling.nextSibling;

  var cbodydescription = cbody.getElementsByTagName("DIV")[0];
  if (cdepth >1) { //eliminate padding div
    cbodydescription = cbodydescription.getElementsByTagName("DIV")[0];
  }
  
  var ccontents = "";
  if (cbodydescription && cbodydescription.getAttribute("class")=="description") {
    ccontents=cbodydescription.innerHTML;
  } 

  var ccontentsnotags = ccontents.replace(/<([^>]+)>/g,' ').trim();
 var be = new RegExp("^(...............................).*(...............................)$").exec(ccontentsnotags);
  var cshortcontents = ccontentsnotags;
  if (be!=null) {
    cshortcontents = be[1]+"..."+be[2];
  }

  commentsinfo += "<br> titre: " + ctitle + ", auteur: "+ cauthor + " : " + cshortcontents;
  comments.push(new Comment(cauthor,ctime,canchor,cparent,ctitle, ccontents))
  comment=comment.nextSibling.nextSibling;
}

var postdiv = document.createElement("div");
var contentsnotags = contents.replace(/<([^>]+)>/g,' ').trim();

var re = new RegExp("^(...............................).*(...............................)$").exec(contentsnotags);

  var shortcontents = contentsnotags;
  if (re!=null) {
    shortcontents = re[1]+"..."+re[2];
  }

var progressstyle="height:8px; background-color:#000; border:1px solid black; display:inline-block;position:relative;left:-101px;visibility:inherit";

postdiv.innerHTML = "titre: "+title+ ", auteur: "+ author + ", date:" +date + 
  ", type: "+type+", tags: "+tags+ ", publié sur: "+places + ", lu "+readcount+
  " fois, "+visibility + "<br>"+ shortcontents +
"<br><br>"+comments.length+" commentaires:<br>"+
commentsinfo +
"<br><br><span style='border:1px solid black; padding:2px; margin:2px;background-color' id='sendoff'>envoyer au serveur</span>"+
"<span id='progressbar' style='margin-left:40px;visiblity=hidden;'>"+
"<span id='progressall' style='width:100px;height:8px; background-color:#fff; border:1px solid black; display:inline-block;visibility:inherit'> </span>"+
"<span id='progressdone' style='width:0px;"+progressstyle+"'> </span>"+
"</span>";
postdiv.setAttribute("style","padding:10px;background-color:#eef;");
document.getElementsByTagName("body")[0].insertBefore(postdiv,document.getElementsByTagName("body")[0].firstChild);
document.getElementById("sendoff").addEventListener('click',
						    function(){
						      document.getElementById("progressbar").setAttribute("style","margin-left:40px;");
						      sendOff();
						      document.getElementById("progressdone").setAttribute("style","width:10px;"+progressstyle);
						    },false);
