var jQuery, $, asyncWhile, TreeNode;
/*jslint
 browser:true
*/


function clean(str){
  str = str.replace(/[^a-z\sàéèêëïîôöüûù']/gi, '');
  str = str.replace(/\s+/g, ' ');
  str = str.replace(/\s$/g, '');
  str = str.replace(/http[^\s]+/g, '');
  return str;
}

var aQueueCursor = 0;
var aQueue = [];

//do next thing in the queue, or clear it out
var doQueue = function(){
  if(aQueueCursor < aQueue.length){
    aQueue[aQueueCursor].call();
    aQueueCursor++;
  }
  else{
    aQueue = [];
    aQueueCursor = 0;
  }
};

//function queue, usually animation related
var addToQueue = function(aFn){
  aQueue.push(aFn);
  if(aQueue.length-1 == aQueueCursor){
    doQueue();
  }
};

var i=0;
function puts(text, cible){
  if (typeof(cible) == 'undefined') { cible = "#mainBody";}
  var spantxt = $("<div>"+text+"</div>").css({'display':'none'});
  $(cible).append(spantxt);
  addToQueue(function(){
      $(spantxt).show("drop", {"direction":"up"}, 300, function(){
          doQueue();
        });
    });	
}


function CadavreExquis(debut) {
  if (typeof(debut) == 'undefined'){ throw new Error("Cadavre non initialisé");}

  this.superclass = TreeNode;
  this.superclass();

  //Nombre de mots utilisés pour chaîner les phrases
  this.nb_mots = 3;
  this.phrase = null;
  this.twitt = null;
  this.phrase = clean(debut).split(/\s/).slice(0-this.nb_mots).join(' ');
//  this.childs_computer = null;
  
}

CadavreExquis.prototype = new TreeNode();

//CadavreExquis.prototype.childs_computer = function (node, callback) {
var childs_computer = function (node, callback) {
//  puts("<div style='clear:both;'></div>", "#mainBody");
//  puts("Searching " + node.phrase, "#mainBody");
  $("#searchevents").html("Searching " + node.phrase);
//  puts("Searching " + node.phrase);
  $.twitter.search('"'+node.phrase + '"', function(query, status){
//      puts(query.results.length);
      var nb_mots = node.nb_mots;
      var childs = Array();
      jQuery.each(query.results, function(){ 
//          puts(twittHtml(this));
          var suite = this.text;
          var found_index = suite.toUpperCase().lastIndexOf(node.phrase.toUpperCase());
          if (found_index > -1) {
            var endphrase = suite.slice(found_index + node.phrase.length);
            var mots = endphrase.split(/\s/);
            if (mots.length >= nb_mots){
              var child = new CadavreExquis(suite);
              child.twitt = this;
              childs.push(child);
            }
          }
        });
      callback.call(node, childs);
    }, 'lang=all');
};

var is_plain_sentence = function(node){
  //var phrase = clean(node.phrase);
  var is_plain = (node.phrase !== null) && (node.phrase !== '');
  node.printTreeStatus();
  return is_plain;
};

function recherche(){
  $('#searchevents').html('');
  $('#treeStatus').html('');
  $('#resultat').html('');
  var searchtxt = $('#search')[0].value;
  var depth = 4;
  var cadavre = new CadavreExquis(searchtxt);
  //        cadavre.findcourseAsync(is_plain_sentence, depth, cadavre.childs_computer, function(twits){
  cadavre.findcourseAsync(is_plain_sentence, depth, childs_computer, function(twits){
      var thecadavre=searchtxt;
      var endlast;
      jQuery.each(twits, function() { 
          if (this.twitt !== null) {
            var found_index = this.twitt.text.toUpperCase().lastIndexOf(endlast.toUpperCase());
            var portion = this.twitt.text.slice(found_index + endlast.length);
            thecadavre += " "+portion;
            //                  puts(twittHtml(this.twitt, portion), "#mainBody");
          }
          if (this.phrase !== null) {endlast = this.phrase;}
        });
      puts("<h2>"+thecadavre+"</h2>", "#resultat");
    });
}

$(document).ready(function(){
    $('#recherche').submit(function(){
        recherche();
        return false;
      });
  });

/* cartouche twitter */
function twittHtml(twitt, portion){
  /*
   * created_at
   * from_user
   * from_user_id
   * id
   * iso_language_code
   * profile_image_url
   * source
   * text
   * to_user_id
   */
  html = "<div class='twitt'>";
  html += "<div class='twittmugshot'><img src='"+twitt.profile_image_url+"'></div>";
  html += "<div class='twittcontent'>";
  html += "<span class='twittuser'>"+twitt.from_user+"</span>";
  var message = twitt.text;
  if (typeof(portion) !== 'undefined'){
    message = twitt.text.replace(portion,"<strong>"+portion+"</strong>"); 
  }
  html += "<div class='twittmessage'>"+message+"</div>";
  var decodedsource = $('<textarea/>').html(twitt.source).val();//on décode les entités HTML
  html += "<div class='twittmetas'>";
//  html += "<a href='http://www.twitter.com/"+twitt.from_user+"/statuses/"+twitt.id+"'>"+jQuery.timeago(twitt.created_at)+"</a>";
  html += "<a href='http://www.twitter.com/"+twitt.from_user+"/statuses/"+twitt.id+"'>"+twitt.created_at+"</a>";
  html += " via "+decodedsource;
  html += "</div>";
  html += "</div>";
  html += "</div>";
  return html;
}

CadavreExquis.prototype.printTreeStatus = function(){
  var highlights = this.path().split(':');
//  highlights.shift();
  $("#treeStatus").html("<div>" + this.root().printNodeStatus(0, highlights) + "</div>");
};

CadavreExquis.prototype.printNodeStatus = function (level, highlights){
  if (typeof(level) === 'undefined' ){ level = 0;}
  var numelem = highlights.shift();
  var str = "";
  var numchild = 0;
  var hchild = null;
  var tabChilds = this.childs();
  jQuery.each(tabChilds, function() {
      if (numelem == numchild){
        hchild = this;
        if (level == 0) {
          $("#twittsBox").html(twittHtml(hchild.twitt));
        }
        else {
          puts(twittHtml(hchild.twitt), "#twittsBox");
        }
        str = str + " <strong>o</strong>"
      }
      else {
        str = str + " o";
      }
      numchild++;
  });
  if (hchild !== null){
    str = str + "<br/>" + hchild.printNodeStatus(level+1, highlights, 'twitts');
  }
  return str;
};


