var mtime = 30000; // 30 sec
var url = '/gwtlog';
var nt = (new Date()).getTime();
var functions = ['getLiveNotif', /*'uOn',*/  'gGuests', 'getLiveGr'];
var last_c = [];


/* checking function */
function g(data) {

   var send = jAjax(url, 'post', data + '&view_as=json&token=' + nt);

   return send;

}

/** generate timer **/
function stitime() {
    var min = 1,
        max = 9;
    return mtime + Math.floor(Math.random() * (max - min + 1)) + min;
}


// update online status
function uOn() {

    var online_card =
        '<div class="online-fr_i" data-uonff="true" data-friend-id="%s" data-int-on="%s" data-onl="1">' +
        '<a href="/user/%s" class="online-fr_link" hrefattr="true"></a>' +
        '<div class="ucard-v __xxs __h">' +
        '<div class="section">' +
        '<div class="photo"><img class="photo_img" src="/getPhoto?p=%s&sz=small&g=%s" alt="%s" width="32" height="32"></div>' +
        '<span class="ic-online"></span></div>' +
        '<div class="caption">' +
        '<div class="online-fr_name ellip">%s</div>' +
        '<a title="Send a message" href="javsacript:void(0);" class="online-fr_msg">' +
        '</a>' +
        '</div>' +
        '</div>' +
        '</div>';


    var friendCont = ga('#online-fr_cards #fcards_hide_f_sch');

   var checkFriendLength = function(){
   var uCount = friendCont.children().length;

   if(uCount > online_hook_limit) friendCont.children(':last').remove();
 

   };

    var setUOnOff = function(o,uid,o_ago){
    var friend = friendCont.find('[data-friend-id="' + uid + '"]');
			if(o){

				friend.find('.ic-offline').addClass('ic-online');
				friend.find('.online_fr_status').html('<i class="ic-online"></i><span>'+lang.active_now+'</span>');

				if(friend.attr('data-uonff')){

					friend.removeClass('_on__highlight').addClass('_on__highlight');
							setTimeout(function(){
										friend.removeClass('_on__highlight');
								},7500);
					}
						friend.removeAttr('data-uonff');
				}else {
					friend.attr('data-uonff','true').find('.ic-online').addClass('ic-offline');
					friend.find('.online_fr_status').html('<span>'+o_ago+'</span>');
				}

						checkFriendLength();

	}
	
    var onOffU = function(uid, Uint, o, o_ago, callback) {


            if (callback) {
                callback(uid);
            }

	    setUOnOff(o,uid,o_ago);



            friendCont.find('[data-friend-id="' + uid + '"]').attr('data-int-on', Uint);


        }
        // alert when a new user is online
    var notifNewOnUs = function(i) {
        var $body = ga('body');
/*
        var new_us = $('<section class="new_fr_on">' +
            '<div class="us_n_details">' +
            '<A href="/profile?q=' + i + '">' +
            '<div class="us_new_photo">' +
            '<img src="/getPhoto?p=' + p + '&sz=small&token=' + nt + '" />' +
            '</div>' +
            '<div class="n_us_fname">' + n + '</div></a></div>' +
            '</section>');
*/
       // $body.append(new_us);

     var user = friendCont.find('[data-friend-id="'+i+'"]');
  /*  user.addClass('__right_now');
    user.focus();
setTimeout(function(){
    user.removeClass('__right_now');
},500);*/


    }

  
    var send = g('cmd=online');

    send.done(function(r) {


        var r = validateJson(r);

        if (r['response'] == '1') {
            var uData = validateJson(r['data']);

	    friendCont.find('.ic-online').removeClass('ic-online').addClass('ic-offline');	
            for (var i = 0; i < uData.length; i++) {

		if( friendCont.find('[data-friend-id="'+uData[i].id+'"]').length <= 0) {
                   friendCont.prepend(jprintf(online_card,uData[i].id,uData[i].online_int,uData[i].id,uData[i].photo,uData[i].gender,uData[i].fullname,uData[i].fullname));
		   setUOnOff(1,uData[i].id);
		   up_href();
		}
                else{

		onOffU(uData[i].id, uData[i].online_int, uData[i].online, uData[i].online_ago);
		}



            }
		
		if(ga('#fcards_hide_f_sch').children().length){
            tinysort(friendCont.children(), {
                data: 'int-on',
                order: 'desc',
                ignoreDashes: true
		});
		}
		
        }

        setTimeout(uOn, stitime()/3);
    });

}

/** bubble **/
function b(c) {

    var n_bubble = '<div class="lnavMenuCount zoomIn animated">+' + c + '</div>';
	
	
	/* '<div class="toolbar_nav_notif __header">' +
        '<div id="counter_ToolbarDiscussions" class="notifications zoomIn animated">' +
        '<div class="counterText">' + c + '</div>' +
        '</div></div>';*/

    return n_bubble;
}

/* check for notifications */
function getLiveNotif() {

    var send = g('cmd=notifications');

    send.done(function(r) {

        var d = validateJson(r);

        if (d['response'] == '1' && d['count'] > 0) {

			
			if(d.count !== last_c.notif)
            ga('.notif_space').each(function(){
				ga(this).html( ga(this).hasClass('tophead') ? '<span>' + d['count'] +'</span>': b(d['count']));
			});
			last_c.notif = d.count;

        } else {
			ga('.notif_space').empty();
		}

        setTimeout(getLiveNotif, stitime());
    });

}
/* check for grades */
function getLiveGr() {

    var send = g('cmd=grades');

    send.done(function(r) {

        var d = validateJson(r);


        if (d['response'] == '1' && d['count'] > 0) {

			
			if(d.count !== last_c.grades)
            ga('.gr_notif_space').html(b(d['count']));
		
			last_c.grades = d.count;

        } else {
			ga('.gr_notif_space').empty();
		}

        setTimeout(getLiveGr, stitime());
    });

}
// get guests notif
function gGuests(){

    var send = g('cmd=guests');

    send.done(function(d) {

        var r = validateJson(d);


        if (r['response'] == 1 && r['count'] > 0) {
	
			if( r.count !== last_c.guests )
            ga('.g_notif_space').html(b(r['count']));
			last_c.guests = r.count;
        } else {
			ga('.g_notif_space').empty();
		}

        setTimeout(gGuests, stitime());
    });


}

function startBoot() {
	if(typeof _U == 'undefined') return false;
    for (var i = 0; i < functions.length; i++)
        window[functions[i]](arguments);

}
ga(document).ready(startBoot);


