/**
 * Original:  @author vincent voyer
 * vincent.voyer@gmail.com
 * 
 * Heavily Modified (not necessarily improved): Robert L. Murphy
 * HelloMetro.com
 */
var messageLengthLimit = 256;
var readMore = true;
var currentUsers = 0;
var autoFocus = true;
var showDialog = true;
var mode = "full";
if(typeof newMode !== 'undefined') {
	mode = newMode;
}
var widths = {
		full:{window:425,output:375},
		compact:{window:212,output:185}
	};
var heights= {
		full:{window:500,output:400},
		compact:{window:300,output:200}
	};
// handle close room
function closeTab(id,room_id) {
	//alert("Coming Soon!!!:  You can close/remove " + id);
	var index = -1;
	var room = "";
	var tab = "";
	room = $("#" + id).find("input[name=room]").val();
	//alert(id + "'s room is " + room);
	if(isNaN(room)) {
		tab = room;
	} else {
		tab = $("#" + id).find("input[name=city]").val();
	}
	
	//alert("Tab Label:  " + tab);
	$(".rooms").each(
		function(i,li) {
	
			if(this.id == room_id) {
				//alert("Tab Index:  " + i);
				//$("#rooms").tabs( "remove" , i );
				var newRooms = {};
				for(key in rooms) {
					if(key != room) {
						newRooms[key] = rooms[key];
					}
				}
				rooms = newRooms;
				if($("select option[value=" + room + "]").length == 0) {
					try {
						$('select[name=rooms]')[0].add(new Option(tab, room), null);
					} catch(IESucksBalls) {
						$('select[name=rooms]')[0].add(new Option(tab, room));
					}					
				}
			}
		}
	);
	
	$('#' + room_id).remove();
	$('#' + room_id + '-users').remove();
	room_click(last_id);
	last_id = 'rooms-1';
	
}
// handle edit funciton
function persistTimeStampSetting(id) {
	var on = false;
	if ($("#" + id).find("input[name=timestamps]").attr('checked')) {
		on = true;
	}
	$.post(
		"/ajax/chat/chat.cfm?action=timestamps",
		{id: id,on: on},
		function(data){
			if(typeof data === 'undefined' || typeof data.STATUS === 'undefined') {
				alert("Can't find the cookie jar");
			} else if(data.STATUS != 'Success' && typeof data.ERROR !== 'undefined') {
				alert(data.ERROR);
			}
		},
		'json'
	);
}

function persistCityStampSetting(id) {
	var on = false;
	if ($("#" + id).find("input[name=citystamps]").attr('checked')) {
		on = true;
	}
	$.post(
		"/ajax/chat/chat.cfm?action=citystamps",
		{id: id,on: on},
		function(data){
			if(typeof data === 'undefined' || typeof data.STATUS === 'undefined') {
				alert("Can't find the cookie jar");
			} else if(data.STATUS != 'Success' && typeof data.ERROR !== 'undefined') {
				alert(data.ERROR);
			}
		},
		'json'
	);
}

function persistSoundSetting(id) {
	var on = false;
	if ($("#" + id).find("input[name=sound]").attr('checked')) {
		on = true;
	}
	$.post(
		"/ajax/chat/chat.cfm?action=sound",
		{id: id,on: on},
		function(data){
			if(typeof data === 'undefined' || typeof data.STATUS === 'undefined') {
				alert("Can't find the cookie jar");
			} else if(data.STATUS != 'Success' && typeof data.ERROR !== 'undefined') {
				alert(data.ERROR);
			}
		},
		'json'
	);
}

