/* ***********************************
 * add-HRM CHAT PLUGIN
 * DEVELOPED BY JITHIN LUKOSE
 * DATE : 27-08-2014 
 * Aadhocc Software Technologies
 ************************************/




var minReloadTime 	= 2000;
var maxReloadTime 	= 10000;
var username;
var chatBoxTitle;
var serviceURLCHAT 	=localStorage['serviceURL'];
var focussed ;
var OpenchatWindows	= [];
var fromUserImage;
var currentTitle 	= $(document).find("title").text();//current Page title...
var lastUser 		= localStorage['currentuser'];

$(function(){
setTimeout(chatCheck,500);
});


$.fn.outerHTMLFN = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("<p>").append(this.eq(0).clone()).html();
};


$(document).on('keyup','.chatBox',function(e){
    if(e.keyCode == 13){
        sendMessage($(this));
    }
});
$(document).on('click','.username',minimize);
$(document).on('click','#openChatWindow',startConversation);
$(document).on('click','.closeButton',closeChat);
$(document).on('click','.addButton',addnewuser);
$(document).on('click','.addUserToGroup',addUserToGroup);


if((localStorage['chatwindows'] != '' || localStorage.getItem('chatwindows') !== null) && lastUser==userid  ){
	var cahtWindow = localStorage['chatwindows'];
//	localStorage.removeItem('chatwindows');
	cahtWindow = (typeof cahtWindow === "undefined") ? "none" : cahtWindow;
	
	if(cahtWindow!="none"){
		
		var OpenWindows = JSON.parse(cahtWindow);
		OpenchatWindows = JSON.parse(cahtWindow);
		
		$.each(OpenWindows,function(index,OpenWindow){
			htmlFiltered = $(OpenWindow).filter('.chatwindow');		
			if($("#"+htmlFiltered.attr('id')).length){	
			}else{
			$('body').append(OpenWindow);
			}
			
		});
		
		
	}
}





$("html").click(function(){
		focussed = '';
});

$(document).on('click','.chatwindow',function(){
	 event.stopPropagation();
	 $(this).find('input').focus();
	focussed = $(this).attr('id');											
});


function createChatBox(chatBoxTitle,uid,data){
	data = (typeof data === "undefined") ? "" : data;
	
	if($('#chatBox-'+uid).length){
		
	}else{
	
	chatbox = '<div class="chatwindow" id="chatBox-'+uid+'">'+
			  '<div class="chatHeader" blink="0"><div class="username">'+chatBoxTitle+'</div>'+
				'<div class="closeButton">X</div>'+//<div class="addButton">+</div>
			  '</div>'+
			   '<div class="chatBody">'+
				'<div class="messageBody" style="width:100%">'+

				'</div>'+
				'<div class="messageBox">'+
				  '<input type="text" name="chatBox" class="chatBox" id="chatBox" data-id="'+uid+'" />'+
				'</div>'+
			  '</div>'+
			'</div>';
		
			
	$('body').append(chatbox);
	
	chatWindows =  'chatBox-'+uid;
	bindScroll(chatWindows);
		
		
		if(data!=''){
			bindMessages(data);
		//	setTimeout(function(){ blinkChat($('#'+chatWindows)); },300);
		}	
	
	}
	focussed ='chatBox-'+uid;
	arrangeChatBoxes();
	
	
	
}

function arrangeChatBoxes(){
	var chatBoxes = $('.chatwindow');
	var chatBoxWidth = 250;
	var chatBoxCount = 	chatBoxes.length;
	var totalWidth=chatBoxWidth+20;
		totalWidth = totalWidth;	
		chatBoxes.each(function(index){
			if(index > 0){
				$(this).css("right",parseInt(totalWidth)+"px");		
				totalWidth = parseInt(totalWidth)+chatBoxWidth+10 ;				
			}else{
				$(this).css("right",parseInt(0)+"px");	
			}
		});
}

