var last = "";
var windowFocus = true;
var chatHeartbeatCount = 0;
var minChatHeartbeat = 1000;
var maxChatHeartbeat = 33000;
var wall_tags = new Array;
function getmessages(tag){
	var tag = (tag == null) ? "" : tag;//this defaults tag to "" if it is unset
	var theURL = document.location.toString();
	if (theURL.match('#') && tag.length == 0) { //if the url contains a tag
		tag = theURL.split('#')[1];		
	}
	var urlparams = "?last="+last+"&tag="+tag+"&user="+$("#MessageContributorId").val(); 
	//grabs the wall ID from the hidden input that holds it on the page
	$.getJSON('../../messages/getwall/'+$('input#MessageWallId').val()+urlparams, function(json){
		var count = 0;
		var message = "";
		var contributor = "";
		var controls = "";
		var voted = false;
		
		if (json.update != null){		
			$.each(json.update, function(i){
				$("#message"+json.update[i].Message.id).html(json.update[i].Message.message);
			});
		}
	
		if (json['delete'] != null){
			$.each(json['delete'], function(i){
				$("#container"+json['delete'][i].Message.id).hide();
			});
		}
		
		if (json.create != null){
			$.each(json.create, function(i){
				var starclass = "";
				var results = "";
				var starred = false;
				var type = "message"; //default type
				if (json.create[i].Contributor.mobile != null){
					type = "sms";
				}
				if (json.create[i].Contributor.twitter_id != null){
					type = "tweet";
				}
				if (json.create[i].Tag.length != 0){//put the tags from the message onto the menu
					$.each(json.create[i].Tag, function(x){
						if ($.inArray(json.create[i].Tag[x].tag, wall_tags) == -1){
							$("#wall_menu").append("<li><a href='#"+json.create[i].Tag[x].tag+"' class='taglink'>#"+json.create[i].Tag[x].tag+"</a></li>");
							wall_tags.push(json.create[i].Tag[x].tag);
						}
					})
				}
				message = "<span id='message"+json.create[i].Message.id+"'>"+json.create[i].Message.message+"</span>";
				contributor = "<span class='contributor'>"+json.create[i].Contributor.name+" says...</span>";
				if (json.create[i].Message.starred == '1'){
					starred = true;
					starclass = "star_on";
				}
				controls = "<a href='star' onclick='return false' class='star "+starclass+"' id='star"+json.create[i].Message.id+"'>Star</a>";
				if(json.create[i].PollOption.length != 0){//if there are any polls associated with this message
					type = "poll";
					results = "<a class='resultslink ui-icon-newwin' href='../../messages/viewchart/"+json.create[i].Message.id+"'>See Live Results</a>";
					//if (json.create[i].Poll_participated == false){
						var polls = "";
						$.each(json.create[i].PollOption, function(x){
							polls = polls+"<a href='#' class='fg-button ui-state-default ui-corner-all' onClick='return false' id='"+json.create[i].PollOption[x].id+"'>Text: "+json.create[i].PollOption[x].id+" to vote "+json.create[i].PollOption[x].text+"</a>";
						});
						if (polls != ""){
							polls = "<div id='votingbuttons"+json.create[i].Message.id+"' class='fg-buttonset'>" + polls + "</div>";
						}
						$('#polloptions').hide("fast");
					/*} else {
						voted = true;
						polls = "<div id='chart"+json.create[i].Message.id+"'></div>";//create an empty div for chart
					}*/
					message = message + polls;
				}
				message = controls + contributor + message + results;
				$("div").removeClass("new");
				$("<div id='container"+json.create[i].Message.id+"'>").addClass(type+" new").css('display', 'none').html(message).prependTo("#wall").slideDown('slow', function(){
				if (type == "poll") {				
					if (voted){//if they've voted, show the chart
						getchart(json.create[i].Message.id,"#chart"+json.create[i].Message.id);
					} else {//else present the buttons
						$('#votingbuttons'+json.create[i].Message.id+' a').click(function() {
							//AJAX post to record the vote with the ID of the button (same as the poll_option_id)	
							$.get("../../responses/add/"+$(this).attr('id'), function(){
								$('#votingbuttons'+json.create[i].Message.id).toggle('slow');
								getchart(json.create[i].Message.id,'#votingbuttons'+json.create[i].Message.id);
								$('#votingbuttons'+json.create[i].Message.id).toggle('slow');							
							});
						}).hover(function(){ 
									$(this).addClass("ui-state-hover"); 
								},
								function(){ 
									$(this).removeClass("ui-state-hover"); 
								});
					}				
				}
				$("#star"+json.create[i].Message.id).data("starred", starred);
				});
				count++;
			});	
		}
		if (count > 0){//if the last check returned some results, update the last timestamp
			last = json.info.last;
		}
	});
}