function edit() {
	autoFocus = false;
	$(".chooseNickname").show();	
	$('#worldChat-nickname-form').dialog('open');
}
function newRoom(id,room,tab,tabs) {
	if($(".rooms").size() >= 5){
		alert("You can only have 5 rooms open at a time.  Please close a room to open up a new one.");			
						
	}else{
	
	if(
		typeof id === 'undefined'
	&&
		typeof room === 'undefined'
	&&
		typeof tab === 'undefined'
	&&
		typeof tabs === 'undefined'
	) {
		// since IE sucks balls, we have to use this convoluted feces
		room = $('select[name=rooms]')[0].options[$('select[name=rooms]')[0].options.selectedIndex].value;
		if(isNaN(room)) {
			
		} else {
			tab = $('select[name=rooms]')[0].options[$('select[name=rooms]')[0].options.selectedIndex].text;
		}
	}
	// set default tab group
	if(typeof tabs === 'undefined') {
		tabs = "rooms";
	}
	// user can specify id, room, tab or any combination of the three
	if(typeof id === 'undefined') {
		// make three values unique if not all three were specified
		if(typeof room !== 'undefined') {
			if(typeof tab !== 'undefined' && isNaN(room)) {
				id = tab.replace(/'/g,'') + "ID";
			} else {
				if(room > 0)
					id = "localChat";
				else {
					id = "ID" + room.replace(/ /g,"").replace(/'/g,'');					
				}
			}
		}
		if(typeof tab !== 'undefined') {
			if(typeof id === 'undefined')
				id = tab.replace(/ /g,"").replace(/'/g,'') + "ID";
			if(typeof room === 'undefined')
				room = tab;			
		}
	}
	// derive unique room from id if necesary
	if(typeof room === 'undefined') {		
		room = id;
		id = room.replace(/ /g,"").replace(/'/g,'') + "ID";
	}
	// derive unique tab from id if necesary
	if(typeof tab === 'undefined') {
		tab = "tab" + id.replace(/ /g,"").replace(/'/g,'');
	}
	if (typeof id !== 'undefined') {
		var exists = false;
		
		$('.rooms').each(
			function(i,li) {
				
				if(this.id.replace('tab', "").toLowerCase() == id.replace(/ /g, "").toLowerCase()) {
					exists = true;
					room_click(this.id);
				}
			}
		);
		
		if (exists == false && $("#" + id.replace(/ /g, "").replace(/'/g,'')).length == 0) {
			
			$.get("/ajax/chat/addRoom.cfm?id=" + id.replace(/ /g, "").replace(/'/g,'') + "&roomID=" + room + "&tab=" + tab.replace(/ /g, "").replace(/'/g,''), function(data) {
			  tempHTML = $('#room_container').html() + data;
			  $('#room_container').html(tempHTML);
			  $('.rooms').click(function(event) {	room_click(this.id);	});
			  
			  $(".rooms").each( function(i,elem){
					$(elem).find(".chat").attr("scrollTop",$(elem).find(".chat").attr("scrollHeight")- $(elem).find(".chat").height())	
				});

			  room_click(tab.replace(/ /g, "").replace(/'/g,''));
			});

			/*var tab_count = $("#" + tabs).tabs("length");
			if(isNaN(room))
				$("#" + tabs).tabs("add", "/ajax/chat/addRoom.cfm?id=" + id.replace(/ /g, "") + "&roomID=" + room + "&tab=" + tab.replace(/ /g, ""), room,tab_count-1);
			else
				$("#" + tabs).tabs("add", "/ajax/chat/addRoom.cfm?id=" + id.replace(/ /g, "") + "&roomID=" + room + "&tab=" + tab.replace(/ /g, ""), tab,tab_count-1);
			//$("#moreRoomsTab").insertAfter($("#moreRoomsTab").next("li"));
			$("#" + tabs).tabs("select",tab_count-1);*/
		} 
		
		/* shouldn't need this
		else {
			$('.rooms').each(
				function(i,elem) {
					if($("#" + this).id.toLowerCase() == $.trim(room).toLowerCase()) {
						$("#" + tabs).tabs("select",i);
					}
				}
			);
		}	*/
	}
	}
}
// handle report
function report(id,reporter,identity,nickname) {
	// Remove display of last abuser's identity
	$("#abuser").remove();
	$("#abuser-nickname").remove();
	
	// Set values to be submitted
	$('#reportAbuse-id').val(id);
	$('#reportAbuse-reporter').val(reporter);	
	$('#reportAbuse-identity').val(identity);
	
	// Display identity of abuser		
	$('#reportAbuse-identity').after("<span id='abuser'>" + identity + "<br/></span>");
	
	// Set and display abuser's nickname
	$('#reportAbuse-nickname').val(nickname);			
	$('#reportAbuse-nickname').after("<span id='abuser-nickname'>" + nickname + "<br/></span>");
	
	// If identity and nickname are the same
	if(identity == nickname) {
		// hide label and remove nickname display
		$('#reportAbuse-nickname-label').hide();
		$("#abuser-nickname").remove();
	} else {
		// show label
		$('#reportAbuse-nickname-label').show();
	}
	// Show abuse description editor
	$('#reportAbuse').dialog('open');
}
// handle boot function
function boot(id,identity){				
	$.post(
		"/ajax/chat/chat.cfm?action=boot",
		{identity: identity,id: id},
		function(data){
			var timestamp = "";
			if ($("input[name=timestamps]").attr('checked')) {
				data.TIME = data.TIME.substring(data.TIME.lastIndexOf(" ") + 1);
				data.TIME = data.TIME.substring(0, data.TIME.lastIndexOf(".")) + data.TIME.substring(data.TIME.length - 4);
				timestamp = '<small>[' + data.TIME + ']</small> ';
			}
			$('.chat').find("div").append(
				'<p><strong>' + timestamp + data.NICKNAME +
				(
					data.CITYNAME == ""
				?
					""
				:
					" <small>(" + data.CITYNAME + ")</small>"
				) +
				':</strong> ' + data.MSG + '</p>'
			);					
		},'json'
	);
}
var do_once_flag = 0;
var rooms = {};
// handle the read messages function
function readMessages() {
	var sqlRooms = "";
	var sqlCities= "";
	var roomDelimiter = "";
	var cityDelimiter = "";
	$.each(
		rooms,
		function(key,value) {
			if (isNaN(key)) {
				sqlRooms += roomDelimiter + "'" + key.replace(/'/g, "''") + "'";
			} else {
				if(cityDelimiter == "")
					sqlRooms += roomDelimiter + "'City'";
				sqlCities += cityDelimiter + key;
				cityDelimiter = ",";
			}
			roomDelimiter = ",";
		}
	);
	$.post(
		"/ajax/chat/chat.cfm?action=read",
		{
			rooms: sqlRooms,
			cities: sqlCities
		},
		function(data){
			if(readMore === true)
				setTimeout("readMessages();", 5 * 1000);
			if(typeof data.MSG !== 'undefined') {							
				$.each(
					data.MSG,
					function(i,msg){
						var timestamp = "";
						var citystamp = "";
						var chatID = "";
						if (msg.ROOM == "City")
							chatID = rooms[msg.CITYID];
						else 
							chatID = rooms[msg.ROOM];
						if($("#" + chatID).find("input[name=timestamps]").attr('checked')) {
							msg.TIME = msg.TIME.substring(msg.TIME.lastIndexOf(" ") + 1);
							msg.TIME = msg.TIME.substring(0, msg.TIME.lastIndexOf(".")) + msg.TIME.substring(msg.TIME.length - 4);
							timestamp = '<small>[' + msg.TIME + ']</small> ';
						}	
						
						if($("#" + chatID).find("input[name=citystamps]").attr('checked')) {
							citystamp = (msg.CITYNAME == "" ? "" : " <small>(" + msg.CITYNAME + ")</small>");
						}				
						soundPlay("MessageReceived", chatID);
						if (msg.MSG == "cornify:" + msg.YOU) {
							if (typeof cornify_add !== 'undefined') {
								cornify_add();
								$("img[src*=getacorn.php]").parent().fadeTo(3,.5);
								$("img[src*=getacorn.php]").fadeTo(3,.5);
							}							
						} else if (msg.MSG == "decornify:" + msg.YOU) {
							//alert("Trying to kill unicorns");
							$("img[src*=getacorn.php]").parent().remove();						
						} else if(msg.MSG.toString().indexOf("cornify:")==0 || msg.MSG.toString().indexOf("decornify:")==0) {
							
						} else {
							
							temp_room_id = $("#" + chatID).parent().parent().attr("id");
							$("#roomlist_" + temp_room_id).css('background-image','url(/ajax/chat/images/star25_25.png)');
							
							$("#" + chatID).find(".chat").find("div").append('<p><strong>' + timestamp + msg.NICKNAME +
							citystamp +
							':</strong> ' +
							msg.MSG +
							'</p>');
						}
						$("#" + chatID).find(".chat").attr("scrollTop",$("#" + chatID).find(".chat").attr("scrollHeight")- $("#" + chatID).find(".chat").height());
						$(".chat").find("div").removeClass("Loading");
						$(".chat").find("div").find("img").hide();
						if(autoFocus == true)
							$("#" + cur_id).find("input[name=message]:visible").focus();
						//$(".Loading").hide();
					}
				);					
			}
			if (
				typeof data.MSG !== 'undefined'
			&&
				data.MSG.length > 0
			) {
				if(
					data.MSG[0].IDENTITY == 'The Server'
				&&
					data.MSG[0].NICKNAME == 'The Server'
				&&
					data.MSG[0].IPADDRESS == '127.0.0.1'
				&&
					data.MSG[0].MSG == 'END TRANSMISSION'
				) {
					readMore = false;
				}
			}
		},
		'json'
	);
		
}

//var userListScrollTop = {};
// handle the current users function
function listUsers() {	
	var sqlRooms = "";
	var sqlCities= "";
	var roomDelimiter = "";
	var cityDelimiter = "";	
	$.each(
		rooms,
		function(key,value) {
			//userListScrollTop[value] = $('#' + value + 'UserList').attr("scrollTop");
			if (isNaN(key)) {
				sqlRooms += roomDelimiter + "'" + key.replace(/'/g, "''") + "'";
			} else {
				if(cityDelimiter == "")
					sqlRooms += roomDelimiter + "'City'";
				sqlCities += cityDelimiter + key;
				cityDelimiter = ",";
			}
			roomDelimiter = ",";
		}
	);
	$.post(
		"/ajax/chat/chat.cfm?action=users",
		{
			rooms: sqlRooms,
			cities: sqlCities
		},
		function(data){
			if(typeof data.USER !== 'undefined') {
				$.each(
					rooms,
					function(key,value) {
						$('#' + value + 'UserList').html("");		
						if(data.USER.length > currentUsers) {
							soundPlay("UserEntered",value);
						} else if(data.USER.length < currentUsers) {
							soundPlay("UserLeft",value);
						}				
					}
				);
				currentUsers = data.USER.length;
				$.each(
					data.USER,
					function(i,user){
						var chatID = "";
						$('#' + chatID + 'UserList').append('<ul>');
						if (user.ROOM == "City")
							chatID = rooms[user.CITYID];
						else 
							chatID = rooms[user.ROOM];
						$('#' + chatID + 'UserList').append(
							'<li><span>' +
							(
								user.YOU == 1
							?
								'<a href="javascript:edit();" title="Edit your nickname."><img style="margin-bottom:-5px;" src="/images/icons/pencil_25x25.png" alt="Edit your nickname." border="0"/></a> '
							:
								(
									user.YOU == 0
								?
									(
										user.LOGGEDIN == 1
									?
										'<a href="javascript:report(' + "'" + chatID + "','" + user.READER.replace(/'/g,"\\'") + "','" + user.IDENTITY.replace(/'/g,"\\'") + "','" + user.NICKNAME.replace(/'/g,"\\'") + "'" + ')" title="Report '+user.NICKNAME+' for abuse of chat room"><img style="margin-bottom:-5px;" src="/images/icons/chat_25x25.png" border="0" alt="Report '+user.NICKNAME+' for abuse of chat room"/></a> '
									:
										'<a href="javascript:boot(' + "'" + chatID + "','" + user.IDENTITY.replace(/'/g,"\\'") + "'" + ')" title="Boot '+user.NICKNAME+' from room"><img style="margin-bottom:-5px;" src="/images/icons/boot_25x25.png" border="0" alt="Boot '+user.NICKNAME+' from room"/></a> '
									)
								:
									' '
								)
							) +
							"</span>" +
							(user.IDENTITY.length > 30 + 15 ? "" + user.NICKNAME + "" : user.NICKNAME) + "</li>"
						);
						$('#' + chatID + 'UserList').append('</ul>');
						if($("select[name=rooms]").length > 0 && user.YOU == 1 && user.LOGGEDIN != 1) {
							$("#moreRooms").html("<p><a href='javascript:edit();'>Log in</a> to enable this feature.</p>");
						} else if($("select[name=rooms]").length == 0 && user.YOU == 1 && user.LOGGEDIN == 1) {
							$("#moreRooms").load("/ajax/chat/enableJoinRooms.cfm");
						}
						//$('#' + chatID + 'UserList').attr("scrollTop",$('#' + chatID + 'UserList').attr("scrollHeight")- $('#' + chatID + 'UserList').height());
					}
				);					
			}
		},
		'json'
	);
	if(readMore === true)
		setTimeout("listUsers()", 5 * 1000);
}
			
(function($){
	$.fn.ajaxChat = function(params){
		
		var params = $.extend({
			refresh:5
		},params);
		
		var chat = function (jElt) {
			//jElt is the jQuery object where the function starts
			var chatContainer=jElt.find('.chat');
			var chat=chatContainer.find('div'); // this is div containing the messages
			var writeInput=jElt.find('.writeInput');
			var chooseNickname=jElt.find('.chooseNickname');
			var ajaxStatus=jElt.find('.ajaxStatus');
			var id = jElt.attr("id");
			var readMore = true;
			var currentUsers = $("#" + id + "UserList").find("br").length;
			var userCount = 0;
			rooms[jElt.find(".chat").find("input[name=room]").val()] = id;
			
			// handle the submit message function
			var activateKeyboard = function(){
				writeInput.submit(function(){
					var input = $(this).find('input[name=message]');
					var message = input.val();
					if(
						message.toString().toLowerCase() == "yes"
					||
						message.toString().toLowerCase() == "no"
					||
						message.toString().indexOf(".0") == message.toString().length -2
					)
					 	message = " " + message + " ";
					
					if ($.trim(message).length > messageLengthLimit) {
						alert("Sorry, we have a "+messageLengthLimit+" character limit");						
					} else if ($.trim(message).length > 0) { // need to have something to say !
						ajaxStatus.show();
						
						input.val('');
						input.blur();
						input.attr("disabled", "disabled"); // we have to this so there'll be less spam messages
						if(message == "read" && readMore == false) {
							readMore = true;
							setTimeout("readMessages();",5*1000);
							setTimeout("listUsers();",7.5*1000);
							input.removeAttr("disabled");
							if(autoFocus == true)
								input.focus();
						} else {
							$.post("/ajax/chat/chat.cfm?action=write", { //this is the url of your server side script that will handle write function
								msg: message,
								id: id
							}, function(data){
								input.removeAttr("disabled");
								if(autoFocus == true)
									input.focus();
								if (data) {
									var timestamp = "";
									var citystamp = "";
									if (jElt.find("input[name=timestamps]").attr('checked')) {
										data.TIME = data.TIME.substring(data.TIME.lastIndexOf(" ") + 1);
										data.TIME = data.TIME.substring(0, data.TIME.lastIndexOf(".")) + data.TIME.substring(data.TIME.length - 4);
										timestamp = '<small>[' + data.TIME + ']</small> ';
									}
									
									
								if (jElt.find("input[name=citystamps]").attr('checked')) {
									citystamp = (data.CITYNAME == "" ? "" : " <small>(" + data.CITYNAME + ")</small>");
								}
									chat.append(
										'<p><strong>' + timestamp + data.NICKNAME +
										citystamp +
										':</strong> ' + data.MSG + '</p>'
									);									
									jElt.find(".chat").attr("scrollTop", jElt.find(".chat").attr("scrollHeight")- jElt.find(".chat").height());
								}
								ajaxStatus.hide();
							}, 'json');
						}
					}
					
					return false;
				});
			}
			
			// handle the read messages function
			var readMessages = function(){
				$.post(
					"/ajax/chat/chat.cfm?action=read",
					{id: id},
					function(data){
						if(typeof data.MSG !== 'undefined') {							
							$.each(data.MSG, function(i,msg){
								var timestamp = "";
								if (jElt.find("input[name=timestamps]").attr('checked')) {
									msg.TIME = msg.TIME.substring(msg.TIME.lastIndexOf(" ") + 1);
									msg.TIME = msg.TIME.substring(0, msg.TIME.lastIndexOf(".")) + msg.TIME.substring(msg.TIME.length - 4);
									timestamp = '<small>[' + msg.TIME + ']</small> ';
								}	
								soundPlay("MessageReceived",id);		
								
								
								chat.append(
									'<p><strong>' +timestamp+msg.NICKNAME +
									(
										msg.CITYNAME == ""
									?
										""
									:
										" <small>(" + msg.CITYNAME + ")</small>"
									) +
									':</strong> '+msg.MSG+'</p>'
								);

							
								jElt.find(".chat").attr("scrollTop",jElt.find(".chat").attr("scrollHeight")- jElt.find(".chat").height());
								jElt.find(".chat").find("div").removeClass("Loading");
								jElt.find(".chat").find("div").find("img").hide();
							});					
						}
						if (
							typeof data.MSG !== 'undefined'
						&&
							data.MSG.length > 0
						) {
							if(
								data.MSG[0].IDENTITY == 'The Server'
							&&
								data.MSG[0].NICKNAME == 'The Server'
							&&
								data.MSG[0].IPADDRESS == '127.0.0.1'
							&&
								data.MSG[0].MSG == 'END TRANSMISSION'
							) {
								readMore = false;
							}
						}
				},'json');
				if(readMore === true)
					setTimeout(readMessages, params.refresh * 1000);
			}
			// handle the current users function
			var listUsers = function(){
				$.post(
					"/ajax/chat/chat.cfm?action=users",
					{id: id},
					function(data){
						if(typeof data.USER !== 'undefined') {
							$('#' + id + 'UserList').html("");
							if(data.USER.length > currentUsers) {
								soundPlay("UserEntered",id);
							} else if(data.USER.length < currentUsers) {
								soundPlay("UserLeft",id);
							}
							currentUsers = data.USER.length;
							$.each(data.USER, function(i,user){
								$('#' + id + 'UserList').append(
									'<span style="padding:5px;">' +
									(
										user.YOU == 1
									?
										'<a href="javascript:edit();" title="Edit your nickname."><img style="margin-bottom:-5px;" src="/images/very-tiny-pencil.png" alt="Edit your nickname." border="0"/></a> '
									:
										(
											user.YOU == 0
										?
											(
												user.LOGGEDIN == 1
											?
												'<a href="javascript:report(' + "'" + id + "','" + user.READER.replace(/'/g,"\\'") + "','" + user.IDENTITY.replace(/'/g,"\\'") + "','" + user.NICKNAME.replace(/'/g,"\\'") + "'" + ')" title="Report '+user.NICKNAME+' for abuse of chat room"><img style="margin-bottom:-5px;" src="/images/icons/chat_25x25.png" border="0" alt="Report '+user.NICKNAME+' for abuse of chat room"/></a> '
											:
												'<a href="javascript:boot(' + "'" + id + "','" + user.IDENTITY.replace(/'/g,"\\'") + "'" + ')" title="Boot '+user.NICKNAME+' from room"><img style="margin-bottom:-5px;" src="/images/very-tiny-boot.png" border="0" alt="Boot '+user.NICKNAME+' from room"/></a> '
											)
										:
											' '
										)
									) +
									(user.IDENTITY.length > 30 + 15 ? "<small>" + user.NICKNAME + "</small>" : user.NICKNAME) + "</span><br/>"
								);
								$('#' + id + 'UserList').attr("scrollTop",$('#' + id + 'UserList').attr("scrollHeight")- $('#' + id + 'UserList').height());
							});					
						}
					},
					'json'
				);
				if(readMore === true)
					setTimeout(listUsers, params.refresh * 5 * 1000);
			}
			// handle room changes function
			var roomChange = function(){
				$.post(
					"/ajax/chat/chat.cfm?action=room",
					{room: jElt.find('select[name=room] option:selected').val(),id: id},
					function(data){
						chat.html("<img alt='Loading...' src='/images/ajax-loader.gif'/>");
						//$('.ajaxStatus').show();
					}
				);
			}
			
			chooseNickname.submit(function(){
				var tryNickname=$(this).find(':input:first').val();
				
				$.post("/ajax/chat/chat.cfm?action=nickname", { //this is the url of your server side script that will handle write function
					nickname: tryNickname,
					id: id
				}, function(data){
					if (data) {
						chooseNickname.hide();
						$(".chooseNickname").hide();
						chatContainer.show();
						writeInput.show();
						//readMessages();
						
						writeInput.find(':input').val('has joined the room').parent().trigger('submit');
						
					} else {
						alert('bad nickname, try something else !');
					}
				}, 'json');
				
				return false;
			});
			
			// uncomment line below to require handle for reading.
			//chatContainer.hide();
			if($('#' + id + '-nickname').val() == "") {
				writeInput.hide();
				if($("#" + id + "-nickname-form").dialog) {
					if($("#" + id + "-nickname-form").dialog('isOpen')) {

					} else if(showDialog == true) {
						showDialog = false;
						$(".chooseNickname").show();
						$("#" + id + "-nickname-form").dialog('open');
					} else {
						writeInput.show();
					}
				}
				//chooseNickname.show();
			} else {
				writeInput.show();
				$(".chooseNickname").hide();
				//chooseNickname.hide();
			}
			ajaxStatus.hide();
			
			activateKeyboard();
			jElt.find('select[name=room]').change(roomChange);
			//setTimeout(readMessages, params.refresh * 1000);
			//setTimeout(listUsers,params.refresh * 5 * 1000);
		}
		
		return this.each(function(){
			chat($(this));
		});		
	};
})(jQuery)

//$(
//	function() {
		//$('#rooms').tabs({cache:true});
		//$('.tabs-bottom .ui-tabs-nav, .tabs-bottom .ui-tabs-nav > *').removeClass('ui-corner-all ui-corner-top').addClass('ui-corner-bottom');
		//$('#rooms').bind(
		//	'tabsshow',
		//	function(event,ui) {				
		//		$(ui.panel).find(".chat").attr("scrollTop",$(ui.panel).find(".chat").attr("scrollHeight")-$(ui.panel).find(".chat").height());
		//		/*if($(ui.panel).find("a[name*=-bottom]").length > 0)
		//			$(ui.panel).find("a[name*=-bottom]")[0].scrollIntoView(true);*/		
		//	}
		//);
//	}
//);

$(
	
	function() {		
		var description = $('#reportAbuse-description'),
		reporter = $('#reportAbuse-reporter'),
		identity = $('#reportAbuse-identity'),
		id = $('#reportAbuse-id'),
		allFields = $([]).add(description).add(reporter).add(identity).add(id),
		tips = $('.validateTips');
		$('#reportAbuse').dialog(
			{
				autoOpen: false,
				height: 350,
				width: 350,
				modal: true,
				zIndex:100000001,
				buttons: {
					'Send Report': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');
					if (bValid) {
						$.post(
							'/ajax/chat/chat.cfm?action=report',
							{ //this is the url of your server side script that will handle write function
								description: description.val(),
								id: id.val(),
								reporter: reporter.val(),
								identity: identity.val()
							},
							function(data){
								if (data) {
									if(typeof data.MSG !== 'undefined') {
										alert(data.MSG);
									}
									$('#reportAbuse').dialog('close');									
								} else {
									alert("Something didn't work, try again.");
								}
							},
							'json'
						);	
					}
				}
			},
			close: function() {
				autoFocus = true;
				allFields.val('').removeClass('ui-state-error');
			}
		});
	}
);		


$(
	
	function() {		
		var nickname = $('#worldChat-nickname'),
		username = $('#worldChat-username'),
		password = $('#worldChat-password'),
		allFields = $([]).add(nickname).add(username).add(password),
		tips = $('.validateTips'),
		keyUpHandler = function(e) {
				if((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
					//alert("TAB then SPACEBAR or click button with mouse");
					var bValid = true;
					allFields.removeClass('ui-state-error');
					if (bValid) {
						$.post(
							'/ajax/chat/chat.cfm?action=nickname',
							{ //this is the url of your server side script that will handle write function
								nickname: nickname.val(),
								id: 'worldChat',
								username: username.val(),
								password: password.val()
							}, function(data){
								if (data) {									
									if(typeof data.MSG !== 'undefined') {
										alert(data.MSG);
									}
									if (typeof data.ERROR !== 'undefined') {
										$("#worldChat-username").addClass("ui-state-error");
										$("#worldChat-password").addClass("ui-state-error");
										alert(data.ERROR);
									} else {
										//chooseNickname.hide();
										$('.chat').each(function(i){
											$(this).show();
										});
										$('.writeInput').each(function(i){
											$(this).show();
										});
										$('.writeInput').each(function(i){
											$(this).find(':input').val('has joined the room').parent().trigger('submit');
										});								
										$(".chooseNickname").hide();
										$('#worldChat-nickname-form').dialog('close');
									}					
								} else {
									alert('bad nickname, try something else !');
								}
							},
							'json'
						);	
					}
				}
			}
		;
		$(nickname).keyup(keyUpHandler);
		$(username).keyup(keyUpHandler);
		$(password).keyup(keyUpHandler);
		$('#worldChat-nickname-form').dialog({
			autoOpen: false,
			height: 350,
			width: 350,
			zIndex:100000001,
			modal: true,
			buttons: {
				'Log out': function() {
					$.post(
						'/ajax/chat/chat.cfm?action=logout',
						{},
						function(data){
							if (data) {
								if(typeof data.MSG !== 'undefined') {
									alert(data.MSG);
								}
								if (typeof data.ERROR !== 'undefined') {
									alert(data.ERROR);
								}
								$('.chat').each(function(i){
									$(this).show();
								});
								$('.writeInput').each(function(i){
									$(this).show();
								});
								$(".chooseNickname").hide();
								$('#worldChat-nickname-form').dialog('close');
							} else {
								alert('bad nickname, try something else !');
							}
						},
						'json'
					);	
				},
				'Create a nickname': function() {
				var bValid = true;
				allFields.removeClass('ui-state-error');
				if (bValid) {
					$.post(
						'/ajax/chat/chat.cfm?action=nickname',
						{ //this is the url of your server side script that will handle write function
							nickname: nickname.val(),
							id: 'worldChat',
							username: username.val(),
							password: password.val()
						}, function(data){
							if (data) {
								if(typeof data.MSG !== 'undefined') {
									alert(data.MSG);
								}
								if (typeof data.ERROR !== 'undefined') {
									$("#worldChat-username").addClass("ui-state-error");
									$("#worldChat-password").addClass("ui-state-error");
									alert(data.ERROR);
								} else {
									//chooseNickname.hide();
									$('.chat').each(function(i){
										$(this).show();
									});
									$('.writeInput').each(function(i){
										$(this).show();
									});
									$('.writeInput').each(function(i){
										$(this).find(':input').val('has joined the room').parent().trigger('submit');
									})
									$(".chooseNickname").hide();
									$('#worldChat-nickname-form').dialog('close');
								}	
							} else {
								alert('bad nickname, try something else !');
							}
						},
						'json'
					);	
				}
			}
		},
		close: function() {
			allFields.val('').removeClass('ui-state-error');
		}
	}
);		
/*$('#create-nickname')
	.button()
	.click(function() {
		$('#worldChat-nickname-form').dialog('open');
	});*/

});
//======================================================================
var soundEmbed = null;
//======================================================================
function soundPlay(which,id)
    {
		if (typeof id == 'undefined' || $("#" + id).find("input[name=sound]").attr("checked")) {
			if (!soundEmbed) {
				soundEmbed = document.createElement("embed");
				soundEmbed.setAttribute("src", "http://media1.hellometro.com/ajax/chat/sound/" + which + ".wav");
				soundEmbed.setAttribute("hidden", true);
				soundEmbed.setAttribute("autostart", true);
			}
			else {
				document.body.removeChild(soundEmbed);
				soundEmbed.removed = true;
				soundEmbed = null;
				soundEmbed = document.createElement("embed");
				soundEmbed.setAttribute("src", "http://media1.hellometro.com/ajax/chat/sound/" + which + ".wav");
				soundEmbed.setAttribute("hidden", true);
				soundEmbed.setAttribute("autostart", true);
			}
			soundEmbed.removed = false;
			document.body.appendChild(soundEmbed);
		}
    }
//======================================================================
$(
	function() {
		$("input[name=sound]").click(
			function(checkbox) {
				soundPlay("MessageReceived");				
			}
		);
	}
);
setTimeout("readMessages();",5*1000);
setTimeout("listUsers();",7.5*1000);




/*--- carasel code ---*/
var cur_id = 'nothing';
var last_id = 'nothing';

function room_click(this_id_var){
	if(this_id_var != cur_id){
		last_id = cur_id;
		cur_id = this_id_var;
		var id_num = cur_id.replace(/rooms-/i,'');
		
		var rooms_max = 5;
		var rooms_i = 0;
		var rooms_z = 1;
		var rooms_mid = 0;
		var rooms_passflag = 0;
		var roomlist_html = "<ul>";
		
		//get middle room
		$("*[class^=rooms]").each(function(){
			rooms_i++;
			if (cur_id == this.id)	rooms_mid = rooms_i;
		});
		rooms_total = rooms_i;
		$('#room_container').css('padding-left',(60 - (rooms_total * 9)));
		
		rooms_i = rooms_mid;
		
		//reposition rooms based on center room
		$("*[class^=rooms]").each(function(){
			
			if(rooms_passflag ==0)rooms_i--;
			else rooms_i++;
			
			if(rooms_passflag ==0)rooms_z++;
			else rooms_z--;
			
			$(this).css('z-index',rooms_passflag - rooms_i );
			
			if (this.id <= cur_id){
				$(this).find("h3").css('text-align','left');
			}else{
				$(this).find("h3").css('text-align','right');
			}
			if (cur_id == this.id){
				rooms_passflag = 1;
				$(this).animate(
					{
						opacity: 1,
						width:
							widths[mode]["window"] +
							(60 * (rooms_max - rooms_total)),
						height: heights[mode]["window"],
						top: 25 * rooms_i
					},
					200
				);
				$(this).css('background-image','url(/images/home/back3x395.png)');
				$(this).css('background-color','#d2dbe8');
				$(this).css('z-index','100');
				$(this).css('margin-right','-350' + 'px');
				
				$(this).find(".chat_close_button").css('display','block');
				$(this).find(".chat").css('height',heights[mode]["output"]+'px');
				$(this).find(".chat").css('width',(widths[mode]["output"]-5) + (60 * (rooms_max - rooms_total)) + 'px');
				$(this).find(".chat_input").css('width',(widths[mode]["output"]-5) + (60 * (rooms_max - rooms_total)) + 'px');
				
				$('#' + this.id + '-users').css('z-index','100');
				roomlist_html = roomlist_html + '<li id="roomlist_' + this.id + '" class="current_room"><a href="javascript:room_click(\'' + this.id + '\')">' + $(this).find('h3:first').text() + '</li>';
			}else{
				$(this).animate({opacity: .55,width: widths[mode]["window"],height: heights[mode]["window"] - (50 * rooms_i),top: 25 * rooms_i}, 200);
				$(this).css('background-image','none');
				$(this).css('background-color','#fff');
				$(this).css('z-index',100  - rooms_i);
				$(this).css('margin-right','-350' + 'px');				

				$('#' + this.id + '-users').css('z-index','99');
				$(this).find(".chat_close_button").css('display','none');
				$(this).find(".chat").css('height',heights[mode]["output"] - (50 * rooms_i) + 'px');
				$(this).find(".chat").css('width',widths[mode]["output"] + 'px');
				$(this).find(".chat_input").css('width',widths[mode]["output"] + 'px');
				
				roomlist_html = roomlist_html + '<li id="roomlist_' + this.id + '"><a href="javascript:room_click(\'' + this.id + '\')">' + $(this).find('h3:first').text() + '</a></li>';
			}
			
		});
		roomlist_html = roomlist_html + "</ul>" ;
		$('#roomlist_content').html(roomlist_html);
		if($('#roomlist_content').html() != roomlist_html) {
			$('#roomlist_content')[0].innerHTML = roomlist_html;
		}

	}
}

jQuery(function($) {
	$('.rooms').click(function(event) {	room_click(this.id);	});
});



