userchat_domain = '';
userchat_smile_box_list = '';
userchat_smile_box_set = '';
userchat_smiley_packs = new Array('blueticon','simple');
userchat_smiley_default_pack = 'simple';
userchat_smiley_packs_data = new Array();
userchat_box_width = 220+10;
userchat_bbl_width = 26;
userchat_enable_debug = false;
userchat_debug_max_lines = 200;
userchat_cache_expire = 1000*60*60;
userchat_cache_write_interval = 1000*5;
userchat_enable_cache = false;
userchat_initial_status = 'online';
userchat_update_timer = 10; /* in seconds */
userchat_smiley_packs_json = {};
userchat_supported_images = ["jpg","jpeg","png","bmp"];
userchat_list_mode = 'all';
userchat_cid = 'unique_site_id';
userchat_old_cache = '';
userchat_old_update = '';

var smiley_loaded_after_callback = function(){
userchat_debug('Smiley pack loaded.', 'magenta');
}

function userchat_avatar_updated(time){
jQuery('.phpl-alert-ctr').fadeOut("slow", function(){
var new_img = userchat_domain+'userpics/'+userchat_current_user+'.jpg?x='+time;
jQuery('.userchat-cmt-right .userchat-cmt-pic, .userchat-profile-pic').attr('src', new_img);
userchat_debug('new profile photo : '+new_img, 'magenta');
jQuery('.phpl-alert-ctr').remove();
userchat_cache_save('data', '.userchat-ctr');
});
}

function userchat_file_uploaded(xdata, to_id){
var content = '['+xdata+']';
userchat_queue_message(content, to_id);
jQuery('.phpl-alert-ctr').fadeOut("slow", function(){
jQuery(this).remove();
});
}

//================================= alert box =================================

function userchat_alert(data, title, footer,xid){
if(title===undefined){title='Message from server';}
if(footer===undefined || footer==''){footer='<div class="phpl-alert-btn-danger phpl-alert-close">Close</div>';}
if(xid===undefined){
var xtot = jQuery('.phpl-alert-ctr').length+1;
} else {
var xtot = xid;
}
xhtml = '<div id="phpl-alert-'+xtot+'" style="display:none;" class="phpl-alert-ctr">\
<div class="phpl-alert-bg"></div>\
<div class="phpl-alert-box-outer">\
<div class="phpl-alert-box-inner">\
<div class="phpl-alert-box">\
<div class="phpl-alert-box-top">\
<div class="phpl-alert-box-top-text">'+title+'</div>\
<div class="phpl-alert-box-top-close" title="Close">X</div>\
<div style="clear:both;"></div>\
</div>\
<div class="phpl-alert-box-middle">'+data+'</div>\
<div class="phpl-alert-box-bottom">'+footer+'\
<div style="clear:both;"></div>\
</div></div></div></div></div>';
jQuery('body').append(xhtml);
jQuery('#phpl-alert-'+xtot).fadeIn("slow");
}

function userchat_confirm(data, on_click, xid){
if(on_click===undefined){on_click='';} else {on_click=' onclick="'+on_click+'" ';}
footer = '<div class="phpl-alert-btn-danger phpl-alert-close">Cancel</div> <div class="phpl-alert-btn-success phpl-alert-close" '+on_click+'>Continue</div>';
userchat_alert(data,'Please confirm to continue', footer, xid);
}

function userchat_close_alert(xid){
if(xid===undefined || xid===''){var xid='phpl-alert-1';}
jQuery('#'+xid).fadeOut("slow", function(){
jQuery('#'+xid).remove();
});
}
//================================= alert box end =================================

function userchat_date(timestamp) {
  var d = new Date(timestamp * 1000),	// Convert the passed timestamp to milliseconds
		yyyy = d.getFullYear(),
		mm = ('0' + (d.getMonth() + 1)).slice(-2),	// Months are zero based. Add leading 0.
		dd = ('0' + d.getDate()).slice(-2),			// Add leading 0.
		hh = d.getHours(),
		h = hh,
		min = ('0' + d.getMinutes()).slice(-2),		// Add leading 0.
		ampm = 'AM',
		time;
			
	if (hh > 12) {
		h = hh - 12;
		ampm = 'PM';
	} else if (hh === 12) {
		h = 12;
		ampm = 'PM';
	} else if (hh == 0) {
		h = 12;
	}
	
	// ie: 2013-02-18, 8:35 AM	
	time = yyyy + '-' + mm + '-' + dd + ', ' + h + ':' + min + ' ' + ampm;
		
	return time;
}

function userchat_load_smiley_sets(){
for(var i=0;i<userchat_smiley_packs.length;i++){
	

var url = userchat_domain+"smile/"+userchat_smiley_packs[i]+"/userchat-pack.js";
userchat_debug('Loading smiley pack : '+userchat_smiley_packs[i], 'purple');
userchat_load_smiley_script(url, smiley_loaded_after_callback);
}
return true;
}


function userchat_add_smiley_theme(name){

var json = jQuery.parseJSON(userchat_smiley_packs_data[name]);
if(name==userchat_smiley_default_pack){
var liclass=userchat_smiley_default_pack+" userchat-pack-active-li";
var xcss = ' style="display:block;"';
} else {
var liclass=name;
var xcss = '';
}

var xdata = '<ul'+xcss+' class="userchat-icon-pack-'+name+'-data">';
var xarr = {};
xarr['height']=json.height;
xarr['xtype']=json.xtype;
for(var i=0;i<json.data.length;i++){
var iconid = json.data[i][0];
var icon = json.data[i][1];
xarr[iconid] = icon;
userchat_smiley_packs_json[name] = xarr;
xdata = xdata +'<li class="userchat-'+name+'-'+json.data[i][0]+'"><img title="['+name+':'+json.data[i][0]+']" style="height:'+json.height+'px;" src="'+userchat_domain+'smile/'+name+'/'+json.data[i][1]+'" /></li>';
}
xdata = xdata+'<p class="userchat-clear"></p></ul>';

userchat_smile_box_list = userchat_smile_box_list + '<li class="userchat-icon-pack-'+liclass+'" title="'+name+' icon pack" style="background-image:url(\''+userchat_domain+'smile/'+name+'/'+json.icon+'\')"></li>';
userchat_smile_box_set = userchat_smile_box_set + xdata;
}