function sendMessage($this){
	sendto = $this.attr('data-id');
	fromid = userid;
	message = $this.val();
	$this.val('');
	var dataString = {"message":message,"from":fromid, "toid":sendto};
	$.post(serviceURLCHAT +"chat.php?action=sendReply",dataString,function(data){
		if(data.messages!==null){															   
		 	bindMessages(data.messages);	
		}
	},"json");
	
}

function startConversation(){
	$this = $(this);
	var chatBuddy = $this.attr('data-id');
	var dataString = {"fromid":userid,"toid":chatBuddy};
	var chatBoxTitle = $this.text();
	
	createChatBox(chatBoxTitle,chatBuddy);
	
	$.post(serviceURLCHAT + "chat.php?action=getMessages",dataString,function(data){
		messages = data.messages;		
		if(data.messages!==null){	
			bindMessages(messages);	
		}
	},"json");
}

function chatCheck(){
	localStorage['currentuser'] = userid;
	var dataString = {'fromid':userid}
	$.post(serviceURLCHAT + "chat.php?action=getNewMsg",dataString,function(data){
		var messageList = data.messages;
		

		var onlineUsers = messageList[parseInt(messageList.length)-1].useronline;
		changeOnlineStatus(onlineUsers);
		
		if(data.messages !== null ){
			var messageOne = data.messages[0].time;
			if(messageOne){
				bindMessages(data.messages);
			}
		}
		
		
		if(minReloadTime < maxReloadTime){    // IF CONVERSATION RELOAD TIME IS lessthan max time, add 100ms to min time.( For decreas server load at ideal time).
			minReloadTime = minReloadTime+200;
		}
		setTimeout(function(){ chatCheck() } ,minReloadTime);
	},"json");
}

var changeOnlineStatus = function(list){
	//icon-available.png
	$('.openChatWindow').each(function(){
		$this =$(this);
		$empid= $this.attr('data-id');
		$this.attr('data-status',2);
		$this.find('.chat-color-status img').attr('src','images/icon-notavailable.png');
		
		$.each(list, function (i, elem) {
			if (elem.user_id == $empid ) {
				$this.attr('data-status',1);
				$this.find('.chat-color-status img').attr('src','images/icon-available.png');
				
				if($this.prev('.openChatWindow').attr('data-status') == 2){
					$this.prependTo('.employeeList');	
				}
			}
		});
		
	});
	
/*	$(".employeeList li").sort(sort_li).appendTo('.employeeList');
	function sort_li(a, b){
		if( $(b).data('status') !==  $(a).data('status')){
			return ($(b).data('status')) < ($(a).data('status')) ? 1 : -1;  
		}
	}*/
	
}




