	
	navigator.getUserMedia = navigator.getUserMedia ||
		navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
		
	console.log(navigator.getUserMedia);
	
	var peer = new Peer(username, {
		host: server_ip, 
		port: 9000, 
		key: 'pskey'
	});
	peer.on('open', function(){ console.log('Peer open:', peer); });
	peer.on('connection', acceptConnection);
	
	peer.on('call', function(call){
		call.answer(window.localStream);
		acceptCall(call);
    });
	
	function chatHandshake(user){
		createConnection('chathandshake', user.username);		
	}
	
	function openChat(user){
		createConnection('chathandshake', user.username);		
	}
	
	function callHandshake(user){
		createConnection('callhandshake', user.username);
	}
	
	function openCall(user){
		createConnection('callhandshake', user.username);
	}
	
	function dataHandshake(user){
		createConnection('datahandshake', user.username);
	}
	
	function dataSync(user){
		createConnection('datahandshake', user.username);
	}
	
	var syncs = [];
	var syncCounter = 1;
	
	function acceptCall(call){
	
		var sync = {};
		
		call.answer(window.localStream);
		
		call.on('stream', function(stream){
		
			$(document.body).append('\
				<div id="call-'+syncCounter+'" class="callpane" \
					style="display: block; width: 330px; height: 300px;\
						background: url(ui/shards/images/callpane.png);\
						background-size: 100% 100%; color: white; position: absolute;\
						z-index: 50000; position: absolute; left: 35%; top: 38%;">\
					<video class="video" autoplay\
						style="width: 70%; height: 58%; border: 1px solid white;\
						position: absolute; left: 12%; top: 21%;"></video>\
					<div class="call-close" style="position: absolute; width: 4%; height: 4%;\
						right: 12.0%; bottom: 9%;">\
						<img class="close-icon" src="/prismshards/ui/shards/icons/close.png"\
							style="width: 100%; height: 100%;\
							z-index: 20; position: absolute;" />\
					</div>\
				</div>\
			');
			element = $('#call-' + syncCounter)[0];
			$(element).draggable();
			$(element).resizable({aspectRatio: true});
			
			sync = {id: syncCounter, element: element,
				connections: [call], stream: stream, type: 'call'};
			syncs.push(sync);
			
			syncCounter++;
			
			$(sync.element).find('.video').prop('src', URL.createObjectURL(stream));

			$(sync.element).find('.call-close').click(function(){
				for (var i=0; i<sync.connections.length; i++){
					sync.connections[i].close();
				}
			});
			
		});
		
		call.on('close', function(data){
		
			removeFromArray(sync.connections, call);
			
			if (sync.stream.stop) sync.stream.stop();
			
			if (sync.connections.length == 0){
				$(sync.element).fadeOut(400, function(){
					$(sync.element).remove();
					removeFromArray(syncs, sync);
				});
			}
			
		});
			
	}
	
