var latest_update_time=0
var visible_post_keys = new Array()
var post_update_times = new Array()
var posts = new Array()
var poster_uid = null
var poll_time = 1000

function init_n3xt(wall_id) {  
  //update_all_posts(wall_id)
  queue_update_all_posts(wall_id)        
  poster_uid = FB.Connect.get_loggedInUser()
  if (poster_uid == null) {
    $('#wallpost_form').html('<fb:login-button length="short" size="medium" onlogin="facebook_onlogin();"></fb:login-button>')
     FB.XFBML.Host.parseDomElement(document.getElementById("wallpost_form"));    
  } else {
    $('#user_img').html("<fb:profile-pic size=q uid="+poster_uid+"></fb:profile-pic>")
    FB.XFBML.Host.parseDomElement(document.getElementById("user_img"));    
  }
  $('<div id="pause">PAUSED</div>').insertAfter($("#user_title"));
  $("#wallposts").hover(
	function() {
		$("#pause").addClass("hover")
	},
	function() {
		$("#pause").removeClass("hover")
	})
}





function update_karma() {
  if (poster_uid != null) {
    $.getJSON('http://n3xt.appspot.com/karma?callback=?', {uid:poster_uid}, function(data) {
        var score = data[0]
        var old_score = $('#user_karma').html()
        if (old_score != score) {
          $('#user_karma').html(score)
          $('#user_karma').effect("highlight", {color:'#FFEABD'}, 1500)
        } 
        //var title = data[1]
        //var old_title = $('#user_title').html()
        //if (old_title != title) {
        //  $('#user_title').html(title)
        //  $('#user_title').effect("highlight", {color:'#FFEABD'}, 1500)
        //}         
    })
  }
}

function update_all_posts(wall_id) {
  if (posts_to_slide.length > 0) {
    posts_to_slide = new Array()
  }
  $.ajax({
    url:'http://n3xt.appspot.com/latest/json',
    data:{wall_id:wall_id,timestamp:latest_update_time},
    dataType:'jsonp',
    //error: function(){ queue_update_all_posts(wall_id) },
    success: function(data,textStatus) {
      for (i in data) {
        idx = data.length-parseInt(i)-1
    		if ((!is_paused()) || (!is_new_post(data[idx]))) {
    			update_post(data[idx],wall_id)
    		}
      }
      if (!is_paused()) {
    	  update_poll_time(data.length)
    	}
    	if (posts_to_slide.length > 0) {
        slide_posts()
      }
    }
  })
  update_karma()
}

function update_poll_time(post_count) {
  if (post_count > 0) {
    poll_time = 0.8 * poll_time
  } else {
    poll_time = 1.25 * poll_time
  }
  if (poll_time < 1000) {
    poll_time = 1000
  }
  if (poll_time > 10000) {
    poll_time = 10000
  }
}

function is_new_post(post) {
	for(var i=0; i<visible_post_keys.length; i++){
		if (visible_post_keys[i]==post['key']) {
			return false
		}
	}
  return true
}

function post_should_be_updated(post) {
	return (post_update_times[post['key']] < post['updated_at'])
}

function is_paused() {
  return $("#pause").hasClass('hover')
}

var posts_to_slide = new Array()
function update_post(post,wall_id) {
  var is_new = false
  if (!is_in_boo_list(parseInt(post.facebook_uid))) {
    if (is_new_post(post)) {
     	add_post(post)
      is_new = true
    }
  }
  if (!is_new_post(post)) {
    if (post_should_be_updated(post)) {
      var id = id_for_post(post)
      $('li#'+id).html(render_post(post,wall_id))
      FB.XFBML.Host.parseDomElement(document.getElementById(id));
      post_update_times[post['key']] = post['updated_at']
	
      if ((latest_update_time < post['updated_at']) && (!is_paused())) {
        latest_update_time = post['updated_at']
      }
    	if (post['post_points'] < -11) {
    	  $('li#'+id).addClass("donotshow")
    	}
      if (!is_new) {
        $('li#'+id+' .posttext').effect("highlight", {color:'#FFEABD'}, 1500)
      }
    }
  }
}