function bindMessages(message,place){
	place = (typeof place === "undefined") ? "1" : place;
	var chatuser;
	minReloadTime = 500;  // reset timer if conversation is continue......
	message = message.sort(function(a,b) { return parseFloat(a.price) - parseFloat(b.price) } );
	var lastDate='';
	$.each(message,function(index,data){
		if(data.user_one != userid ){
			chatWindow = $('#chatBox-'+data.user_one);
			chatuser = data.user_one;
			
		}else{
			chatWindow = $('#chatBox-'+data.user_two);
			chatuser = data.user_two;
			//userimage = userimage;
		}	

		var username;
		//console.log(userid);
		if(data.user_id_fk == userid){
			fromUserImage = userimage;
			username = "Me";
			
		}else{
			fromUserImage = data.photo;
			username = data.e_fname;
		}
		
				
		if(fromUserImage == '' || fromUserImage === null || fromUserImage=="undefined"){
			fromUserImage = "noimg.jpg";
		}
		fromUserImage = (typeof fromUserImage === "undefined") ? "noimg.jpg" : fromUserImage;
	
	var chatDate = moment.unix(data.msgtime).format("DD MMMM YYYY");
	var today	 = moment().format("DD MMMM YYYY");		
	
	if(today == chatDate){
		displayDate = 	"Today";
	}else{
		displayDate = 	chatDate;
	}
		
		if(chatWindow.length > 0){
			
			
			
		if(place == 1){

				chatWindow.find('.messageBody').append('<div class="conversationLeft" chat-unix="'+data.msgtime+'" chat-date="'+moment.unix(data.msgtime).format("DDMMYYYY")+
				'" style="width:100%" data-id="'+data.cr_id+'" data-conversation="'+data.c_id+'">'+
				'<div style="width:30px; height:30px; padding:2px; float:left"><img src="upload/image/'+fromUserImage+'" width="30" height="30" /></div>'+
				'<div class="message"><b>'+username+'</b></div>'+
				'<div class="message">'+data.reply+'<span class="pull-right" sryle="font-size:10px; color:#ccc;" style="font-size: 10px;">'+
				moment.unix(data.msgtime).format("h:mm a")+'</span></div>'+
				'</div>');
				chatWindow.find('.messageBody').scrollTop(chatWindow.find('.messageBody')[0].scrollHeight);
				
			}else{
				
				
				chatWindow.find('.messageBody').prepend('<div class="conversationLeft"  chat-unix="'+data.msgtime+'" chat-date="'+moment.unix(data.msgtime).format("DDMMYYYY")+
				'" style="width:100%" data-id="'+data.cr_id+'" data-conversation="'+data.c_id+'">'+
				'<div style="width:30px; height:30px; padding:2px; float:left"><img src="upload/image/'+fromUserImage+'" width="30" height="30" /></div>'+
				'<div class="message"><b>'+username+'</b></div>'+
				'<div class="message">'+data.reply+'<span class="pull-right" sryle="font-size:10px; color:#ccc;" style="font-size: 10px;">'+
				moment.unix(data.msgtime).format("h:mm a")+'</span></div>'+
				'</div>');
	
			}


			for(i=0;i<OpenchatWindows.length; i++){									  
				htmlFiltered = $(OpenchatWindows[i]).filter('.chatwindow');
 				if(htmlFiltered.attr('id') == 'chatBox-'+chatuser){
						OpenchatWindows.splice(i, 1);
						i -=1;
				}
			}

			setTimeout(function(){
				var CurrentChatBOXhtml = $('#chatBox-'+chatuser).html();
				
				CurrentChatBOX = '<div class="chatwindow" id="chatBox-'+chatuser+'">'+CurrentChatBOXhtml+'</div>';
				
				
				OpenchatWindows.push(CurrentChatBOX);
				setTimeout(function(){ localStorage['chatwindows'] =  JSON.stringify(OpenchatWindows)},50);
				console.log(OpenchatWindows);
			},100);
		
			
		
		
		lastDate = chatDate;
		
		}else{
			createChatBox(data.e_fname,chatuser,message);
		}
	});
	
			dateChange='';
			$('.conversationHistoryTime').remove();
			$('.conversationLeft').each(function(){
					$this = $(this);
					
					if( $this.attr('chat-date') !=dateChange ){
					
					if(moment.unix($this.attr('chat-unix')).format("DD MMMM YYYY") == moment().format("DD MMMM YYYY")){
						var dateDisplay = "Today";	
					}else{
						var dateDisplay = moment.unix($this.attr('chat-unix')).format("DD MMMM YYYY");
					}
					
					$this.before('<div class="conversationHistoryTime">'+
									 '<img src="images/history.png" width="15"/> '+dateDisplay+'<div>');	
					}
					dateChange = $this.attr('chat-date');
				});

}




function minimize(){
	$this = $(this);
	$this.parent().parent().find('.chatBody').toggle();

}

function blinkChat(chatWindow){
	title = chatWindow.find('.username').html();	
		blinking(chatWindow,title);
}


var id;
function blinking(chatWindow,title){
	var exit=0;
	if(focussed !== chatWindow.attr('id')){
		
		if(chatWindow.find('.chatHeader').attr('blink') == 0){
			chatWindow.find('.chatHeader').css('background','#CCC').attr('blink','1');
			$(document).find("title").text(title+"  says...");
		}else{
			chatWindow.find('.chatHeader').css('background','#333333').attr('blink','0');
			$(document).find("title").text(currentTitle);
		}
		
	}else{
		
		 exit=1;
	}
	id = setTimeout(function(){ blinking(chatWindow) },1000);
	if(exit == 1){
		chatWindow.find('.chatHeader').css('background','#333333').attr('blink','0');
		$(document).find("title").text(currentTitle);
		clearTimeout(id);
		exit =0;
	}
	
}

