/* shoutout chat 
*uses node.js and jabber
*/

function ui_error (type) {
	switch (type) {
		case "msg":
			notification("Your message could not be sent :( Please try again");
			break;
		case "join":
			notification("There was a problem joining shoutout");
			break;
		case "poll":
			notification(".");
			break;
	}
}

var shoutout = {
	party: false,
	join_url: "index.php?r=party/joinshoutout",
	node_url: Utility.getBaseURL() + "node",
	jid: null,
	default_type: "chat",
	messages: [1],
	guests: [1],				//it's always going to be one to begin with one
	old_guest_length: null,
	lastdata: {},

	timesort: function (timestamp) {
	    return function (a,b) {
	        return (a[timestamp] < b[timestamp]) ? -1 : (a[timestamp] > b[timestamp]) ? 1 : 0;
	    }
	},
	
	/**
	 * set the poll interval
	 * @param {participants}  the number of participants in the particular party
	 */
	
	get_poll_interval: function () {
		//console.log("shoutout.get_poll_interval()");
		return this.get_update_interval(this.guests.length, this.defaults.min_participants, this.defaults.max_participants, this.defaults.min_interval, this.defaults.max_interval);
	},								
	
	
	defaults: {											//defaults
		min_participants: 5,
		max_participants: 1000,
		min_interval: 5,
		max_interval: 60
	},
	
	/**	
	* Interpolate the interval between polls of the shoutout box
	*	based on the number of participants in the box, the minimum expected party attendees
	*	(e.g. 5), the cutoff for max attendees (e.g. 5000)
	*	the minimum poll interval (e.g. 5 seconds) and the max poll interval (e.g. 60 seconds)
	*/
	
	get_update_interval: function (participants, min_participants, max_participants, min_interval, max_interval) {
		//console.log("shoutout.get_update_interval()");
		var normal_participants = Utility.normalise(participants, min_participants, max_participants);
		if (normal_participants < 1) { 	
			return (Utility.linear_interpolate(normal_participants, min_interval, max_interval));
		} else {
			return max_interval;
		}
	},
	
	/**
	 * Get the token string necessary for authenticating shoutout messages
	 */
	
	get_token: function () {
		//console.log("shoutout.get_token()");
		$.getJSON('index.php?r=global/prebind', { node: this.node }, function (data) {
			shoutout.token = data['node'];
		});
		shoutout.token = received_token;
	},
	
	/**
	 * Joins the shoutout for an event
	 * @param {event_code} The event code TODO
	 */
	
	join_shoutout: function (callback) {
        $.ajaxSetup({ cache: false });
		try {
			$.getJSON(shoutout.join_url, 
					{
						space: "time",
						action: "join",
						event_code: shoutout.event_code,
						jid : chat.my_user_jid,
						thumbnail: chat.my_thumbnail,
						user_name: chat.my_user_name
					},
					
					function (data) {
						try {
							if (data.error) {
								ui_error("join")
							}
							$.ajaxSetup({ cache: true });
							shoutout.lastdata = data;
							shoutout.parse_response(false);
							$(document).trigger("update_polling");
							
							if(callback) {
								callback();
							}
						} catch (e) {
							//console.log(e);
						}
				});
		} catch (e) {
			shoutout.error(e);
		}
	},
	
	/**
	 * sends an?action=leave message to node
	 * leaving the party 
	 */	
	leave_shoutout: function () {
        $.ajaxSetup({ cache: false });
		try {
			$.getJSON( shoutout.node_url, 
					{space: "time",
					action: "leave",
					event_code: shoutout.event_code,
					jid: chat.my_user_jid,
					thumbnail: chat.my_thumbnail,
					user_name: chat.my_user_name},
					
					function (data) {
						try {
						if (data.error) {
								ui_error("leave");
						}
						$.ajaxSetup({ cache: true });
						//shoutout.lastdata = data;
						//shoutout.parse_response(false);
						} catch (e) {
							//console.log(e);
						}
				});
		} catch (e) {
			shoutout.error(e);
		}
	},
	
	poll_for_messages: function () {
		
        $.ajaxSetup({ cache: false });

		try {
			$.getJSON( shoutout.node_url, 
					{space: "time",
					action: "poll",
					event_code: shoutout.event_code,
					jid: chat.my_user_jid,
					thumbnail: chat.my_thumbnail,
					user_name: chat.my_user_name,
					type: "chat"},
					
					function (data) {
						try {
							if (data.error) {
								ui_error("poll");
							}
							$.ajaxSetup({ cache: true });
							shoutout.lastdata = data;
							shoutout.parse_response(false);
						} catch (e) {
							shoutout.stop_polling();
							shoutout.error(e);
							//console.log(e);
						}
				});
		} catch (e) {
			shoutout.error(e);
		}
		
	},
	
	/**
	 * Sends a message ("adds a comment") to the shoutout
	 */
	
	send_message: function (message) {
        $.ajaxSetup({ cache: false });
		if (message != "") {
				$.getJSON( shoutout.node_url, 
					{space: "time",
					action: "add_message",
					event_code: shoutout.event_code,
					jid: chat.my_user_jid,
					thumbnail: chat.my_thumbnail,
					user_name: chat.my_user_name,
					msg: message,
					type: "chat"},
					
					function (data) {
						try {
							if (data.error) {
								ui_error("poll");
							}
							$.ajaxSetup({ cache: true });
							shoutout.lastdata = data;
							shoutout.parse_response(false);
							
						} catch (e) {
							//console.log(e);
						}
				});
		}
	},
	
	/**
	 * generic error handler for shoutout.js
	 */
	
	error: function (e) {
		//console.log(e);
		//console.log ("ERROR!!");
		shoutout.stop_polling();
		setTimeout(shoutout.retry, 10000);	
	},
	
	/**
	 *  Parse messages
	 */
	parse_response: function (just_joined) {
		
		try {
			if (shoutout.lastdata) {
				if (shoutout.lastdata.guests) {
					shoutout.old_guest_length = shoutout.guests.length;
					shoutout.guests = [];
		            $.each(shoutout.lastdata.guests, function () {
		                    shoutout.guests.push(this);
		            });
				}
	            this.update_guest_list();
	
	            if (shoutout.lastdata.messages.length > 0) {
	                    shoutout.lastdata.messages.sort(shoutout.timesort("time"));
	                    $.each(shoutout.lastdata.messages, function () {
	                            shoutout.messages.push(this);
	                    });
	            }
	
	            if(just_joined) {
	            	
	                    shoutout.display_messages(shoutout.messages, true);     //all = true
	            } else if (shoutout.lastdata.messages.length > 0) {
	                    shoutout.display_messages(shoutout.lastdata.messages); //all = false
	            }
			}

			
		} catch (e) {
			shoutout.error(e);
		}
	},
	
	/**
	 * Displays the messages. all comes from whether we have just joined (true, in which case show all messages) or if we are just polling
	 * (false, in which case only show the recent messages)
	 * @param {messages} receive messages from shoutout.messages, or shoutout.lastdata.messages
	 */
	
	display_messages: function (messages, all) {
		//console.log("shoutout.display_messages()");
		if (all) {
			$('#sCommentsUL').empty();
		}
		
		//loop through messages
		$.each(messages, function () {
			if (typeof this == "object") {
								
				var time = Utility.timeConverter(this.time);
				var text = this.message_text;
				
				if (!Utility.is_undefined(text)) {
					var profile_id = this.user_jid.split("@")[0];
					
					var dHtml = '<li class="sComment">';
						dHtml +=	'<div class="userImg chatDragger" data-user_jid="' + this.user_jid +'">';
						dHtml +=		'<img class="userImg" src="' + this.thumbnail + '" />';
						dHtml +=	'</div>';
						dHtml +=	'<div>';
						dHtml +=		'<a href="index.php/?r=mystuff/createmessage&amp;userProfile=' + profile_id + '&amp;tab=1" class="replyToMessage userLink">' + this.user_name + '</a>';
						dHtml +=	'</div>';
						dHtml +=	'<p class="sCommentText">' + text + '</p>';
						
						if (chat.my_user_jid != this.user_jid) {	
							dHtml +=	'<ul id="sCommentBottomMenu">';
							dHtml +=		'<li id="sCoomentSendMessage" class="sCommentWrite textLink" data-user_jid="' + this.user_jid +'">message</li>'
							dHtml +=		'<li id="sCommentChat" class="textLink" onclick="chat.create_room(';
							dHtml +=			"'" + this.user_jid+"')";
							dHtml +=			'" data-user_jid="' + this.user_jid +'">chat';
							dHtml +=		'</li>';
											if (!chat.lists.friends.find_user(this.user_jid)) {
												dHtml += '<li id="sCommentAddFriend" class="textLink" href="'+Utility.getBaseURL()+'index.php/?r=mystuff/addfriend&userProfile='+profile_id+'">add as friend</li>';
											}
							dHtml +=	'</ul>';
						}
						
						dHtml +=	'<div class="secDetails">' + time + '</div>';
						dHtml += '</li>';	
					
					$('#sCommentsUL').prepend(dHtml);
					
				}
			}
			
		})
	},
	
	
	/* 
	 * Start polling for new messages
	 * @param interval the interval between each poll
	 */
	
	start_polling: function (interval) {
		shoutout.polling = true;
		//console.log("shoutout.start_polling()");
		shoutout.poll_interval_handler = setInterval(shoutout.poll_for_messages, interval);
	},
	
	/*
	 * Stop polling for messages
	 */
	
	stop_polling: function () {
		clearInterval(shoutout.poll_interval_handler);
		shoutout.polling = false;
	},
	
	retry: function () {
		//console.log("shoutout.retry()");
		setTimeout ( function ()  { $(document).trigger('join_shoutout', {event_code: shoutout.event_code}) }, 5000);
	},
	
	/*
	 * returns the guest with that JID
	 * @param {user_jid} the JID of the guest to be returned
	 */
	
	find_guest_info: function (user_jid) {
		for (var i = 0; i < this.guests.length; i++) {
			if (this.guests[i].user_jid == user_jid) {
				return this.guests[i];
			}
		}
		return false;
	},
	
	/*
	 * update guest_list
	 * TODO comment
	 */
	
	update_guest_list: function () {
		if (shoutout.guests.length == shoutout.old_guest_length) {
		} else {
			$('#friendsOnline ul.guests').empty();
			var html = "";
			
			var items = shoutout.guests;
	
			items.sort(function(a,b){
			       var keyA = a.user_name;
			       var keyB = b.user_name;
			       
			       if (keyA < keyB) return -1;
			       if (keyA > keyB) return 1;
			       return 0;
			});
			
			$.each(items, function() {
				if (this.user_jid != chat.my_user_jid) {
					html += shoutout.create_guest_html(this.user_jid);
				}
			});
			$('#friendsOnline ul.guests').html(html);
			try {
				$(document).trigger('show_host');
			} catch (e) {
				//console.info("?");
			}
		}
	},
	
	create_guest_html: function (user_jid)	{
		
		var guest = shoutout.find_guest_info(user_jid);
		
		if (!guest) {
			guest = chat.lists.friends.find_user(user_jid);
		}
		
		if (guest && guest.user_name && guest.thumbnail) {
			var user_name = guest.user_name || user_jid;
			var thumbnail = guest.thumbnail || null;
		} else {
			var name = "Party guest";
			var thumbail = "http://www.venueone.com/images/avatars/avatar_100_g.jpg";
		}
		
		if (Utility.is_undefined(thumbnail) || user_name == "empty") {
			thumbnail = "http://www.venueone.com/images/avatars/avatar_100_g.jpg";
		}
		
		if (Utility.is_undefined(user_jid) || user_name == "empty") {
			html = "<li class='chatDragger ui-draggable nojid' data-user_name ='";
			html += "Guest";
			html += "'>";
		} else {
			html = "<li class='chatDragger ui-draggable' data-user_jid='";
			html += user_jid.splice || user_jid;
			html += "' data-user_name='";
			html += user_name;
			html += "'>";
		}
		
		html += "<img src='" + thumbnail +"'/>";
		html += "<span class='username'>" + user_name + "</span>";
		html +=	 "</li>";
		return html;
	}

}