function id_for_post(post) {
  return "post_"+post['key']  
}

function add_post(post) {
  var id = id_for_post(post)
  if (posts.length==0) { 
    $('#wallposts ul').prepend(html_for_post(post))
    posts.push(post)
  } else {
    var i = 0
    while (i < posts.length) {
      if (posts[i]['created_at'] < post['created_at']) {
        break
      }
      i += 1
    }
    if (i > 0) {
      //$('li#'+id_for_post(posts[posts.length-1])).after(html_for_post(post))
      //$('#wallposts ul').append(html_for_post(post))
      $('li#'+id_for_post(posts[i-1])).after(html_for_post(post))
      //posts.push(post)
    } else {
      //$('li#'+id_for_post(posts[i])).before(html_for_post(post))
      $('#wallposts ul').prepend(html_for_post(post))
    }
    posts.splice(i,0,post)
  }
  //$('li#'+id).show("blind", { direction: "vertical" }, 500);
  posts_to_slide.push(post)
  visible_post_keys.push(post['key'])
  post_update_times[post['key']] = 0
}

function slide_posts() {
  var i = 0
  for (i in posts_to_slide) {
    $('li#'+id_for_post(posts_to_slide[i])).show("blind", { direction: "vertical" }, 500);
  }
}

function html_for_post(post) {
  return "<li id='"+id_for_post(post)+"'></li>"
}


function render_post(post,wall_id) {
	lineheight=parseInt(post_font_size(post['post_points']))+4;
	
  s = '<span class="user_info">'
  if (post['post_points'] >= 0) {
    s += "<a href='http://facebook.com/profile.php?id="+post['facebook_uid']+"' target='_blank'><fb:profile-pic linked=false size=q uid="+post['facebook_uid']+"></fb:profile-pic></a>"
    s += "<br>"
    s += post['user_points']
  }  
  s += " </span>"

  s += "<span class='posttext " + post['category'] 
  s += "' style='font-size:"+post_font_size(post['post_points'])+"px; line-height:"+lineheight+"px; color:#"+post_font_color(post['post_points'])+";'>"
  if (post['post_points'] < 0) {
    s += "<span class='user_name'><fb:name linked=false uid="+post['facebook_uid']+"></fb:name></span>"
  }
  s += transform_text(post) + "</span>" 

  var feedback = post["feedback"]
  s += "<span class='feedback'>" 
  
  s += "<span class='positive'>"
  s += '<a href="#" class="feedback_link" onclick="submit_feedback(\''+post["key"]+'\',1,'+poster_uid+','+wall_id+','+post.facebook_uid+'); return false;" id="yaa">yaa</a>'
  s += '</span>'
 for (j in feedback) {
    if (parseInt(feedback[j]['value']) > 0) {
	  //s += "<div class='name_pos'><strong>+</strong><fb:profile-pic size=q uid="+feedback[j]['facebook_uid']+'></fb:profile-pic></div>'
      s += "<div class='name_pos'><strong>+</strong><fb:name linked=false lastnameonly=true uid="+feedback[j]['facebook_uid']+'></fb:name></div>'
    }
  }
 for (j in feedback) {
    if (parseInt(feedback[j]['value']) < 0) {
	  //s += "<div class='name_neg'><strong>-</strong><fb:profile-pic size=q uid="+feedback[j]['facebook_uid']+'></fb:profile-pic></div>'
      s += "<div class='name_neg'><strong>-</strong><fb:name linked=false lastnameonly=true uid="+feedback[j]['facebook_uid']+'></fb:name></div>'
    }
  }
s += "<span class='negative'>"
  s += '<a href="#" class="feedback_link" onclick="submit_feedback(\''+post["key"]+'\',-1,'+poster_uid+','+wall_id+','+post.facebook_uid+'); return false;" id="boo">boo</a>'
  s += '</span>'
 
  //s += "<span class='post_points'>"+ post["post_points"] + "</span>"
  
  s += "</span>"
  return s
}