function closeChat(){
	$this=$(this);
	var chatWindowID = $this.parents('.chatwindow').attr("id");
	
	$this.parents('.chatwindow').remove();
	
		for(i=0;i<OpenchatWindows.length; i++){									
				htmlFiltered = $(OpenchatWindows[i]).filter('.chatwindow');
 				if(htmlFiltered.attr('id') == chatWindowID){
					OpenchatWindows.splice(i, 1);	
					i -=1;
				}
		}

			setTimeout(function(){
			localStorage['chatwindows'] =  JSON.stringify(OpenchatWindows);
			},100);	
	
	arrangeChatBoxes();
}

function addnewuser(){
	$(this).parent().append('<div class="newChatUser" width="100%"><input type="text" ><input type="button" class="addUserToGroup" value="+"></div>');
}

function addUserToGroup(){
	$(this).parent().hide();	
}


function bindScroll(id){
	$('#'+id).find('.messageBody').on('scroll', function(){
			
			lastMessage = $(this).find('.conversationLeft:first').attr('data-id');
			conversationid =  $(this).find('.conversationLeft:first').attr('data-conversation');
			fromtop = $(this).scrollTop();
		console.log(conversationid);
			if(fromtop == 0){
				dataString = {'cid':conversationid,'lastid':lastMessage,'fromid':userid};
				$.post(serviceURLCHAT + "chat.php?action=getMessages",dataString,function(data){
					if(data.messages!==null){
						bindMessages(data.messages,"0");
					}														   
				},"json");
			}
				// console.log(fromtop);
	});
	
}



jQuery.fn.listMember = function(){
	var $this = $(this);
	$this.append('<ul class="employeeSearch">'+
				 '<li class="empSearchBox"><input type="text" name="searchEmployee" class="searchEmployee" style="width:100%" placeHolder="Search"/>'+
				 '</li>'+
				 '</ul>'+
				 '<div class="employeesListWrapper">'+
				 '<ul class="employeeList">'+
				 '</ul></div>');
	
	$.post(serviceURLCHAT + "chat.php?action=listEmp", function(data){
		employees = data.employees;
		
		$.each(employees,function(index,employees){
			
			if(employees.photo == ""){
				empimage = "noimage.jpg";
			}else{
				empimage = employees.photo	
			}
	
			if(employees.e_id != userid){			
			
						$('.employeeList').append('<li id="openChatWindow" class="openChatWindow" data-id="'+employees.e_id+'">'+
									  '<div class="chat-foto"><img src="upload/image/'+empimage+'" /></div><div class="chat-text-name">'+
									  employees.e_fname+" "+employees.e_lname +'<br/>'+
									  '</div>'+//<div class="chat-text-small">Designation </div> //before close this div
									  '<div class="chat-color-status"><img src="images/icon-notavailable.png" /></div></li>');	
			}
		});
		
	},"json");
	
}


$(document).on('keyup','.searchEmployee',function(){
    searchWord = $(this).val();
		$.post(serviceURLCHAT + "chat.php?action=listEmp&search="+searchWord, function(data){
		employees = data.employees;
		$('.employeeList').html('');
		$.each(employees,function(index,employees){
			
			if(employees.photo == ""){
				empimage = "noimage.jpg";
			}else{
				empimage = employees.photo	
			}
			
			if(employees.e_id != userid){
								  
						$('.employeeList').append('<li id="openChatWindow" class="openChatWindow" data-id="'+employees.e_id+'">'+
									  '<div class="chat-foto"><img src="upload/image/'+empimage+'" /></div><div class="chat-text-name"><span>'+
									  employees.e_fname+" "+employees.e_lname +'</span><br/>'+
									  '<div class="chat-text-small">Test </div></div>'+
									  '<div class="chat-color-status"><img src="images/icon-notavailable.png" /></div></li>');	
			}
		});
		
	},"json");

});



$('.sidebar').listMember(); 


