var socket = io.connect( 'http://orangecurve.dedicated.co.za:8080' );

var current_room = localStorage.getItem('room');
if(current_room != undefined || current_room != null)
{
	//alert("leaveroom : " + current_room);
	socket.emit('leaveroom', current_room);
}

var room = getUrlParameterPlain("room");
//alert(room);
room = room.replace(" ","");
room = $.trim(room);

localStorage.setItem('room',room);
socket.emit('create',localStorage.getItem('room'));

//alert(localStorage.getItem('room'));

$("#btnSendMessage").click(function(){
	//alert("here");
	var nameVal = localStorage.getItem('name');
	var msg = $( "#message" ).val();
	$( "#message" ).val("");
	socket.emit( 'message', { name: nameVal, message: msg } );
	
	// Ajax call for saving datas
	$.ajax({
		url: "ajax/insertNewMessage.php",
		type: "POST",
		data: { name: nameVal, message: msg },
		success: function(data) {
			
		}
	});
});

/*$( "#messageForm" ).submit( function() {
	var nameVal = localStorage.getItem('name');
	var msg = $( "#message" ).val();
	var theRoom = localStorage.getItem('room');
	$( "#message" ).val("");
	var datetime = currentdate.getDate() + "/"
                + (currentdate.getMonth()+1)  + "/" 
                + currentdate.getFullYear() + " @ "  
                + currentdate.getHours() + ":"  
                + currentdate.getMinutes() + ":" 
                + currentdate.getSeconds();
	socket.emit( 'message', { name: nameVal, message: msg,messagetime : datetime } );
	
				
	// Ajax call for saving datas
	alert(theRoom);
	$.ajax({
		url: "ajax/insertNewMessage.php",
		type: "POST",
		data: { name: nameVal, message: msg, messagetime : datetime, room : theRoom },
		success: function(data) {
			
		}
	});
	
	return false;
});*/

socket.on( 'message', function( data ) {
	var currentdate = new Date(); 
	var day = "";
	if(currentdate.getDate() < 10)
	{
		day = "0"+currentdate.getDate();
	}
	var datetime = currentdate.getFullYear() + "-"
				+ (currentdate.getMonth()+1)  + "-" 
				+ day + " @ "  
                + currentdate.getHours() + ":"  
                + currentdate.getMinutes() + ":" 
                + currentdate.getSeconds();
	
	var actualContent = $( "#messages" ).html();
	var theClass = "triangle-border left";
	if(data.name == localStorage.getItem('name'))
	{
		theClass = "triangle-border right";
	}
	var html = "<p class='"+theClass+"'><i>"+data.name+ " " +datetime  +"</i>:<br/>"+data.message+"</p>";
	//var newMsgContent = '<li> <strong>' + data.name + '</strong> : ' + data.message + '</li>';
	//var newMsgContent = '<li> '+html+'</li>';
	var newMsgContent = html+'<br/>';
	var content =  actualContent + newMsgContent;
	
	$( "#messages" ).html( content );
});