function getchart (message, div){
var labels = new Array();
var data = new Array();
var max = 0;
$.getJSON("../../messages/getchart/"+message, function(chartData){
	var colors = new Array('navy', 'olive', 'orange', 'purple', 'red', 'aqua', 'black', 'blue', 'fuchsia', 'gray', 'green', 'lime', 'maroon', 'silver', 'teal', 'transparent', 'white', 'yellow');
	$.each(chartData, function(x){
		data[x] = chartData[x].PollOption.response_count;
		labels[x] = chartData[x].PollOption.text;
		if (data[x] > 0){
			max = data[x];
		}
	});
var thedata = [$.gchart.series(data,colors)];
var newAxes = $.gchart.axis('left', 0, max, "black");
$(div).html("");//removes the buttons
$(div).gchart({	type: 'barVert', 
				series: thedata,
				dataLabels: labels,
				axes: [newAxes],
				maxValue: $.gchart.calculate,
				width: 300,
				height: 150,
				barWidth: 50
				});
//$.gchart.barWidthAuto;
$('#removeChart').toggle(function() { 
        $(this).text('Re-attach'); 
        $('#defaultChart').gchart('destroy'); 
    }, 
    function() { 
        $(this).text('Remove'); 
        $('#defaultChart').gchart(); 
    } 
);
});
}
$(document).ready(function() {
	$("#sidebar").data("open", false);//menu starts closed
	getmessages();
	//$.get("../../messages/gettweets/"+$('input#MessageWallId').val());
	//Checks if window is active and starts/stops polling accordingly
	$([window, document]).blur(function(){
		windowFocus = false;
	}).focus(function(){
		windowFocus = true;
	});
	$.timer(8000,function(timer){
		//if (windowFocus == true){			
			getmessages();
	//	}
	});
	/*$.timer(60000,function(timer){
		if (windowFocus == true){			
			$.get("../../messages/gettweets/"+$('input#MessageWallId').val());
		}
	});*/
	/*$("#add_user").click(function (){
		$("#add_user").val("Creating User").attr("disabled","disabled");
	});
	NOTE: This bit doesn't work in safari, as it disables the buttons before the form has been sent
	*/
	//$("#add_message").click(function (){$("#add_message").attr("disabled","disabled")});
	if ($("#MessageContributorId").val() ==""){
		$("#new_contributor").removeAttr("disabled");
		$("#newuser").toggle();
		$("#ContributorName").focus().bind("keyup", function(){
			if ($("textarea#ContributorName").val() != ""){
			$("input#add_user").removeAttr("disabled");//enable submit once there is something typed
			} else {
				$("input#add_user").attr("disabled","disabled");//disable submit if there is nothing typed
			}
		});
		$('#new_contributor').ajaxForm(function(user) {
			$("input#add_user").attr("disabled","disabled");
	 		var user_array = user.split("|");
	 		//$.fn.log(user_array[0]);
	 		$("#newuser").toggle();
			$("#messages_form").toggle();
			$("#MessageContributorId").val(user_array[1]);
			$("#nameholder").prepend(user_array[0]+" ");
			$('#MessageMessage').focus();
		});
	} else {
		$("#messages_form").toggle();
	}
	//TODO: Make the timer ammount longer for production purposes.
	$('#show_poll_options').click(function() {
	     $('#polloptions').toggle('fast');
		 $('#MessagePollOptions').focus();
	   });
	$('#new_message').ajaxForm(function() {
	 	$('textarea').val('');
		$("input#add_message").attr("disabled","disabled");
		$('#MessageMessage').focus();
		getmessages();
	});
	$(".taglink").live("click", function(){
		$("#wall").html("");
		last = "";
		getmessages($(this).html().slice(1));//the "slice" removes the hash from the tag
		//window.location.reload();
	});
	$(".star").live("click", function(){
		var id = $(this).attr("id").substr(4);
		var turn = "on";
		var currentdiv = this;
		$(this).blur();//removes the focus from the star to avoid the nasty dotted border
		if ($(currentdiv).hasClass("star_on")){
			turn = "off";
		}
		$.post("../../messages/star_toggle/"+id+"/"+turn, function(){
			$(currentdiv).toggleClass("star_on");
		});
	});
	$("input#add_message").attr("disabled","disabled");//initialise the submit button as disabled
	$('#MessageMessage').bind("keyup", function(){
		if ($("textarea#MessageMessage").val() != ""){
			$("input#add_message").removeAttr("disabled");//enable submit once there is something typed
		} else {
			$("input#add_message").attr("disabled","disabled");//disable submit if there is nothing typed
		}
	});
	$("#starred_link").click(function(){
		$("#wall").html("");
		last = "";
		getmessages("starred");
	});
});