/**
 * 
 * sets party = true for core.js
 * sets my JID for the shoutout
 * Sets correctly the event code
 * Joins the shoutout
 * This is triggered by a script tag on the party or stage view
 */

$(document).bind('join_shoutout', function(ev, data){
	$('#guests').addClass('dnone');
	
	shoutout.stop_polling();
	setTimeout ( function () {
			if (chat.my_user_jid) {
				//console.log("LISTENER: start shoutout");
				$('.shoutGuests').removeClass('dnone');
				
				shoutout.event_code = data.event_code;
				shoutout.join_shoutout(data.callback);
			} else {
				notification("You must log in to view or join party shoutout");
			}
	}, 5000);
});


$(document).bind('update_polling', function(){
	shoutout.stop_polling();
	var interval = shoutout.get_poll_interval();		//by this time, join_party() will give us a useful shoutout.guests.length
	shoutout.start_polling(interval * 1000);
});					//TODO trigger this from somewhere



$(document).bind("non_shoutout_room", function () {
	
	shoutout.messages = [];
	shoutout.guests = [];
	shoutout.party = false;
	shoutout.update_guest_list();
	if (shoutout.polling) {
		shoutout.leave_shoutout();
		shoutout.stop_polling();
	}
	$('.shoutGuests').addClass('dnone');
	//console.log("left shoutout"); //TODO delete
});