function userchat_load_smiley_script(url, callback){
    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

function userchat_show_box(xuid){
var uidtxt = jQuery('.userchat-box-show:last').attr('id');
var uid = uidtxt.replace('userchat-box-','');
var uname = jQuery('#userchat-box-'+uid+' .userchat-box-uname').html();
var upos = jQuery('#'+uidtxt).css('right');
jQuery('#'+uidtxt).removeClass('userchat-box-show').addClass('userchat-box-hidden');
jQuery('.userchat-bbl-list').prepend('<li class="userchat-bbl-user" uid="'+uid+'"><h5>'+uname+'</h5><p class="userchat-bbl-close">X</p><p class="userchat-new-msg" count="0">0</p><p class="userchat-clear"></p></li>');

jQuery('#userchat-box-'+xuid).removeClass('userchat-box-hidden').addClass('userchat-box-show');
jQuery('#userchat-box-'+xuid).css('right', upos);
jQuery('.userchat-bbl-user[uid="'+xuid+'"]').remove();
jQuery('#userchat-box-'+xuid+' textarea').trigger('focus');
userchat_cache_save('data', '.userchat-ctr');
}

function userchat_box_reposition(){
jQuery('.userchat-bbl-list').html('');
var difference = 260-userchat_box_width;
var newright = difference;
var capacity = parseInt((jQuery(window).width()-260-difference-userchat_bbl_width)/userchat_box_width);
var tot_cycles = 0;
jQuery( ".userchat-box" ).removeClass('userchat-box-hide').removeClass('userchat-box-show');
jQuery( ".userchat-box" ).each(function(i){
tot_cycles = i;
newright = newright+userchat_box_width;
var xuid = jQuery(this).attr('id');
var uid = xuid.replace('userchat-box-','');
var user_name = jQuery(this).find('.userchat-box-uname').html();
var user_pic = jQuery('li.userchat-user[uid="'+uid+'"] .userchat-user-pic').attr('src');

if(i<capacity){
jQuery(this).addClass('userchat-box-show');
} else {
jQuery(this).addClass('userchat-box-hide');
jQuery('.userchat-bbl-list').prepend('<li uid="'+uid+'" class="userchat-bbl-user"><h5>'+user_name+'</h5><p class="userchat-bbl-close">X</p><p count="0" class="userchat-new-msg">0</p><p class="userchat-clear"></p></li>');
}

jQuery(this).css( "right", newright+"px" );
});

//alert(tot_cycles+1);
if((tot_cycles+1)>capacity){
jQuery('.userchat-bubble').css('right', (((capacity+1)*userchat_box_width)+difference)+'px');
jQuery('.userchat-bubble').show();
} else {
jQuery('.userchat-bubble').hide();
}
var xtot = jQuery('.userchat-box-hide').length;
jQuery('.userchat-bubble b').html(xtot);
userchat_cache_save('data', '.userchat-ctr');
}


function userchat_create_box(uid){
var lmode = jQuery('.userchat-bubble').attr('lmode');
var user_name = jQuery('li.userchat-user[uid="'+uid+'"] .userchat-user-name').text();
var user_pic = jQuery('li.userchat-user[uid="'+uid+'"] .userchat-user-pic').attr('src');
jQuery('title').text('chat with '+user_name);
if(lmode=='contacts'){var chtml = '<li class="userchat-remove-contact">Remove from contacts</li>';} else {var chtml = '';}

if(jQuery('#userchat-box-'+uid).length!=0){
jQuery('#userchat-box-'+uid+' textarea').trigger('focus');
} else {

var xhtml = '<div id="userchat-box-'+uid+'" class="userchat-box userchat-box-show">\
<div class="userchat-box-inner">\
\
<div class="userchat-box-top">\
<ul class="userchat-box-menu">\
<li class="userchat-box-icon userchat-box-uname" title="click on name to minimize or maximize">'+user_name+'</li>\
<li title="Close Conversation" class="userchat-box-icon userchat-box-close"></li>\
<li class="userchat-box-icon userchat-box-settings">\
	<ul class="userchat-submenu">\
	'+chtml+'\
	<li class="userchat-clear-data">Clear chat history</li>\
	</ul>\
</li>\
</ul>\
<p class="userchat-clear"></p>\
</div>\
\
<div class="userchat-box-comments"></div>\
\
<div class="userchat-box-write">\
<div class="userchat-box-attach" onclick="userchat_upload_alert(\'file&uid='+uid+'\')"></div>\
\
<div class="userchat-box-smiley"></div>\
\
<div class="userchat-box-smiley-ctr" style="display:none;">\
<div class="userchat-pack-select">'+userchat_smile_box_list+'</div>\
<div class="userchat-box-smiley-icons">'+userchat_smile_box_set+'</div>\
<b class="userchat-caret-bottom"></b>\
</div>\
\
<textarea placeholder="Type and press Enter to send" name="ghghgh"></textarea>\
</div>\
\
</div>\
</div>';

jQuery('.userchat-inner-ctr').prepend(xhtml);
jQuery('#userchat-box-'+uid).fadeIn("fast");
jQuery('#userchat-box-'+uid+' textarea').trigger('focus');
jQuery('#userchat-box-'+uid+' .userchat-box-smiley-icons').perfectScrollbar();
jQuery('#userchat-box-'+uid+' .userchat-box-comments').perfectScrollbar();
userchat_old_msgs(uid);

}
setTimeout("userchat_box_reposition()", 10);
}



function userchat_acceptf(uid){
jQuery('.userchat-faccept[data-uid="'+uid+'"]').closest('.userchat-list-user').remove();
jQuery.post(userchat_domain+"userchat-functions.php", {curr_user:userchat_current_user, method:'acceptf', user:uid}, function(data) {
userchat_generate_chat_list();
var xc = parseInt(jQuery('.userchat-bubble').attr('xf'));
jQuery('.userchat-bubble').attr('xf', (xc-1));
jQuery('#userchat-freq').html(xc-1);
userchat_cache_save('data', '.userchat-ctr');
});
}

function userchat_contact_removed(uid){
userchat_rejectf(uid);
jQuery('#userchat-box-'+uid).remove();
jQuery('.userchat-user[uid="'+uid+'"]').remove();
}

function userchat_rejectf(uid){
jQuery('.userchat-faccept[data-uid="'+uid+'"]').closest('.userchat-list-user').remove();
jQuery.post(userchat_domain+"userchat-functions.php", {curr_user:userchat_current_user, method:'rejectf', user:uid}, function(data) {
var xc = parseInt(jQuery('.userchat-bubble').attr('xf'));
jQuery('.userchat-bubble').attr('xf', (xc-1));
jQuery('#userchat-freq').html(xc-1);
if(jQuery('.phpl-alert-box-middle .userchat-list-user').length==0){
jQuery('.phpl-alert-ctr').fadeOut("slow", function(){
jQuery('.phpl-alert-ctr').remove();
});
}
userchat_cache_save('data', '.userchat-ctr');
});
}

function userchat_deletef(uid){
jQuery.post(userchat_domain+"userchat-functions.php", {curr_user:userchat_current_user, method:'rejectf', user:uid}, function(data) {
userchat_alert('The contact was deleted successfully.');
userchat_cache_save('data', '.userchat-ctr');
});
}



function userchat_old_msgs(uid){
if(jQuery('#userchat-box-'+uid+' .userchat-box-comments [sent]').length==0){
var ltime = jQuery('.userchat-bubble').attr('ltime');
userchat_debug('current time used', '#000');
} else {
var ltime = jQuery('#userchat-box-'+uid+' .userchat-box-comments [sent]:first').attr('sent');
userchat_debug('last message time used', '#000');
}
var myid = jQuery('.userchat-bubble').attr('xid');
var mypic = jQuery('.userchat-bubble').attr('xpic');
//setTimeout("userchat_old_msgs("+uid+")", 5000);
jQuery('#userchat-box-'+uid+' .userchat-box-comments .userchat-cmt-date').remove();
jQuery.post(userchat_domain+"userchat-functions.php", {curr_user:userchat_current_user, list_mode:userchat_list_mode, method:'old_msgs', xtime:ltime, user:uid}, function(data) {
json = jQuery.parseJSON(data);
for(var i=0;i<json.totalm;++i){
if(json.msgs[i].xfrom==myid){
var uname = 'You';
var upic = mypic;
var xclass = 'userchat-cmt-right';
} else {
var xclass = 'userchat-cmt-left';
var uname = jQuery('.userchat-users li[uid="'+json.msgs[i].xfrom+'"] .userchat-user-name').text();
var upic = jQuery('.userchat-users li[uid="'+json.msgs[i].xfrom+'"] .userchat-user-pic').attr('src');
}
jQuery('#userchat-box-'+uid+' .userchat-box-comments').prepend('<div class="'+xclass+'" sent="'+json.msgs[i].sent+'"><img src="'+upic+'" title="'+uname+' on '+userchat_date(json.msgs[i].sent)+'" class="userchat-cmt-pic"><div class="userchat-cmt-pin"></div><div class="userchat-cmt">'+userchat_parse_text(json.msgs[i].msg)+'</div><p class="userchat-clear"></p></div>');
jQuery('#userchat-box-'+uid+' .userchat-box-comments').scrollTop(jQuery('#userchat-box-'+json.msgs[i].xfrom+' .userchat-box-comments').prop( "scrollHeight" ));
jQuery('#userchat-box-'+uid+' .userchat-box-comments').perfectScrollbar('update');
}

if(json.totalm<10){
jQuery('#userchat-box-'+uid+' .userchat-box-comments').prepend('<div class="userchat-cmt-date"><i>- No more old messages to display -</i></div>');
} else {
jQuery('#userchat-box-'+uid+' .userchat-box-comments').prepend('<div class="userchat-cmt-date"><a href="#">click to show older messages</a></div>');
}
userchat_cache_save('data', '.userchat-ctr');
});
}

function userchat_debug(data, color){
if(jQuery('.userchat-debug').length==0){jQuery('body').append('<div class="userchat-debug"><p>Debugger initialised.</p></div>');}
if(userchat_enable_debug){
jQuery('.userchat-debug').show();
if(jQuery('.userchat-debug p').length>userchat_debug_max_lines){jQuery('.userchat-debug').html('');}
jQuery('.userchat-debug').prepend('<p style="color:'+color+'">'+data+'</p>');
} else {
jQuery('.userchat-debug').hide();
}
}

function userchat_color_status(utime,now,device){
if(device===undefined){device='Online';}
var diff = parseInt((parseInt(now)-parseInt(utime))/60);

if(diff>1 && diff<=15){var data = '<p class="userchat-status userchat-away">'+diff+' min<span></span></p>';}
if(diff<=1){var data = '<p class="userchat-status userchat-online">'+device+'<span></span></p>';}
if(diff>15){var data = '<p class="userchat-status userchat-offline">'+device+'<span></span></p>';}
return data;
}

function userchat_generate_chat_list(){
var xdata = '';
jQuery.post(userchat_domain+"userchat-functions.php", {curr_user:userchat_current_user, list_mode:userchat_list_mode, method:'user_list'}, function(data) {

var json = jQuery.parseJSON(data);
for(var i=0;i<json.total;++i){
xdata = xdata + '<li uid="'+json.data[i].uid+'" class="userchat-user"><img class="userchat-user-pic" src="'+userchat_domain+'userpics/'+json.data[i].pic+'.jpg" /><h5 class="userchat-user-name">'+json.data[i].name+'</h5>'+userchat_color_status(json.data[i].userchat, json.time, json.data[i].device)+'<p class="userchat-clear"></p></li>';
}
userchat_debug(''+data, '#008080');
jQuery('.userchat-users').html(xdata);
jQuery('.userchat-list').perfectScrollbar('update');
if(jQuery('.phpl-alert-box-middle .userchat-list-user').length==0){
jQuery('.phpl-alert-ctr').fadeOut("slow", function(){
jQuery('.phpl-alert-ctr').remove();
});
}
});
}


function userchat_generate_ui(){
userchat_debug('running - userchat_generate_ui.', 'red');
if(jQuery('.userchat-ctr').length==0){
var xdata = '';

jQuery.post(userchat_domain+"userchat-functions.php", {curr_user:userchat_current_user, list_mode:userchat_list_mode, method:'user_list'}, function(data) {

var json = jQuery.parseJSON(data);
for(var i=0;i<json.total;++i){
xdata = xdata + '<li uid="'+json.data[i].uid+'" class="userchat-user"><img class="userchat-user-pic" src="'+userchat_domain+'userpics/'+json.data[i].pic+'.jpg" /><h5 class="userchat-user-name">'+json.data[i].name+'</h5>'+userchat_color_status(json.data[i].userchat, json.time, json.data[i].device)+'<p class="userchat-clear"></p></li>';
}
userchat_debug(''+data, '#008080');
var xhtml = '<div class="userchat-ctr">\
<div class="userchat-inner-ctr">\
<div id="userchat-freq-data"></div>\
<div list_mode="'+userchat_list_mode+'" ltime="'+json.time+'" updated="'+userchat_update_timer+'" lmode="'+json.listmode+'" xid="'+json.uid+'" xpic="'+userchat_domain+'userpics/'+json.pic+'.jpg" xf="0" class="userchat-bubble"><b>0</b>\
<ul class="userchat-bbl-list">\
</ul>\
</div>\
\
<div class="userchat-list-ctr">\
\
<div class="userchat-list">\
<ul class="userchat-users">'+xdata+'</ul>\
</div>\
\
<div class="userchat-list-header"><h5>Chat</h5></div>\
\
<div class="userchat-find">\
<img src="'+userchat_domain+'images/userchat-find.png" class="userchat-find-icon">\
<input type="text" name="userchat-key" id="userchat-key" placeholder="Search users" />\
</div>\
\
<div class="userchat-options-ctr">\
<div class="userchat-options-caret-bottom"></div>\
<div class="userchat-options"><div class="userchat-h3">Profile Picture</div> \
<p>To change your profile picture, please select upload photo from below button.</p>\
<img src="'+userchat_domain+'userpics/'+json.pic+'.jpg" class="userchat-profile-pic">\
<div class="userchat-button" onclick="userchat_upload_alert(\'userpic\')">Upload Photo</div>\
<div class="userchat-hr"></div>\
<div class="userchat-h3">Contact request</div>\
<p>You have <b id="userchat-freq">0</b> contact requests. To manage them, <div class="userchat-button" onclick="userchat_show_requests()">View Requests</div></p>\
<p class="userchat-clear"></p>\
<div class="userchat-hr"></div>\
<div class="userchat-h3">Switch theme</div>\
<p>Themes are applied to your account for this session only. Theme settings are stored in cookies, so changes will be lost if cookies are cleared.</p>\
<ul class="userchat-theme-chooser">\
<li light="#1d8cde" dark="#135f97" style="background-color:#135f97;" title="default theme(blue)"></li>\
<li light="#ff3c3c" dark="#d50000" style="background-color:#d50000;"  title="red theme"></li>\
<li light="#0f9500" dark="#0a5b00" style="background-color:#0a5b00;"  title="green theme"></li>\
<li light="#b7b700" dark="#757500" style="background-color:#757500;"  title="yellow theme"></li>\
<li light="#777" dark="#555" style="background-color:#555;"  title="gray theme"></li>\
<li light="#555" dark="#000" style="background-color:#000;"  title="black theme"></li>\
<li light="#fe650a" dark="#cd4e01" style="background-color:#cd4e01;"  title="orange theme"></li>\
<li light="#00b99d" dark="#008470" style="background-color:#008470;"  title="pink theme"></li>\
<li light="#ff40ec" dark="#d900c4" style="background-color:#d900c4;"  title="magenta theme"></li>\
<li light="#9135ff" dark="#5800c4" style="background-color:#5800c4;"  title="purple theme"></li>\
</ul>\
<p class="userchat-clear"></p>\
<div class="userchat-hr"></div>\
<div class="userchat-h3">Disable/offline chat</div>\
<p>You are currently online. To disable chat or go offline, please click button below.</p>\
<div class="userchat-button userchat-go-offline">Go Offline</div>\
</div>\
</div>\
<div class="userchat-options-icon"></div>\
\
</div>\
</div>\
<div status="'+userchat_initial_status+'" class="userchat-offline-icon" title="Click to go online and begin chatting"></div>\
</div>';
jQuery('body').append(xhtml);

userchat_debug('Cache not found or expired. Loaded fresh data.', 'red');
userchat_debug('Fresh List Created.', '#008080');

if(userchat_current_user=='0'){
jQuery.jStorage.set(userchat_cid+"_status", "offline");
jQuery.jStorage.setTTL(userchat_cid+"_status", userchat_cache_expire);
} else {
jQuery.jStorage.set(userchat_cid+"_status", "online");
jQuery.jStorage.setTTL(userchat_cid+"_status", userchat_cache_expire);
}

userchat_check_offline();

if(userchat_load_smiley_sets()){
jQuery('.userchat-list').perfectScrollbar();
//setTimeout("userchat_write_cache()", userchat_cache_write_interval);
userchat_updater();
}

userchat_old_cache = jQuery('.userchat-ctr')[0].outerHTML;
userchat_cache_save('data', '.userchat-ctr');
userchat_cache_restore_service();
});
}

}



function userchat_contact_request(uid){
userchat_close_alert(uid);
if(userchat_current_user=='0'){
userchat_confirm('<b>You must be logged in to use online chat features.</b><br /><br />Redirect to login page?', 'userchat_login_redirect()');
} else {
jQuery.post( userchat_domain+"userchat-functions.php",{curr_user:userchat_current_user, method:'add_contact', user_id:uid}, function( data ) {
var res = jQuery.parseJSON(data);
if(res.rcode==1){
jQuery('[data-uid="'+uid+'"]').closest('.userchat-list-user').remove();
userchat_alert('There is no need for you to chat with yourself.','Oops...');
}

if(res.rcode==2){
jQuery('[data-uid="'+uid+'"]').closest('.userchat-list-user').remove();
userchat_alert('Contact request sent successfully. you may close this notification.','Success...');
}

if(res.rcode==3){
userchat_alert('You have already sent a chat request to this person, please wait for the response.','Hmmm...');
}

if(res.rcode==4){
userchat_alert('You already had received a chat request from this person, please accept it or reject it.','Hmmm...', '<div class="phpl-alert-btn-danger phpl-alert-close">Cancel</div> &nbsp; <div onclick="userchat_rejectf(\''+uid+'\')" class="phpl-alert-btn-warning userchat-rejectf">Reject Request</div> &nbsp; <div class="phpl-alert-btn-success userchat-acceptf">Accept Request</div>');
}

if(res.rcode==5){
userchat_alert('Some db error occured!!','What the hell....');
}

});
}
}



function userchat_parse_text(ntext){
	
ntext = jQuery('<div />').text(ntext).html();
words = [];
ntext.replace(/\[(.+?)\]/g, function(jQuery0, jQuery1) { words.push(jQuery1) });

for(var i=0;i<words.length;i++){
var fw = words[i].split(':');
var fword = fw[0];

if(fword=='file'){
var fsize = fw[1];
fname = fw[2];
var ext = fname.split('.').pop();
if(jQuery.inArray(ext, userchat_supported_images) !== -1){
var xhtml = '<div class="userchat-pic">\
<a title="'+fname+'" class="userchat-file-lightbox" href="'+userchat_domain+'uploads/'+fname+'">\
<img src="'+userchat_domain+'uploads/'+fname+'" /></a><br />\
<a download class="userchat-file-link" target="_blank" href="'+userchat_domain+'uploads/'+fname+'">Download</a> ('+userchat_bytes(fsize,2)+', '+ext+' file)\
<div class="userchat-clear"></div>\
</div>';
} else {
var xhtml = '<div class="userchat-file">\
<img src="'+userchat_domain+'filetypes/'+ext+'.png" class="userchat-file-img">\
<div class="userchat-file-name">'+fname+'</div>\
<a download class="userchat-file-link" target="_blank" href="'+userchat_domain+'uploads/'+fname+'">download</a> ('+userchat_bytes(fsize,2)+')\
<div class="userchat-clear"></div>\
</div>';
}
ntext = ntext.replace('['+words[i]+']', xhtml);
}

else if(jQuery.inArray(fword, userchat_smiley_packs) !== -1){
var pack = fword;
var icon_title = fw[1];
var pic = userchat_smiley_packs_json[pack][icon_title];
var xtype = userchat_smiley_packs_json[pack].xtype;
if(xtype=='block'){
var xhtml = '<div class="userchat-sticker"><img title="['+pack+':'+icon_title+']" src="'+userchat_domain+'smile/'+pack+'/'+pic+'" /></div>';
} else {
var xhtml = '<img title="['+pack+':'+icon_title+']" src="'+userchat_domain+'smile/'+pack+'/'+pic+'" />';
}
ntext = ntext.replace('['+words[i]+']', xhtml);
}

else {ntext = ntext;}

}

return ntext;
}

function userchat_replaceAll(str, find, replace) {
  var i = str.indexOf(find);
  if (i > -1){
    str = str.replace(find, replace); 
    i = i + replace.length;
    var st2 = str.substring(i);
    if(st2.indexOf(find) > -1){
      str = str.substring(0,i) + userchat_replaceAll(st2, find, replace);
    }       
  }
  return str;
}


function userchat_bytes(bytes,decimals) {
   if(bytes == 0) return '0 Byte';
   var k = 1024;
   var dm = decimals + 1 || 3;
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
   var i = Math.floor(Math.log(bytes) / Math.log(k));
   return (bytes / Math.pow(k, i)).toPrecision(dm) + ' ' + sizes[i];
}

function userchat_updater(){
userchat_check_offline();
var status = jQuery.jStorage.get(userchat_cid+'_status', userchat_initial_status);
var xtime = parseInt(jQuery.jStorage.get(userchat_cid+'_updated', userchat_update_timer));

if(xtime<=0){
userchat_debug('Synchronising...'+xtime, 'brown');
jQuery.jStorage.set(userchat_cid+"_updated", userchat_update_timer, {TTL: userchat_cache_expire});
if(status=='online'){
/* dequeue messages to send */
var msgs = [];
jQuery(".userchat-ready-post").each(function(i){
var xuid = jQuery(this).closest('.userchat-box').attr('id');
var uid = xuid.replace('userchat-box-','');
var umsg = jQuery(this).find('.userchat-cmt').text();
jQuery(this).find('.userchat-cmt').html(userchat_parse_text(umsg));
jQuery(this).removeClass('userchat-ready-post').addClass('userchat-sent-post');
msgs.push({name: uid, value: umsg});
});

jQuery.post( userchat_domain+"userchat-functions.php",{curr_user:userchat_current_user, list_mode:userchat_list_mode, method:'updater', mdata:msgs}, function( data ) {
//userchat_alert(data);
var json = jQuery.parseJSON(data);
utime = userchat_date(json.time);
jQuery('.userchat-sent-post .userchat-cmt-pic').attr('title','You posted on '+utime);
jQuery('.userchat-sent-post').removeClass('userchat-sent-post');
jQuery('.userchat-status').attr('class','userchat-status userchat-offline');

/* Marking as online-offline-away */
for(var i=0;i<json.total;++i){
jQuery('.userchat-user[uid="'+json.data[i].uid+'"]').html('<img class="userchat-user-pic" src="'+userchat_domain+'userpics/'+json.data[i].pic+'.jpg" /><h5 class="userchat-user-name">'+json.data[i].name+'</h5>'+userchat_color_status(json.data[i].userchat, json.time, json.data[i].device)+'<p class="userchat-clear"></p>');
}

/* Putting messages into boxes */
for(var i=0;i<json.totalm;++i){
if(jQuery('#userchat-box-'+json.msgs[i].xfrom).length==0){
userchat_create_box(json.msgs[i].xfrom);
}

//var mtext = userchat_parse_text(json[i].xfrom);
var mtext = userchat_parse_text(json.msgs[i].msg);
var uname = jQuery('.userchat-users li[uid="'+json.msgs[i].xfrom+'"] .userchat-user-name').text();
var upic = jQuery('.userchat-users li[uid="'+json.msgs[i].xfrom+'"] .userchat-user-pic').attr('src');
jQuery('title').text('NEW - '+uname);
jQuery('#userchat-box-'+json.msgs[i].xfrom+' .userchat-box-comments').append('<div class="userchat-cmt-left" sent="'+json.msgs[i].sent+'"><img src="'+upic+'" title="'+uname+' on '+json.msgs[i].sent+'" class="userchat-cmt-pic"><div class="userchat-cmt-pin"></div><div class="userchat-cmt">'+mtext+'</div><p class="userchat-clear"></p></div>');
jQuery('#userchat-box-'+json.msgs[i].xfrom+' .userchat-box-comments').scrollTop(jQuery('#userchat-box-'+json.msgs[i].xfrom+' .userchat-box-comments').prop( "scrollHeight" ));
jQuery('#userchat-box-'+json.msgs[i].xfrom+' .userchat-box-comments').perfectScrollbar('update');
}

jQuery('.userchat-bubble').attr('updated', userchat_update_timer);
jQuery('.userchat-bubble').attr('ltime', json.time);
userchat_debug('Synchronising completed.', 'brown');
userchat_debug(''+data, 'brown');

/* displaying friend requests */
var fcount = parseInt(jQuery('.userchat-bubble').attr('xf'));
if(fcount!=json.totreq && json.totreq!=0){

var thtml = '';
for(var z=0;z<json.totreq;z++){
thtml = thtml + '<div class="userchat-list-user"><div class="userchat-list-left"><img src="'+userchat_domain+'userpics/'+json.req[z].pic+'.jpg"></div><div class="userchat-list-right"><div class="userchat-list-name">'+json.req[z].name+'</div><div data-uid="'+json.req[z].uid+'" class="userchat-button userchat-faccept">Accept</div> <div data-uid="'+json.req[z].uid+'" class="userchat-button userchat-freject">Reject</div></div></div>';
}
var xonclick = 'userchat_show_requests()';
jQuery('.userchat-bubble').attr('xf',json.totreq);
jQuery('#userchat-freq').html(json.totreq);
if(jQuery('#phpl-alert-freq').length==0){
userchat_confirm('You have <b>'+json.totreq+' contact requests</b>. Do you want to manage them?', xonclick, 'freq');
}

jQuery('#userchat-freq-data').html(thtml);
}

jQuery.jStorage.set(userchat_cid+"_online", data, {TTL: userchat_cache_expire});
if(json.totreq==0 && json.totalm==0 && msgs.length==0){
userchat_debug('not saving the cache, nothing new', 'black');
} else {
userchat_cache_save('data', '.userchat-ctr');
}

setTimeout("userchat_updater()", 1000);
});
} else {
userchat_debug('could not sync. You are offline', 'red');
setTimeout("userchat_updater()", 1000*userchat_update_timer);
}
} else {
jQuery.jStorage.set(userchat_cid+"_updated", (xtime-1), {TTL: userchat_cache_expire});
//jQuery('.userchat-bubble').attr('updated', xtime-1);
setTimeout("userchat_updater()", 1000);
}
}

function userchat_cache_restore(id, elem){
var cache_data = jQuery.jStorage.get(userchat_cid+"_"+id, 'no-data');
userchat_old_cache = cache_data;
//alert(cache_data.toSource());
jQuery(elem).replaceWith(cache_data);
userchat_cache_update_scrollbars();
userchat_debug('cache restored to <b>'+elem+'</b>', 'blue');
}

function userchat_cache_save(id, elem){
var savedata = jQuery(elem)[0].outerHTML;
userchat_old_cache = savedata;
jQuery.jStorage.set(userchat_cid+"_"+id, savedata, {TTL: userchat_cache_expire});
userchat_debug('cache saved for <b>'+elem+'</b>', 'blue');
}

function userchat_write_cache(){
var ctime = Math.round(+new Date()/1000);
var userchat_time = jQuery.jStorage.get(userchat_cid+"_time", 'no-data');

if(userchat_time=='no-data' || (parseInt(userchat_time)-ctime)<=0){
jQuery.jStorage.set(userchat_cid+'_time', (ctime+5), {TTL: userchat_cache_expire});
var userchat_uid = jQuery.jStorage.get(userchat_cid+"_uid", 'no-data');
if(userchat_uid!=userchat_current_user){document.location.reload();} else {
userchat_debug('userchat_uid='+userchat_uid+', userchat_current_user='+userchat_current_user, 'red');
var savedata = jQuery('.userchat-ctr').html();
jQuery.jStorage.set(userchat_cid+'_data', savedata, {TTL: userchat_cache_expire});
userchat_debug('Saved data to cache.', 'blue');
}
} else {
var cache_data = jQuery.jStorage.get(userchat_cid+"_data", 'no-data');
jQuery('.userchat-ctr').html(cache_data);
userchat_debug('ignoring cache write.', 'blue');
}


}

function userchat_write_cache_old(){
var ctime = userchat_time();
var userchat_time = jQuery.jStorage.get(userchat_cid+"_time", 'no-data');

if(userchat_time=='no-data'){
jQuery.jStorage.set(userchat_cid+'_time', (ctime+5), {TTL: userchat_cache_expire});
}


var userchat_uid = jQuery.jStorage.get(userchat_cid+"_uid", 'no-data');
//if(userchat_uid=='no-data'){document.location.reload();}

if(userchat_uid!=userchat_current_user){document.location.reload();} else {
userchat_debug('userchat_uid='+userchat_uid+', userchat_current_user='+userchat_current_user, 'red');
var savedata = jQuery('.userchat-ctr').html();
jQuery.jStorage.set(userchat_cid+'_data', savedata, {TTL: userchat_cache_expire});
userchat_debug('Saved data to cache.', 'blue');
setTimeout("userchat_write_cache()", userchat_cache_write_interval);
}
}

function userchat_cache_update_scrollbars(){
jQuery( ".userchat-box" ).each(function(){
var xuid = jQuery(this).attr('id');
jQuery('#'+xuid+' .userchat-box-smiley-icons').removeClass('ps-container,ps-active-y');
jQuery('#'+xuid+' .userchat-box-smiley-icons').removeAttr('data-ps-id');
jQuery('#'+xuid+' .userchat-box-smiley-icons .ps-scrollbar-x-rail').remove();
jQuery('#'+xuid+' .userchat-box-smiley-icons .ps-scrollbar-y-rail').remove();


jQuery('#'+xuid+' .userchat-box-smiley-icons').perfectScrollbar();
jQuery('#'+xuid+' .userchat-box-comments').removeAttr('data-ps-id');
jQuery('#'+xuid+' .userchat-box-comments').removeClass('ps-container,ps-active-y');
jQuery('#'+xuid+' .userchat-box-comments .ps-scrollbar-x-rail').remove();
jQuery('#'+xuid+' .userchat-box-comments .ps-scrollbar-y-rail').remove();

jQuery('#'+xuid+' .userchat-box-comments').perfectScrollbar();
jQuery('#'+xuid+' .userchat-box-comments').scrollTop(jQuery('#'+xuid+' .userchat-box-comments').prop( "scrollHeight" ));
});
}

function userchat_user_list(){
var xhtml = '';
jQuery.post(userchat_domain+"userchat-functions.php", {curr_user:userchat_current_user, list_mode:userchat_list_mode, method:'full_user_list'}, function(data) {
var json = jQuery.parseJSON(data);
for(var i=0;i<json.total;i++){
newhtml = '<div class="userchat-list-user">\
<div class="userchat-list-left"><img src="'+userchat_domain+'userpics/'+json.users[i].pic+'.jpg"></div>\
<div class="userchat-list-right"><div class="userchat-list-name">'+json.users[i].name+'</div>\
<div class="userchat-button userchat-list-add-contact" data-uid="'+json.users[i].id+'">Add to Contacts</div>\
</div>\
</div>';
xhtml = xhtml + newhtml;
}

if(json.total==1){xhtml='<i>There are no people remaining to be added to your list.</i>'}

jQuery('.userchat-people-list').html(xhtml+'<div class="userchat-clear"></div>');

setTimeout("userchat_remove_current_user_from_list()", 100);

});
}

function userchat_remove_current_user_from_list(){
var cuser = jQuery('.userchat-bubble').attr('xid');
jQuery('[data-uid="'+cuser+'"]').closest('.userchat-list-user').remove();
}


function userchat_find(a){
searchWord=a;
if(a=='Search users'){ jQuery('#userchat-key').val(''); }
var gdele0='';
var gdele='';
var gdelex='';
if(searchWord.length>=1){
jQuery('.userchat-users li.userchat-user').each(function(i,data){
text = jQuery(this).find('.userchat-user-name').text();
xhtml = jQuery(this).html();
var attr2 = jQuery(this).attr('uid');
var attr1 = jQuery(this).find('.userchat-user-pic').attr('src');
attr3 = jQuery(this).find('.userchat-status').attr('class');
attr3 = attr3.replace('userchat-status', '');
attr3 = attr3.replace(' ', '');
attr4 = jQuery(this).find('.userchat-status').html();

jQuery(this).remove();
newHTML=text.replace(RegExp(searchWord), '<b class="userchat-found">'+searchWord+'</b>');
if(attr3=='userchat-online'){
gdele0=gdele0+'<li class="userchat-user" uid="'+attr2+'"><img src="'+attr1+'" class="userchat-user-pic"><h5 class="userchat-user-name">'+newHTML+'</h5><p class="userchat-status '+attr3+'">'+attr4+'</p><p class="userchat-clear"></p></li>';
} else {
if(text.match(RegExp(searchWord,'i'))){
gdele=gdele+'<li class="userchat-user" uid="'+attr2+'"><img src="'+attr1+'" class="userchat-user-pic"><h5 class="userchat-user-name">'+newHTML+'</h5><p class="userchat-status '+attr3+'">'+attr4+'</p><p class="userchat-clear"></p></li>';
}else{
gdelex=gdelex+'<li class="userchat-user" uid="'+attr2+'"><img src="'+attr1+'" class="userchat-user-pic"><h5 class="userchat-user-name">'+newHTML+'</h5><p class="userchat-status '+attr3+'">'+attr4+'</p><p class="userchat-clear"></p></li>';
}
}
});
jQuery('.userchat-users').append(gdele0);
jQuery('.userchat-users').append(gdele);
jQuery('.userchat-users').append(gdelex);
}else{
userchat_sort_list('.userchat-users','li');
}
}


function userchat_sort_list(a,b){
var mylist = jQuery(a);
var listitems = mylist.children(b).get();
listitems.sort(function(a, b) {
var compA = jQuery(a).text().toUpperCase();
var compB = jQuery(b).text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
jQuery.each(listitems, function(idx, itm) { mylist.append(itm); });
}

function clear_browser_cache(){
userchat_confirm('<b>Are you sure to clear your browser\'s userchat cache?</b>', 'userchat_reset()');
}

function userchat_delete_pack(pack){
userchat_confirm('<b>Are you sure to delete this pack?</b><br /><br />You should know that you can instead disable it by unchecking. This will remove this icon pack permanently by physically deleting its files.', 'userchat_pack_deleted(\''+pack+'\')');
}

function userchat_pack_deleted(pack){
document.location.href = 'admin.php?page=userchat_settings.php&delpack='+pack;
}

function userchat_reset(){
jQuery.jStorage.flush();
document.location.reload();
}

function userchat_cache_restore_service(){
var xydata = jQuery.jStorage.get(userchat_cid+'_online', "no-data");
//alert(xydata);
if(xydata!='no-data'){
var json = jQuery.parseJSON(xydata);
for(var i=0;i<json.total;i++){
//alert(xdata[i].pic);
jQuery('.userchat-user[uid="'+json.data[i].uid+'"]').html('<img class="userchat-user-pic" src="'+userchat_domain+'userpics/'+json.data[i].pic+'.jpg" /><h5 class="userchat-user-name">'+json.data[i].name+'</h5>'+userchat_color_status(json.data[i].userchat, json.time, json.data[i].device)+'<p class="userchat-clear"></p>');
}
}

var new_cache = jQuery.jStorage.get(userchat_cid+'_data', "no-data");
if(new_cache!=userchat_old_cache && new_cache!='no-data'){
userchat_cache_restore('data', '.userchat-ctr');
userchat_debug('cache restore success', 'green');
} else {
userchat_debug('cache restore ignored', 'gray');
}
setTimeout("userchat_cache_restore_service()", 2000);
}

// jQuery listeners
jQuery(document).ready(function(){


jQuery.jStorage.set(userchat_cid+"_uid", userchat_current_user);
jQuery.jStorage.setTTL(userchat_cid+"_uid", userchat_cache_expire);


if(jQuery('.userchat-people-list').length!=0){
userchat_user_list();
}

if(!userchat_enable_cache){jQuery.jStorage.flush();}
var userchat_cached = jQuery.jStorage.get(userchat_cid+'_data', "no-data");
if(userchat_cached=='no-data'){
userchat_generate_ui();
} else {
userchat_load_smiley_sets();
if(jQuery('.userchat-ctr').length==0){
jQuery('body').append('<div class="userchat-ctr"></div>');
}

userchat_old_cache = userchat_cached;
userchat_cache_restore('data', '.userchat-ctr');
userchat_cache_restore_service();

userchat_debug('Loaded data from cache.', 'green');
setTimeout("userchat_cache_update_scrollbars()", 100);
userchat_updater();
userchat_check_offline();
}

userchat_debug('Initial browser width : '+jQuery(window).width()+'px', 'green');

jQuery('body').on('click', '.userchat-box-smiley', function(){
jQuery(this).closest('.userchat-box-write').find('.userchat-box-smiley-ctr').toggleClass('userchat-visible');
});

jQuery('body').on('click', '.userchat-list-header', function(){
jQuery(this).closest('.userchat-list-ctr').toggleClass('userchat-list-hidden');
});

jQuery('body').on('click', '.userchat-remove-contact', function(){
var uuid = jQuery(this).closest('.userchat-box').attr('id');
var uid = uuid.replace('userchat-box-','');
userchat_confirm('<b>Are you sure to remove this person from your contacts?</b><br /><br />To remove, press continue else press Cancel.', 'userchat_contact_removed(\''+uid+'\')');
});

jQuery('body').on('click', '.userchat-cmt-date a', function(){
var xuid = jQuery(this).closest('.userchat-box').attr('id');
var uid = xuid.replace('userchat-box-','');
userchat_old_msgs(uid);
});


jQuery('body').on('click', '.userchat-clear-data', function(){
var xuid = jQuery(this).closest('.userchat-box').attr('id');
var uid = xuid.replace('userchat-box-','');
var xhtml = '<b>Are you sure to clear the history with this person?</b><br /><br />history will never be deleted from server, it will be just deleted from your account. Only admin can delete the messages permanently. Press continue if you want to clear the history else press cancel.';
var xclick = 'userchat_clear_history(\''+uid+'\')';
userchat_confirm(xhtml,xclick);
});



jQuery('body').on('click', '.userchat-theme-chooser li', function(){
var light = jQuery(this).attr('light');
var dark = jQuery(this).attr('dark');
jQuery('#userchat-color-apply').remove();
var xhtml = '<style id="userchat-color-apply" type="text/css">\
.userchat-box-top, .userchat-button, .phpl-alert-box-top{background-color:'+dark+';}\
.userchat-box{border-left: 1px solid '+dark+';border-right: 1px solid '+dark+';}\
.userchat-box-focus .userchat-box-top, .userchat-box:hover .userchat-box-top{background-color:'+light+';}\
.userchat-box-focus, .userchat-box:hover {border-left: 1px solid '+light+';border-right: 1px solid '+light+';}\
.userchat-submenu li {background-color: '+dark+';border-bottom: 1px solid '+light+';}\
.userchat-box-icon:hover, .userchat-box-settings:hover {background-color: '+dark+';}\
.userchat-submenu li:hover, .phpl-alert-bg {background-color: '+light+';}\
.userchat-pack-select, .userchat-cmt-right .userchat-cmt, .userchat-button:hover, .userchat-button:active{background-color: '+light+';}\
</style>';
jQuery('.userchat-ctr').append(xhtml);
});


jQuery('body').on('click', '.userchat-user', function(){
var uid = jQuery(this).attr('uid');
userchat_create_box(uid);
});


jQuery('body').on('click', '.userchat-pack-select li', function(){
var bid = jQuery(this).closest('.userchat-box').attr('id');
var cname = jQuery(this).attr('class');
jQuery('#'+bid+' .userchat-pack-select li').removeClass('userchat-pack-active-li');
jQuery(this).addClass('userchat-pack-active-li');
jQuery('#'+bid+' .userchat-box-smiley-icons ul').hide();
jQuery('#'+bid+' .'+cname+'-data').show();
jQuery('#'+bid+' .userchat-box-smiley-icons').perfectScrollbar('update');
});

jQuery('body').on('click', '.userchat-box-smiley', function(){
jQuery(this).closest('.userchat-box').find('.userchat-box-smiley-ctr').toggle("medium");
});

jQuery('body').on('click', '.userchat-offline-icon', function(){
if(userchat_current_user == '0'){
userchat_confirm('<b>You must be logged in to use online chat features.</b><br /><br />Redirect to login page?', 'userchat_login_redirect()');
} else {
jQuery.jStorage.set(userchat_cid+"_status", "online");
jQuery.jStorage.setTTL(userchat_cid+"_status", userchat_cache_expire);
userchat_check_offline();
}
});

jQuery('body').on('click', '.userchat-go-offline', function(){
jQuery.jStorage.set(userchat_cid+"_status", "offline");
jQuery.jStorage.setTTL(userchat_cid+"_status", userchat_cache_expire);
userchat_check_offline();
});

jQuery('body').on('click', '.userchat-bbl-close', function(){
var uid = jQuery(this).closest('li').attr('uid');
jQuery('#userchat-box-'+uid).fadeOut("fast", function(){
jQuery('#userchat-box-'+uid).remove();
jQuery('.userchat-bbl-list li[uid="'+uid+'"]').remove();
setTimeout("userchat_box_reposition()", 10);
});
});

jQuery('body').on('click', '.userchat-box-close', function(){
jQuery(this).closest('.userchat-box').fadeOut("fast", function(){
jQuery(this).remove();
userchat_box_reposition();
});
});

jQuery('body').on('click', '.userchat-bubble b', function(){
jQuery(this).parent().find('.userchat-bbl-list').toggle();
});

jQuery('body').on('click', '.userchat-bbl-user', function(){
var uid = jQuery(this).attr('uid');
userchat_show_box(uid);
});


jQuery('body').on('focus', '.userchat-box-write textarea', function(){
jQuery('.userchat-box').removeClass('userchat-box-focus');
jQuery(this).closest('.userchat-box').addClass('userchat-box-focus');
});

jQuery('body').on('blur', '.userchat-box-write textarea', function(){
jQuery('.userchat-box').removeClass('userchat-box-focus');
});

jQuery('body').on('click', '.userchat-box-uname', function(){
jQuery(this).closest('.userchat-box').toggleClass('userchat-box-min');
userchat_cache_save('data', '.userchat-ctr');
});


jQuery(window).resize(function() {
userchat_debug('Browser width reset to : '+jQuery(window).width()+'px', 'brown');
jQuery('.userchat-list').perfectScrollbar('update');
userchat_box_reposition();
if(jQuery(window).width() > 1200){
jQuery('.userchat-list-ctr').removeClass('userchat-list-hidden');
} else {
jQuery('.userchat-list-ctr').addClass('userchat-list-hidden');
}

});

jQuery('body').on('click', '.userchat-faccept', function(){
var fid = jQuery(this).attr('data-uid');
userchat_acceptf(fid);
});

jQuery('body').on('click', '.userchat-freject', function(){
var fid = jQuery(this).attr('data-uid');
userchat_rejectf(fid);
});

jQuery('body').on('click', '.userchat-options-icon, .userchat-theme-chooser li', function(){
jQuery('.userchat-options-ctr').fadeToggle(300);
setTimeout("userchat_cache_save(\'data\', \'.userchat-ctr\')", 1000);
});


jQuery('body').on('keyup', '.userchat-box-write textarea', function(event){
var content = jQuery.trim(this.value);
content = jQuery('<div />').text(content).html();
//alert(content);
var xid = jQuery(this).closest('.userchat-box').attr('id');
var to_id = xid.replace('userchat-box-', '');
if(event.keyCode == 13 && !event.shiftKey){
if(content!='' && content!='Type and press Enter to send'){
userchat_queue_message(content, to_id);
}
jQuery(this).val('');
}
});

jQuery('body').on('keyup', '#userchat-key', function(event){
var content = this.value;
userchat_find(content);
});

jQuery('body').on('click', '.userchat-box-smiley-icons li img', function(){
var box_id = jQuery(this).closest('.userchat-box').attr('id');
var code = jQuery(this).attr('title');
jQuery('#'+box_id+' textarea').userchatInserttext(code);
});

jQuery('body').on('click', '.userchat-list-add-contact', function(){
var uid = jQuery(this).attr('data-uid');
userchat_contact_request(uid);
});

jQuery('body').on('click', '.userchat-file-lightbox', function(e){
e.preventDefault();
var xurl = jQuery(this).attr('href');
var xtitle = jQuery(this).attr('title');
userchat_alert('<img style="width:100%;" src="'+xurl+'" />', xtitle);
});



//================================= alert box =================================
jQuery('body').on('click', '.phpl-alert-close, .phpl-alert-box-top-close', function(){
var xid = jQuery(this).closest('.phpl-alert-ctr').attr('id');
userchat_close_alert(xid);
});
//================================= alert box =================================


});


//================================= caret code begin =================================
jQuery.fn.extend({
userchatInserttext: function(myValue){
  return this.each(function(i) {
    if (document.selection) {
      //For browsers like Internet Explorer
      this.focus();
      var sel = document.selection.createRange();
      sel.text = myValue;
      this.focus();
    }
    else if (this.selectionStart || this.selectionStart == '0') {
      //For browsers like Firefox and Webkit based
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
      this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
      this.focus();
      this.selectionStart = startPos + myValue.length;
      this.selectionEnd = startPos + myValue.length;
      this.scrollTop = scrollTop;
    } else {
      this.value += myValue;
      this.focus();
    }
  });
}
});
//================================= caret code ends =================================


function userchat_check_offline(){
var userchat_status = jQuery.jStorage.get(userchat_cid+'_status', userchat_initial_status);
if(userchat_status=='offline'){
jQuery('html').removeClass('userchat-html');
jQuery('.userchat-options-ctr').fadeOut();
jQuery('.userchat-inner-ctr').hide();
jQuery('.userchat-offline-icon').show();
}
if(userchat_status=='online'){
jQuery('html').addClass('userchat-html');
jQuery('.userchat-inner-ctr').show();
jQuery('.userchat-offline-icon').hide();
}
}

function userchat_offline(forced){
userchat_debug('Going '+forced, 'red');
if(forced===undefined){
var userchat_status = jQuery.jStorage.get(userchat_cid+'_status', userchat_initial_status);
} else {
var userchat_status = forced;
}

if(userchat_status=='offline'){
jQuery('html').removeClass('userchat-html');
jQuery('.userchat-options-ctr').fadeOut();
jQuery('.userchat-offline-icon').attr('status', 'offline');
jQuery('.userchat-inner-ctr').hide();
jQuery('.userchat-offline-icon').show();
}
if(userchat_status=='online'){
jQuery('html').addClass('userchat-html');
jQuery('.userchat-offline-icon').attr('status', 'online');
jQuery('.userchat-inner-ctr').show();
jQuery('.userchat-offline-icon').hide();
}
}


function userchat_login_redirect(){
var url      = window.location.href;
document.location.href = userchat_admin_url.replace('wp-admin/', '')+'wp-login.php?redirect_to='+url;
}


function userchat_show_requests(){
var xhtml = jQuery('#userchat-freq-data').html();
if(jQuery('#userchat-freq-data').text()==''){xhtml = 'There are <b>no new contact requests</b> to display!';}
userchat_alert(xhtml, 'Contact requests..');
}

function userchat_queue_message(comment, to_id){
if(jQuery('#userchat-box-'+to_id+' .userchat-ready-post').length==1){
jQuery('#userchat-box-'+to_id+' .userchat-ready-post .userchat-cmt').append("\n"+comment);
} else {
var xhtml = '<div class="userchat-cmt-right userchat-ready-post"><img src="'+jQuery('.userchat-bubble').attr('xpic')+'" title="You Posted this just now" class="userchat-cmt-pic"><div class="userchat-cmt-pin"></div><div class="userchat-cmt">'+comment+'</div><p class="userchat-clear"></p></div>';
jQuery('#userchat-box-'+to_id+' .userchat-box-comments').append(xhtml);
}
jQuery('#userchat-box-'+to_id+' .userchat-box-comments').scrollTop(jQuery('#userchat-box-'+to_id+' .userchat-box-comments').prop( "scrollHeight" ));
jQuery('#userchat-box-'+to_id+' .userchat-box-comments').perfectScrollbar('update');
}

function userchat_upload_status(btntxt, xhtml){
jQuery('.userchat-upload-progress').html(btntxt);
jQuery('.userchat-upload-text').html(xhtml);
}

function userchat_clear_history(uid){
jQuery.post(userchat_domain+"userchat-functions.php", {curr_user:userchat_current_user, method:'clear_history', user:uid}, function(data) {
jQuery('#userchat-box-'+uid+' .userchat-box-comments').html('<div class="userchat-cmt-date"><i>- No more old messages to display -</i></div>');
jQuery('#userchat-box-'+uid+' .userchat-box-comments').perfectScrollbar('update');
userchat_cache_save('data', '.userchat-ctr');
});
}

function userchat_upload_alert(type){
var xhtml = '<div class="userchat-upload-text">Please wait. Processing....</div><br /><br /><div class="userchat-button userchat-upload-progress">Please Wait</div><iframe height="32" width="80" id="userchat-upload-frame" scrolling="no" border="0" frameborder="0" src="'+userchat_domain+'userchat-upload.php?type='+type+'&userid='+userchat_current_user+'">Loading....</iframe>';
userchat_alert(xhtml, 'Upload file');
}