//************************* CREATE CONNECTION ****************************//
	function createConnection(type, name, sync){	
	
		if (undef(sync)) var sync = {};

//*************************** CALL HANDSHAKE *****************************//
		if (type == 'callhandshake'){
				
			var connection = peer.connect(name, {
				label: 'callhandshake',
				serialization: 'none',
				reliable: false
			});
			
			var element = false;
			
			connection.on('open', function(){
				$(document.body).append('\
					<div id="call-'+syncCounter+'" class="callpane" \
						style="display: block; width: 330px; height: 300px;\
							background: url(ui/shards/images/callpane.png);\
							background-size: 100% 100%; color: white; position: absolute;\
							z-index: 50000; position: absolute; left: 35%; top: 38%;">\
						<div style="width: 100%; margin-top: 42%; text-align: center;\
							margin-left: -2.5%;">\
							Waiting on call confirmation...\
						</div>\
						<video class="video" autoplay\
							style="width: 70%; height: 58%; border: 1px solid white;\
						position: absolute; left: 12%; top: 21%;"></video>\
						<div class="chat-close" style="position: absolute; width: 4%; height: 4%;\
							right: 11.0%; bottom: 8%;">\
							<img class="close-icon" src="/prismshards/ui/shards/icons/close.png"\
								style="width: 100%; height: 100%;\
								z-index: 20; position: absolute;" />\
						</div>\
					</div>\
				');
				element = $('#call-' + syncCounter)[0];
				$(element).draggable();
				
				sync = {id: syncCounter, element: element,
					connections: [], type: 'call'};
				syncs.push(sync);
				
				syncCounter++;
				
			});
			
			connection.on('data', function(data){
				
				if (data == '!accept!'){
					createConnection('call', name, sync);				
				}
				if (data == '!deny!'){
				
					$(sync.element).html('\
						<div style="width: 100%; margin-top: 45%; text-align: center;\
							margin-left: 3%;">\
							Call declined.\
						</div>\
					');
					
					setTimeout(function(){
						$(sync.element).fadeOut(500, function(){
							$(sync.element).remove();
						});
					}, 5000);
					
				}
				connection.close();
				
			});
			
			connection.on('error', function(err){ alert(err); });
			
		}
		
//**************************** NEW CALL ******************************//	
		if (type == 'call'){
		
			navigator.getUserMedia({audio: true, video: true}, function(stream){

				window.localStream = stream;
				
				var call = peer.call(name, window.localStream);
				
				sync.connections.push(call);
				sync.stream = stream;
			
				call.on('stream', function(stream){
					$(sync.element).find('.video').prop('src', URL.createObjectURL(stream));
				});
				
				call.on('close', function(data){
			
					removeFromArray(sync.connections, call);
					
					if (sync.stream.stop) sync.stream.stop();
					
					if (sync.connections.length == 0){
						$(sync.element).fadeOut(400, function(){
							$(sync.element).remove();
							removeFromArray(syncs, sync);
						});
					}
					
				});
				
			}, function(){ console.log('Call Error.'); });
			
		}
		
//************************** DATA HANDSHAKE ******************************//	
		if (type == 'datahandshake'){
			
		}
		
				
//*************************** CHAT HANDSHAKE *****************************//
		if (type == 'chathandshake'){
				
			var connection = peer.connect(name, {
				label: 'chathandshake',
				serialization: 'none',
				reliable: false
			});
			
			var element = false;
			
			connection.on('open', function(){
				$(document.body).append('\
					<div id="chat-'+syncCounter+'" class="chatpane" \
						style="display: block; width: 300px; height: 300px;\
							background: url(ui/shards/images/chatpane.png);\
							background-size: 100% 100%; color: white; position: absolute;\
							z-index: 50000; position: absolute; left: 35%; top: 38%;">\
						<div style="width: 100%; margin-top: 45%; text-align: center;\
							margin-left: 3%;">\
							Waiting on chat confirmation...\
						</div>\
					</div>\
				');
				element = $('#chat-' + syncCounter)[0];
				$(element).draggable();
				
				sync = {id: syncCounter, element: element,
					connections: [], type: 'chat'};
				syncs.push(sync);
				
				syncCounter++;
				
			});
			
			connection.on('data', function(data){
				
				if (data == '!accept!'){
					createConnection('chat', name, sync);				
				}
				if (data == '!deny!'){
				
					$(sync.element).html('\
						<div style="width: 100%; margin-top: 45%; text-align: center;\
							margin-left: 3%;">\
							Chat declined.\
						</div>\
					');
					
					setTimeout(function(){
						$(sync.element).fadeOut(500, function(){
							$(sync.element).remove();
						});
					}, 5000);
					
				}
				connection.close();
				
			});
			
			connection.on('error', function(err){ alert(err); });
			
		}

//************************** CHAT ADD HANDSHAKE ***************************//
		if (type == 'chataddhandshake'){
				
			var connection = peer.connect(name, {
				label: 'chataddhandshake',
				serialization: 'none',
				reliable: false
			});
			
			connection.on('open', function(data){
				
				var msgdiv = $(sync.element).find('.chatmessages');
				
				msgdiv.append(
					'<div style="color: gray;"><i>Chat request sent to '+name+'.</i></div>');
					
				msgdiv[0].scrollTop = msgdiv[0].scrollHeight;
				
			});
			
			connection.on('data', function(data){
				
				if (data == '!accept!'){
					createConnection('chatadd', name, sync);				
				}
				if (data == '!deny!'){
				
					var msgdiv = $(sync.element).find('.chatmessages');
				
					msgdiv.append(
						'<div style="color: gray;"><i>'+name+' declined your chat invitation.</i></div>');
					
					msgdiv.scrollTop[0] = msgdiv.scrollHeight[0];
					
				}
				
				connection.close();
				
			});
			
			connection.on('error', function(err){ alert(err); });
			
		}
		
//*************************** ADD TO CHAT *******************************//	
		if (type == 'chatadd'){
		
			var tnames = [];
		
			for (var i=0; i<sync.connections.length; i++){
				tnames.push(sync.connections[i].peer);
			}
		
			var connection = peer.connect(name, {
				label: 'chatadd',
				serialization: 'none',
				reliable: false,
				metadata: {chatlist: implodeArray(tnames), creator: username}
			});
			sync.connections.push(connection);
			
			connection.on('data', function(data){
			
				$(sync.element).find('.chatmessages').append('<div><span class="peer">'
					+connection.peer+'</span>: '+data+'</div>');
				
			});
			
			connection.on('close', function(data){
			
				removeFromArray(sync.connections, connection);
				
				if (sync.connections.length == 0){
					$(sync.element).fadeOut(400, function(){
						$(sync.element).remove();
						removeFromArray(syncs, sync);
					});
				}
				
			});
			
		} 
	
	
//**************************** NEW CHAT ******************************//	
		if (type == 'chat'){
		
			var connection = peer.connect(name, {
				label: 'chat',
				serialization: 'none',
				reliable: false
			});
			sync.connections.push(connection);
				
			syncs.push(sync);
				
			$(sync.element).html('\
				<div class="chatmessages divscrollbar" style="color: black; overflow-y: scroll;\
					width: 70%; height: 50%; background: white; position: absolute;\
					left: 19%; top: 20%;"></div>\
				<div class="chatactions" style="color: black; position: absolute;\
					left: 19%; top: 72%; width: 70%; height: 12%;">\
					<form class="chatsend" style="width: 100%; height: 90%;">\
						<input type="text" class="chattext _resizetext"\
							placeholder="Enter message" data-fontsize="0.8"\
							style="border-radius: 0px; width: 70%; height: 80%;\
							position: absolute; left: 0%; top: 0%;"></input>\
						<input class="button _resizetext" type="submit" value="Send" style="\
							position: absolute; width: 27%; height: 80%;\
							left: 72%; top: 0%;" data-fontsize="0.6"></input>\
					</form>\
				</div>\
				<div class="chat-fade chat-arrow" style="position: absolute; width: 6%; height: 6%;\
					left: 81%; top: 12%; background: url(/prismshards/ui/shards/icons/srarrow.png);\
					background-size: 100% 100%;">\
					<!--<img src="/prismshards/ui/shards/icons/srarrow.png"\
						style="width: 100%; height: 100%; position: absolute;" />-->\
					<img class="fade-icon" src="/prismshards/ui/shards/icons/srarrow2.png"\
						style="width: 100%; height: 100%; display: none;\
						z-index: 20; position: absolute;" />\
				</div>\
				<div class="chat-fade chat-addto" style="position: absolute; width: 6%; height: 6%;\
					left: 73%; top: 12%;">\
					<img src="/prismshards/ui/shards/icons/plus.png"\
						style="width: 100%; height: 100%; position: absolute;" />\
					<img class="fade-icon" src="/prismshards/ui/shards/icons/plus2.png"\
						style="width: 100%; height: 100%; display: none;\
						z-index: 20; position: absolute;" />\
				</div>\
				<div class="chat-fade chat-handle" style="position: absolute; width: 22%; height: 7%;\
					left: 71.0%; top: 4.5%;">\
					<img class="fade-icon" src="/prismshards/ui/shards/icons/chathandle.png"\
						style="width: 100%; height: 100%; display: none;\
						z-index: 20; position: absolute;" />\
				</div>\
				<div class="chat-close" style="position: absolute; width: 4%; height: 4%;\
					left: 16.0%; bottom: 12%;">\
					<img class="close-icon" src="/prismshards/ui/shards/icons/close.png"\
						style="width: 100%; height: 100%;\
						z-index: 20; position: absolute;" />\
				</div>\
				<!--<div class="chat-min" style="position: absolute; width: 4%; height: 4%;\
					left: 21.0%; bottom: 12%;">\
					<img class="min-icon" src="/prismshards/ui/shards/icons/minimize.png"\
						style="width: 100%; height: 100%;\
						z-index: 20; position: absolute;" />\
				</div>-->\
				<div id="chat-list-'+syncCounter+'" style="position: absolute;\
					width: 50%; height: 60%; left: 95.0%; top: 1%;\
					background: url(/prismshards/ui/shards/icons/inchatpane.png);\
					background-size: 100% 100%; display: none;">\
					<select class="chat-select" multiple style="position: absolute;\
						width: 70%; height: 65%; left: 16%; top: 13%; border: 0px;" ></select>\
					<div class="chat-fade chat-plus" style="position: absolute; width: 10%; height: 8%;\
						left: 45%; top: 81%; display: none;">\
						<img src="/prismshards/ui/shards/icons/plus.png"\
							style="width: 100%; height: 100%; position: absolute;" />\
						<img class="fade-icon" src="/prismshards/ui/shards/icons/plus2.png"\
							style="width: 100%; height: 100%; display: none;\
							z-index: 20; position: absolute;" />\
					</div>\
					<div class="chat-fade chat-minus" style="position: absolute; width: 10%; height: 8%;\
						left: 45%; top: 81%;">\
						<img src="/prismshards/ui/shards/icons/minus.png"\
							style="width: 100%; height: 100%; position: absolute;" />\
						<img class="fade-icon" src="/prismshards/ui/shards/icons/minus2.png"\
							style="width: 100%; height: 100%; display: none;\
							z-index: 20; position: absolute;" />\
					</div>\
				</div>\
			');
			
			var sidepanel = $('#chat-list-'+syncCounter)[0];
			
			syncCounter++;
			
			$(sync.element).css({
				width: '300px',
				height: '300px'
			});
			$(sync.element).data('sidepanel', 'closed');
			
			$(sync.element).find('.chat-close').click(function(){
				for (var i=0; i<sync.connections.length; i++){
					sync.connections[i].close();
				}
			});
			$(sync.element).find('.chat-fade').hover(function(){
					$(this).find('.fade-icon').stop().fadeIn();
				},
				function(){
					$(this).find('.fade-icon').stop().fadeOut();
				});
			$(sync.element).find('.chat-arrow').click(function(){
					if ($(sync.element).data('sidepanel') == 'closed'){
						$(sidepanel).stop().fadeIn();
						$(sync.element).data('sidepanel', 'minus');
					}
					else if ($(sync.element).data('sidepanel') == 'minus'){
						$(sidepanel).stop().fadeOut();
						$(sync.element).data('sidepanel', 'closed');
					}
					else if ($(sync.element).data('sidepanel') == 'plus'){
						$(sync.element).data('sidepanel', 'minus');
					}
					$(sync.element).find('.chat-plus').fadeOut();
					$(sync.element).find('.chat-minus').fadeIn();
					
					$(sync.element).find('.chat-select').html('');
						
					for (var i=0; i<sync.connections.length; i++){
						$(sync.element).find('.chat-select').append('<option id="'+
							sync.connections[i].peer+'" class="friend" style="height: 5%;">'+
							sync.connections[i].peer+'</option>');
					}
					
					$(sync.element).find('.chat-minus')[0].onclick = function(){
							
						var selected = $.map(
							$(sync.element).find('.chat-select option:selected'),
								function(e) { return $(e).val(); } 
						);
						
						$(sync.element).find('.chat-select option:selected').remove();
						
						for (var i=0; i<sync.connections.length; i++){
							for (var j=0; j<selected.length; j++){
								if (sync.connections[i].peer == selected[j]){
									sync.connections[i].send('!!!!!close!!!!!');
									sync.connections[i].close();
								}
							}
						}					
						
					};
					
				});
			$(sync.element).find('.chat-addto').click(function(){
					if ($(sync.element).data('sidepanel') == 'closed'){
						$(sidepanel).stop().fadeIn();
						$(sync.element).data('sidepanel', 'plus');
					}
					else if ($(sync.element).data('sidepanel') == 'plus'){
						$(sidepanel).stop().fadeOut();
						$(sync.element).data('sidepanel', 'closed');
					}
					else if ($(sync.element).data('sidepanel') == 'minus'){
						$(sync.element).data('sidepanel', 'plus');
					}
					$(sync.element).find('.chat-plus').fadeIn();
					$(sync.element).find('.chat-minus').fadeOut();
					
					queryDB({
						opts: {
							query: 'selectuser',
							id: user_id
						},
						callback: function(data){
						
							user = jsonDeserialize(data);
							
							if (user.friends != '0'){
								user.friends = explodeString(user.friends);
							}
							else user.friends = [];
							
							$(sync.element).find('.chat-select').html('');
								
							for (var i=0; i<user.friends.length; i++){
								$(sync.element).find('.chat-select').append('<option id="'+
									user.friends[i]+'" class="friend" style="height: 5%;">'+
									user.friends[i]+'</option>');
							}
								
							$(sync.element).find('.chat-plus')[0].onclick = function(){
							
								var selected = $.map(
									$(sync.element).find('.chat-select option:selected'),
									function(e) { return $(e).text(); } 
								);
								
								for (var i=0; i<selected.length; i++){
									createConnection('chataddhandshake', selected[i], sync);
								}
								
								console.log(selected);

							};
							
						}
					}, '/prismshards/query.php');
				});
			
			
				
			$(sync.element).draggable({
				handle: ".chat-handle"
			});
			$(sync.element).resizable({
				aspectRatio: true,
				resize: function(event, ui){
					var tr = $(element).find('._resizetext');
					var uiW = $(element).width();
					if (tr) for (var i=0; i<tr.length; i++){
						tr[i].style.fontSize = 
							(uiW * 0.065 * $(tr[i]).data('fontsize')) + 'px';
						tr[i].style.lineHeight = 
							(uiW * 0.065 * $(tr[i]).data('fontsize')) + 'px';
					}
				}
			});
			
			/*var dropbox = $(sync.element);
	
			dropbox.on('dragenter', doNothing);
			dropbox.on('dragover', doNothing);
			dropbox.on('drop', function(e){
			
				e.originalEvent.preventDefault();
				var file = e.originalEvent.dataTransfer.files[0];
				
				eachActiveConnection(function(c, $c) {
					if (c.label === 'file') {
						c.send(file);
						$c.find('.messages').append('\
							<div><span class="file">You sent a file.</span></div>');
					}
				});
				
			});*/

			$(sync.element).find('.chatclose').click(function(){
				for (var i=0; i<sync.connections.length; i++){
					sync.connections[i].close();
				}
			});
			
			$(sync.element).find('.chatsend').submit(function(e) {
			
				e.preventDefault();				
				var msg = $(sync.element).find('.chattext').val();
				if (msg == '') return;
				
				for (var i=0; i<sync.connections.length; i++){
					sync.connections[i].send(msg);
				}
				
				var msgdiv = $(sync.element).find('.chatmessages');
				
				msgdiv.append(
					'<div><span class="you">You: </span>'+msg+'</div>');
					
				msgdiv[0].scrollTop = msgdiv[0].scrollHeight;
				
				$(sync.element).find('.chattext').val('');
				$(sync.element).find('.chattext').focus();
				
			});
			
			connection.on('data', function(data){
			
				var msgdiv = $(sync.element).find('.chatmessages');
				
				if (data == '!!!!!close!!!!!'){
					for (var i=0; i<sync.connections.length; i++){
						sync.connections[i].close();
					}
					
					return;
				}
			
				msgdiv.append('<div><span class="peer">'
					+connection.peer+'</span>: '+data+'</div>');
					
				msgdiv[0].scrollTop = msgdiv[0].scrollHeight;
				
			});
			
			connection.on('close', function(data){
			
				removeFromArray(sync.connections, connection);
				
				if (sync.connections.length == 0){
					$(sync.element).fadeOut(400, function(){
						$(sync.element).remove();
						removeFromArray(syncs, sync);
					});
				}
				
			});
			
		} 
		
//**************************** FILE ******************************//
		if (type === 'file'){
		
			var connection = peer.connect(name, { label: 'file' });
			 
			connection.on('open', function(){});
			
			connection.on('error', function(err){ alert(err); });
		
			connection.on('data', function(data){
				
				if (data.constructor === ArrayBuffer){
					var dataView = new Uint8Array(data);
					var dataBlob = new Blob([dataView]);
					var url = window.URL.createObjectURL(dataBlob);
					$('#' + c.peer).find('.messages').append('<div><span class="file">' +
						c.peer + ' has posted a <a target="_blank" href="' +
						url + '">file</a>.</span></div>');
				}
				
			});
			
		}
		
		if (connection) return connection;
		else return false;
		
	}