function transform_text(post) {
  var text = post["text"]
  var words = text.split(' ')
  //words = transform_bad_words(words)
  words = transform_links(words)
  text = words.join(' ')
  return text
}

var bad_words = ['fuck','cunt','bitch','asshole','shit']
function transform_bad_words(words) {
  for (var i in words) {
    for (var j in bad_words) {
      if (words[i].toLowerCase() == bad_words[j]) {
        var new_word = ''
      	var chars = "!@#?$%&*";
        for (var k=0;k<words[i].length;k++) {
      		var rnum = Math.floor(Math.random() * chars.length);
          new_word += chars.substring(rnum,rnum+1);
        }
        words[i] = new_word
      }
    }
  }
  return words
}

function transform_links(words) {
  for (i in words) {
    var idx = words[i].search(/http:\/\//)
    if (idx != -1) {
      var display = words[i].slice(idx+7,words[i].length)
      var slashidx = display.search('\\?')
      if (slashidx != -1) {
        display = display.slice(0,slashidx)
      }
      words[i] = '<a href="'+words[i]+'" target="_blank">'+display+'</a>'
    }
  }
  return words
}

function post_font_size(points) {
  return parseInt(points) + 12
}
function post_font_color(v) {
  v = parseInt(v) + 12
  if (v < 2)
    return "fff"
  else if (v < 5)
    return "ddd"
  else if (v < 8)
    return "bbb"
  else if (v < 11)
    return "999"
  else if (v < 14)
    return "777"
  else if (v < 16)
    return "555"
  else if (v < 18)
    return "333"
  else if (v < 20)
    return "111"
  else
    return "000"
}

function queue_update_all_posts(wall_id) {
  update_all_posts(wall_id)
  setTimeout(function(){queue_update_all_posts(wall_id)},poll_time)
}


function wallpost_focus(wall_id) {
	//poster_uid = FB.Connect.get_loggedInUser()
	if ($("#wallpost_text").val()=='Got something to say?') {
		$("#wallpost_text").val('')	
	}
	$(this).bind('keydown', function(e) {
		if(e.keyCode==13) {
			submit_wallpost(wall_id,poster_uid)	// I wonder if it is legit to put this variable in here? or if it should be passed in this or something?
    }
	});
}

function strip_spaces(s) {
  return s.replace(/^\s+|\s+$/g, '')
}

function submit_wallpost(wall_id,uid)
{
	var content = $('#wallpost_text').val()
  content = strip_spaces(content)
  
  if ((content=='Got something to say?') || (content=='')) {
    
  } else {
    $('#wallpost_text').val('')
    $('#formsubmit').attr("disabled","disabled")    
	  var params = { text:content, uid:uid, wall_id:wall_id }  
	  $.getJSON('http://n3xt.appspot.com/post?callback=?', params, function(data) {
	    update_post(data,wall_id)
      $('#formsubmit').removeAttr("disabled")
	  })
	}
}

function submit_feedback(key,val,uid,wall_id,poster_uid) {
  if (!is_in_boo_list(poster_uid)) {
  	$.getJSON('http://n3xt.appspot.com/submit_feedback?callback=?', {post_key:key, value:val, uid:uid}, function(data) {
      update_post(data,wall_id)
  	}) 
    if (val < 0) {
      add_to_boo_list(poster_uid)
    }
  }
}

var _boo_list = []
function add_to_boo_list(uid) {
  if (is_in_boo_list(uid)) {
    return
  }
  _boo_list[_boo_list.length] = uid
  remove_all_posts(uid)
}

function is_in_boo_list(uid) {
  for (var i in _boo_list) {
    if (_boo_list[i]==uid) {
      return true
    }
  }
  return false
}

function remove_all_posts(uid) {
  //TODO
}