///**************************** ACCEPT CONNECTION ******************************//	
	function acceptConnection(connection){
	
		var sync = {};
		
///**************************** CALL HANDSHAKE ******************************//	
	if (connection.label == 'callhandshake' ||
		connection.label == 'calladdhandshake'){
		
		var hiarray = ['Hey!','Listen!','Hello!'];
		var randomhi = hiarray[Math.floor(Math.random() * hiarray.length)];
		
		openDialog({
			title: randomhi,
			height: ($(window).height()*0.45),
			width: ($(window).height()*0.55),
			confirm: 'Yes',
			cancel: 'No',
			type: 'confirm',
			onConfirm: function(){
				
				navigator.getUserMedia({audio: true, video: true}, function(stream){
					window.localStream = stream;
					connection.send('!accept!');
				}, function(){});
				closeDialog();
				
			},
			onCancel: function(){
				connection.send('!deny!');
				closeDialog();
			},
			content: '<div style="padding: '+
				($(window).height()*0.04)+'px; font-size: '+
				($(window).height()*0.04)+'px;">\
				Accept call from '+connection.peer+'?\
				</div>'
		});
		
	}

///**************************** DATA HANDSHAKE ******************************//		
		if (connection.label == 'datahandshake'){
		
		}
		
///**************************** CHAT HANDSHAKE ******************************//	
		if (connection.label == 'chathandshake' ||
			connection.label == 'chataddhandshake'){
			
			var hiarray = ['Hey!','Listen!','Hello!'];
			var randomhi = hiarray[Math.floor(Math.random() * hiarray.length)];
			
			openDialog({
				title: randomhi,
				height: ($(window).height()*0.45),
				width: ($(window).height()*0.55),
				confirm: 'Yes',
				cancel: 'No',
				type: 'confirm',
				onConfirm: function(){
					connection.send('!accept!');
					closeDialog();
				},
				onCancel: function(){
					connection.send('!deny!');
					closeDialog();
				},
				content: '<div style="padding: '+
					($(window).height()*0.04)+'px; font-size: '+
					($(window).height()*0.04)+'px;">\
					Accept chat from '+connection.peer+'?\
					</div>'
			});
			
		}
	
///*************************** ADD TO CHAT *******************************//	
		if (connection.label == 'chatadd'){
		
			if (connection.metadata.chatlist){
				
				$(document.body).append('\
					<div id="chat-'+syncCounter+'" class="chatpane" \
						style="display: block; width: 300px; height: 300px;\
							background: url(ui/shards/images/chatpane.png);\
							background-size: 100% 100%;\
							color: white; position: absolute; z-index: 50000;\
							position: absolute; left: 35%; top: 38%;">\
						<div style="width: 100%; margin-top: 5%; text-align: center;">\
							Waiting on chat confirmation...\
						</div>\
					</div>\
				');
				element = $('#chat-'+syncCounter)[0];
				
				sync = {id: syncCounter, element: element, creator: connection.peer,
					connections: [connection], type: 'chat'};
				
				syncs.push(sync);
					
				$(sync.element).html('\
					<div class="chatmessages divscrollbar" style="color: black; overflow-y: scroll;\
						width: 70%; height: 50%; background: white; position: absolute;\
						left: 19%; top: 20%;"></div>\
					<div class="chatactions" style="color: black; position: absolute;\
						left: 19%; top: 72%; width: 70%; height: 12%;">\
						<form class="chatsend" style="width: 100%; height: 90%;">\
							<input type="text" class="chattext _resizetext"\
								placeholder="Enter message" data-fontsize="0.8"\
								style="border-radius: 0px; width: 70%; height: 80%;\
								position: absolute; left: 0%; top: 0%;"></input>\
							<input class="button _resizetext" type="submit" value="Send" style="\
								position: absolute; width: 27%; height: 80%;\
								left: 72%; top: 0%;" data-fontsize="0.6"></input>\
						</form>\
					</div>\
					<div class="chat-fade chat-arrow" style="position: absolute; width: 6%; height: 6%;\
						left: 81%; top: 12%; background: url(/prismshards/ui/shards/icons/srarrow.png);\
						background-size: 100% 100%;">\
						<!--<img src="/prismshards/ui/shards/icons/srarrow.png"\
							style="width: 100%; height: 100%; position: absolute;" />-->\
						<img class="fade-icon" src="/prismshards/ui/shards/icons/srarrow2.png"\
							style="width: 100%; height: 100%; display: none;\
							z-index: 20; position: absolute;" />\
					</div>\
					<div class="chat-fade chat-handle" style="position: absolute; width: 22%; height: 7%;\
						left: 71.0%; top: 4.5%;">\
						<img class="fade-icon" src="/prismshards/ui/shards/icons/chathandle.png"\
							style="width: 100%; height: 100%; display: none;\
							z-index: 20; position: absolute;" />\
					</div>\
					<div class="chat-close" style="position: absolute; width: 4%; height: 4%;\
						left: 16.0%; bottom: 12%;">\
						<img class="close-icon" src="/prismshards/ui/shards/icons/close.png"\
							style="width: 100%; height: 100%;\
							z-index: 20; position: absolute;" />\
					</div>\
					<!--<div class="chat-min" style="position: absolute; width: 4%; height: 4%;\
						left: 21.0%; bottom: 12%;">\
						<img class="min-icon" src="/prismshards/ui/shards/icons/minimize.png"\
							style="width: 100%; height: 100%;\
							z-index: 20; position: absolute;" />\
					</div>-->\
					<div id="chat-list-'+syncCounter+'" style="position: absolute;\
						width: 50%; height: 60%; left: 95.0%; top: 1%;\
						background: url(/prismshards/ui/shards/icons/inchatpane.png);\
						background-size: 100% 100%; display: none;">\
						<select class="chat-select" multiple style="position: absolute;\
							width: 70%; height: 65%; left: 16%; top: 13%; border: 0px;" ></select>\
					</div>\
				');
				
				var sidepanel = $('#chat-list-'+syncCounter)[0];
				
				syncCounter++;
				
				$(sync.element).css({
					width: '300px',
					height: '300px'
				});
				$(sync.element).data('sidepanel', 'closed');
				
				
				$(sync.element).find('.chat-close').click(function(){
					for (var i=0; i<sync.connections.length; i++){
						sync.connections[i].close();
					}
				});
				$(sync.element).find('.chat-fade').hover(function(){
						$(this).find('.fade-icon').stop().fadeIn();
					},
					function(){
						$(this).find('.fade-icon').stop().fadeOut();
					});
				$(sync.element).find('.chat-arrow').click(function(){
						if ($(sync.element).data('sidepanel') == 'closed'){
							$(sidepanel).stop().fadeIn();
							$(sync.element).data('sidepanel', 'minus');
						}
						else if ($(sync.element).data('sidepanel') == 'minus'){
							$(sidepanel).stop().fadeOut();
							$(sync.element).data('sidepanel', 'closed');
						}
						else if ($(sync.element).data('sidepanel') == 'plus'){
							$(sync.element).data('sidepanel', 'minus');
						}
						$(sync.element).find('.chat-plus').fadeOut();
						$(sync.element).find('.chat-minus').fadeIn();
						
						$(sync.element).find('.chat-select').html('');
							
						for (var i=0; i<sync.connections.length; i++){
							$(sync.element).find('.chat-select').append('<option id="'+
								sync.connections[i].peer+'" class="friend" style="height: 5%;">'+
								sync.connections[i].peer+'</option>');
						}
						
						
					});
					
				$(element).draggable({
					handle: ".chat-handle"
				});
				$(element).resizable({
					aspectRatio: true,
					resize: function(event, ui){
						var tr = $(element).find('._resizetext');
						var uiW = $(element).width();
						if (tr) for (var i=0; i<tr.length; i++){
							tr[i].style.fontSize = 
								(uiW * 0.065 * $(tr[i]).data('fontsize')) + 'px';
							tr[i].style.lineHeight = 
								(uiW * 0.065 * $(tr[i]).data('fontsize')) + 'px';
						}
					}
				});
				
				/*var dropbox = $(sync.element).find('#messages');
		
				dropbox.on('dragenter', doNothing);
				dropbox.on('dragover', doNothing);
				dropbox.on('drop', function(e){
				
					e.originalEvent.preventDefault();
					var file = e.originalEvent.dataTransfer.files[0];
					
					eachActiveConnection(function(c, $c) {
						if (c.label === 'file') {
							c.send(file);
							$c.find('.messages').append('\
								<div><span class="file">You sent a file.</span></div>');
						}
					});
					
				});*/

				$(sync.element).find('.chatclose').click(function(){
					for (var i=0; i<sync.connections.length; i++){
						sync.connections[i].close();
					}
				});
				
				$(sync.element).find('.chatsend').submit(function(e) {
				
					e.preventDefault();				
					var msg = $(sync.element).find('.chattext').val();
					if (msg == '') return;
					
					for (var i=0; i<sync.connections.length; i++){
						sync.connections[i].send(msg);
					}
					
					var msgdiv = $(sync.element).find('.chatmessages');
					
					msgdiv.append(
						'<div><span class="you">You: </span>'+msg+'</div>');
						
					msgdiv[0].scrollTop = msgdiv[0].scrollHeight;
					
					$(sync.element).find('.chattext').val('');
					$(sync.element).find('.chattext').focus();
					
				});
				
				connection.on('data', function(data){
				
					var msgdiv = $(sync.element).find('.chatmessages');
					
					if (data == '!!!!!close!!!!!'){
					
						while (sync.connections.length > 0){
							sync.connections[0].close();
						}
						
						return;
					}
				
					msgdiv.append('<div><span class="peer">'
						+ connection.peer + '</span>: ' + data + '</div>');
						
					msgdiv[0].scrollTop = msgdiv[0].scrollHeight;
					
				});
				
				connection.on('close', function(data){
				
					removeFromArray(sync.connections, connection);
					
					if (sync.connections.length == 0){
						$(sync.element).fadeOut(400, function(){
							$(sync.element).remove();
							removeFromArray(syncs, sync);
						});
					}
					
				});
				
				var tpeers = explodeString(connection.metadata.chatlist);
				
				for (var i=0; i<tpeers.length; i++){
				
					var nconnection = peer.connect(tpeers[i], {
						label: 'chatadd',
						serialization: 'none',
						reliable: false,
						metadata: {creator: connection.metadata.creator}
					});
					sync.connections.push(nconnection);
					
					nconnection.on('data', function(data){
					
						var msgdiv = $(sync.element).find('.chatmessages');
						
						if (data == '!!!!!close!!!!!'){
							for (var j=0; j<sync.connections.length; j++){
								sync.connections[j].close();
							}
							console.log(sync);
							return;
						}
					
						msgdiv.append('<div><span class="peer">'
							+ nconnection.peer + '</span>: ' + data + '</div>');
							
						msgdiv[0].scrollTop = msgdiv[0].scrollHeight;
						
					});
					
					nconnection.on('close', function(data){
					
						removeFromArray(sync.connections, nconnection);
						
						if (sync.connections.length == 0){
							$(sync.element).fadeOut(400, function(){
								$(sync.element).remove();
								removeFromArray(syncs, sync);
							});
						}
						
					});
				}
				
			}
			else {
			
				for (var i=0; i<syncs.length; i++){
					if (syncs[i].type == 'chat' && 
						syncs[i].creator == connection.metadata.creator){
							syncs[i].connections.push(connection);
							sync = syncs[i];
					}
				}
				
				connection.on('data', function(data){
				
					var msgdiv = $(sync.element).find('.chatmessages');
					
					if (data == '!!!!!close!!!!!'){
						for (var i=0; i<sync.connections.length; i++){
							sync.connections[i].close();
						}
							console.log(sync);
						return;
					}
					
					/*if (sync.creator == connection.peer && 
						data.indexOf('!!!!!drop!!!!!') != -1){
						for (var i=0; i<sync.connections.length; i++){
							if (sync.connections[i].peer == data.substring(14, data.length))
								sync.connections[i].close();
						}
						return;
					}*/
				
					msgdiv.append('<div><span class="peer">'
						+ connection.peer + '</span>: ' + data + '</div>');
						
					msgdiv[0].scrollTop = msgdiv[0].scrollHeight;
					
				});
				
				connection.on('close', function(data){
				
					removeFromArray(sync.connections, connection);
					
					if (sync.connections.length == 0){
						$(sync.element).fadeOut(400, function(){
							$(sync.element).remove();
							removeFromArray(syncs, sync);
						});
					}
					
				});
				
			}
			
		} 

///******************************* NEW CHAT ********************************//		
		if (connection.label == 'chat'){
		
			var element = false;
			
			$(document.body).append('\
				<div id="chat-'+syncCounter+'" class="chatpane" \
					style="display: block; width: 300px; height: 300px;\
						background: url(ui/shards/images/chatpane.png);\
						background-size: 100% 100%;\
						color: white; position: absolute; z-index: 50000;\
						position: absolute; left: 35%; top: 38%;">\
					<div style="width: 100%; margin-top: 5%; text-align: center;">\
						Waiting on chat confirmation...\
					</div>\
				</div>\
			');
			element = $('#chat-'+syncCounter)[0];
			
			sync = {id: syncCounter, element: element, creator: connection.peer,
				connections: [connection], type: 'chat'};
			
			syncs.push(sync);
				
			$(sync.element).html('\
				<div class="chatmessages divscrollbar" style="color: black; overflow-y: scroll;\
					width: 70%; height: 50%; background: white; position: absolute;\
					left: 19%; top: 20%;"></div>\
				<div class="chatactions" style="color: black; position: absolute;\
					left: 19%; top: 72%; width: 70%; height: 12%;">\
					<form class="chatsend" style="width: 100%; height: 90%;">\
						<input type="text" class="chattext _resizetext"\
							placeholder="Enter message" data-fontsize="0.8"\
							style="border-radius: 0px; width: 70%; height: 80%;\
							position: absolute; left: 0%; top: 0%;"></input>\
						<input class="button _resizetext" type="submit" value="Send" style="\
							position: absolute; width: 27%; height: 80%;\
							left: 72%; top: 0%;" data-fontsize="0.6"></input>\
					</form>\
				</div>\
				<div class="chat-fade chat-arrow" style="position: absolute; width: 6%; height: 6%;\
					left: 81%; top: 12%; background: url(/prismshards/ui/shards/icons/srarrow.png);\
					background-size: 100% 100%;">\
					<!--<img src="/prismshards/ui/shards/icons/srarrow.png"\
						style="width: 100%; height: 100%; position: absolute;" />-->\
					<img class="fade-icon" src="/prismshards/ui/shards/icons/srarrow2.png"\
						style="width: 100%; height: 100%; display: none;\
						z-index: 20; position: absolute;" />\
				</div>\
				<div class="chat-fade chat-handle" style="position: absolute; width: 22%; height: 7%;\
					left: 71.0%; top: 4.5%;">\
					<img class="fade-icon" src="/prismshards/ui/shards/icons/chathandle.png"\
						style="width: 100%; height: 100%; display: none;\
						z-index: 20; position: absolute;" />\
				</div>\
				<div class="chat-close" style="position: absolute; width: 4%; height: 4%;\
					left: 16.0%; bottom: 12%;">\
					<img class="close-icon" src="/prismshards/ui/shards/icons/close.png"\
						style="width: 100%; height: 100%;\
						z-index: 20; position: absolute;" />\
				</div>\
				<!--<div class="chat-min" style="position: absolute; width: 4%; height: 4%;\
					left: 21.0%; bottom: 12%;">\
					<img class="min-icon" src="/prismshards/ui/shards/icons/minimize.png"\
						style="width: 100%; height: 100%;\
						z-index: 20; position: absolute;" />\
				</div>-->\
				<div id="chat-list-'+syncCounter+'" style="position: absolute;\
					width: 50%; height: 60%; left: 95.0%; top: 1%;\
					background: url(/prismshards/ui/shards/icons/inchatpane.png);\
					background-size: 100% 100%; display: none;">\
					<select class="chat-select" multiple style="position: absolute;\
						width: 70%; height: 65%; left: 16%; top: 13%; border: 0px;" ></select>\
				</div>\
			');
			
			var sidepanel = $('#chat-list-'+syncCounter)[0];
			
			syncCounter++;
			
			$(sync.element).css({
				width: '300px',
				height: '300px'
			});
			$(sync.element).data('sidepanel', 'closed');
			
			
			$(sync.element).find('.chat-close').click(function(){
				for (var i=0; i<sync.connections.length; i++){
					sync.connections[i].close();
				}
			});
			//$(sync.element).find('.chat-min').click(function(){
			//	$(sync.element).css('height', '35px');
			//});
			$(sync.element).find('.chat-fade').hover(function(){
					$(this).find('.fade-icon').stop().fadeIn();
				},
				function(){
					$(this).find('.fade-icon').stop().fadeOut();
				});
			$(sync.element).find('.chat-arrow').click(function(){
					if ($(sync.element).data('sidepanel') == 'closed'){
						$(sidepanel).stop().fadeIn();
						$(sync.element).data('sidepanel', 'minus');
					}
					else if ($(sync.element).data('sidepanel') == 'minus'){
						$(sidepanel).stop().fadeOut();
						$(sync.element).data('sidepanel', 'closed');
					}
					else if ($(sync.element).data('sidepanel') == 'plus'){
						$(sync.element).data('sidepanel', 'minus');
					}
					$(sync.element).find('.chat-plus').fadeOut();
					$(sync.element).find('.chat-minus').fadeIn();
					
					$(sync.element).find('.chat-select').html('');
						
					for (var i=0; i<sync.connections.length; i++){
						$(sync.element).find('.chat-select').append('<option id="'+
							sync.connections[i].peer+'" class="friend" style="height: 5%;">'+
							sync.connections[i].peer+'</option>');
					}
					
					
				});
				
			$(element).draggable({
				handle: ".chat-handle"
			});
			$(element).resizable({
				aspectRatio: true,
				resize: function(event, ui){
					var tr = $(element).find('._resizetext');
					var uiW = $(element).width();
					if (tr) for (var i=0; i<tr.length; i++){
						tr[i].style.fontSize = 
							(uiW * 0.065 * $(tr[i]).data('fontsize')) + 'px';
						tr[i].style.lineHeight = 
							(uiW * 0.065 * $(tr[i]).data('fontsize')) + 'px';
					}
				}
			});
			
			/*var dropbox = $(sync.element).find('#messages');
	
			dropbox.on('dragenter', doNothing);
			dropbox.on('dragover', doNothing);
			dropbox.on('drop', function(e){
			
				e.originalEvent.preventDefault();
				var file = e.originalEvent.dataTransfer.files[0];
				
				eachActiveConnection(function(c, $c) {
					if (c.label === 'file') {
						c.send(file);
						$c.find('.messages').append('\
							<div><span class="file">You sent a file.</span></div>');
					}
				});
				
			});*/

			$(sync.element).find('.chatclose').click(function(){
				for (var i=0; i<sync.connections.length; i++){
					sync.connections[i].close();
				}
			});
			
			$(sync.element).find('.chatsend').submit(function(e) {
			
				e.preventDefault();				
				var msg = $(sync.element).find('.chattext').val();
				if (msg == '') return;
				
				for (var i=0; i<sync.connections.length; i++){
					sync.connections[i].send(msg);
				}
				
				var msgdiv = $(sync.element).find('.chatmessages');
				
				msgdiv.append(
					'<div><span class="you">You: </span>'+msg+'</div>');
					
				msgdiv[0].scrollTop = msgdiv[0].scrollHeight;
				
				$(sync.element).find('.chattext').val('');
				$(sync.element).find('.chattext').focus();
				
			});
			
			connection.on('data', function(data){
			
				var msgdiv = $(sync.element).find('.chatmessages');
				
				if (data == '!!!!!close!!!!!'){
					for (var i=0; i<sync.connections.length; i++){
						sync.connections[i].close();
					}
							console.log(sync);
					return;
				}
			
				msgdiv.append('<div><span class="peer">'
					+ connection.peer + '</span>: ' + data + '</div>');
					
				msgdiv[0].scrollTop = msgdiv[0].scrollHeight;
				
			});
			
			connection.on('close', function(data){
			
				removeFromArray(sync.connections, connection);
				
				if (sync.connections.length == 0){
					$(sync.element).fadeOut(400, function(){
						$(sync.element).remove();
						removeFromArray(syncs, sync);
					});
				}
				
			});
			
		} 
		
///**************************** FILE ******************************//
		if (connection.label === 'file'){
			 
			connection.on('open', function(){});
			
			connection.on('error', function(err){ alert(err); });
		
			connection.on('data', function(data){
				
				if (data.constructor === ArrayBuffer){
					var dataView = new Uint8Array(data);
					var dataBlob = new Blob([dataView]);
					var url = window.URL.createObjectURL(dataBlob);
					$('#' + c.peer).find('.messages').append('<div><span class="file">' +
						c.peer + ' has sent you a <a target="_blank" href="' +
						url + '">file</a>.</span></div>');
				}
				
			});
			
		}
		
	}
	
///******************* CLOSE PEER CONNECTION *********************//	
	window.onunload = window.onbeforeunload = function(e) {
		if (!!peer && !peer.destroyed) {
			peer.destroy();
		}
	};
	